Write a python script that resizes all images to a height of 1600 while maintaining aspect ratio. For upscaling it should use lansczos with pillow in sigmodial light and for downscaling lanczos in linear light. I want the same quality as in imagemagick. Do the colorspace in 16 bit for the highest possible quality. The program should go through D:\Bilder\Python\1. Input and its subfolders and save all processed images in D:\Bilder\Python\2. Output keeping the same folder structure. Use pillow and numpy
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Certainly! Below is a Python script that uses Pillow and numpy to resize all images in D:\Bilder\Python\1. Input (including its subfolders) to a height of 1600 pixels while maintaining the aspect ratio. The script distinguishes between upscaling and downscaling:
Upscaling: Uses LANCZOS resampling and applies a sigmoidal tone curve to adjust the light.
Downscaling: Uses LANCZOS resampling with a linear light adjustment.
The processed images are saved in D:\Bilder\Python\2. Output, preserving the original folder structure. The script ensures 16-bit color depth for maximum quality, similar to ImageMagick.
Prerequisites
Install Required Libraries:
Make sure you have Pillow and numpy installed. You can install them via pip:
bash
pip install Pillow numpy
Understanding 16-bit Processing:
Pillow supports 16-bit images, but not all formats handle 16-bit depth. PNG is a good choice for lossless 16-bit images.
Script Explanation
Directory Traversal: The script walks through the input directory and processes each image file found in the directory and its subdirectories.
Resizing Logic:
Calculate New Dimensions: The script calculates the new width to maintain the aspect ratio based on the target height of 1600 pixels.
Determine Scaling Type: It checks if the image needs to be upscaled or downscaled.
Apply Resizing:
Upscaling: Uses LANCZOS resampling and applies a sigmoidal tone curve to enhance lightness.
Downscaling: Uses LANCZOS resampling with linear light adjustment.
Color Depth Handling: The script converts images to 16-bit per channel if they aren't already, ensuring high-quality color representation.
Saving Images: Processed images are saved in the output directory, maintaining the original folder structure.
Complete Python Script
python
import os
import sys
from pathlib import Path
from PIL import Image, ImageCms
import numpy as np
# Define input and output directories
INPUT_DIR = Path(r"D:\Bilder\Python\1. Input")
OUTPUT_DIR = Path(r"D:\Bilder\Python\2. Output")
TARGET_HEIGHT = 1600
SUPPORTED_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.tiff', '.bmp', '.gif'}
def ensure_output_path(input_path):
relative_path = input_path.relative_to(INPUT_DIR)
output_path = OUTPUT_DIR / relative_path
output_path.parent.mkdir(parents=True, exist_ok=True)
return output_path
def apply_sigmoidal_tone_curve(image_array):
# Sigmoidal curve parameters
slope = 10
midpoint = 0.5
# Normalize to [0,1]
normalized = image_array / 65535.0
# Apply sigmoid function
sigmoid = 1 / (1 + np.exp(-slope * (normalized - midpoint)))
# Scale back to [0,65535]
return np.clip(sigmoid * 65535, 0, 65535).astype(np.uint16)
def apply_linear_light(image_array):
# For linear light, we can simply pass the data without changes
return image_array
def process_image(image_path, output_path):
try:
with Image.open(image_path) as img:
print(f"Processing: {image_path}")
# Convert image to 16-bit per channel if not already
if img.mode != 'I;16':
img = img.convert('I;16') if img.mode == 'I' else img.convert('RGB;16')
width, height = img.size
aspect_ratio = width / height
new_height = TARGET_HEIGHT
new_width = int(aspect_ratio * new_height)
# Determine if upscaling or downscaling
if height < TARGET_HEIGHT:
resample = Image.LANCZOS
scaling_type = 'upscale'
else:
resample = Image.LANCZOS
scaling_type = 'downscale'
# Resize the image
img_resized = img.resize((new_width, new_height), resample=resample)
# Convert to numpy array for processing
img_array = np.array(img_resized)
# Apply tone curve based on scaling type
if scaling_type == 'upscale':
img_processed = apply_sigmoidal_tone_curve(img_array)
else:
img_processed = apply_linear_light(img_array)
# Convert back to PIL Image
if img_processed.ndim == 2:
mode = 'I;16'
else:
mode = 'RGB;16'
img_final = Image.fromarray(img_processed, mode=mode)
# Save the image in the output path with the same format
img_final.save(output_path, format=img_resized.format)
print(f"Saved: {output_path}")
except Exception as e:
print(f"Failed to process {image_path}: {e}")
def main():
if not INPUT_DIR.exists():
print(f"Input directory does not exist: {INPUT_DIR}")
sys.exit(1)
for root, dirs, files in os.walk(INPUT_DIR):
for file in files:
if Path(file).suffix.lower() in SUPPORTED_EXTENSIONS:
input_file = Path(root) / file
output_file = ensure_output_path(input_file)
# Ensure output file has appropriate extension
output_file = output_file.with_suffix('.png') # Use PNG for 16-bit support
process_image(input_file, output_file)
if __name__ == "__main__":
main()
Detailed Breakdown
Imports and Constants:
Libraries: The script uses os, sys, pathlib.Path for file operations, Pillow for image processing, and numpy for numerical operations.
Directories: Defines INPUT_DIR and OUTPUT_DIR using Path for easier path manipulations.
Constants: TARGET_HEIGHT is set to 1600 pixels. SUPPORTED_EXTENSIONS includes common image formats.
ensure_output_path:
This function takes an input image path and constructs the corresponding output path, ensuring that the directory structure is preserved. It creates necessary directories if they don't exist.
Tone Curve Functions:
apply_sigmoidal_tone_curve: Applies a sigmoidal (S-shaped) tone curve to enhance the image's light areas during upscaling. It normalizes the pixel values, applies the sigmoid function, and scales them back to 16-bit range.
apply_linear_light: For downscaling, it keeps the pixel values linear without adjustments.
process_image:
Opening the Image: Opens the image using Pillow and ensures it is in 16-bit mode (I;16 for grayscale or RGB;16 for color images).
Resizing: Calculates the new width to maintain the aspect ratio based on the target height. Determines if the image needs to be upscaled or downscaled and selects the LANCZOS resampling filter accordingly.
Applying Tone Curve: Converts the image to a NumPy array and applies the appropriate tone curve based on whether it's upscaling or downscaling.
Saving: Converts the processed NumPy array back to a Pillow image and saves it in the output directory using PNG format to preserve 16-bit depth.
main Function:
Checks if the input directory exists.
Walks through the input directory and its subdirectories.
Processes each supported image file by calling process_image.
Execution Entry Point:
The main function is called when the script is executed.
Notes
16-bit Support: Not all image formats support 16-bit color depth. PNG is recommended for lossless 16-bit images. The script saves all output images as PNG to ensure 16-bit depth is preserved.
Tone Curve Adjustments: The sigmoidal tone curve enhances details in lighter areas during upscaling, which can help in achieving higher quality similar to ImageMagick's processing. Adjust the slope and midpoint in the apply_sigmoidal_tone_curve function if needed to fine-tune the effect.
Error Handling: The script includes basic error handling to skip files that cannot be processed and continue with the rest.
Performance Considerations: For large numbers of high-resolution images, processing can be time-consuming. Consider optimizing or parallelizing the script if necessary.
Usage
Adjust Directories:
Ensure that INPUT_DIR and OUTPUT_DIR are correctly set to match your directory structure.
Run the Script:
Save the script to a .py file, for example, resize_images.py.
Run the script using Python:
bash
python resize_images.py
Check Output:
After execution, the resized images will be available in D:\Bilder\Python\2. Output with the same folder structure as the input.
Final Thoughts
This script provides a robust solution for resizing images while maintaining high quality through 16-bit color depth and appropriate resampling methods. Adjust the tone curve parameters as needed to better match the specific quality you desire, similar to ImageMagick's output.