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 accomplishes your requirements using Pillow and NumPy. It processes all images in D:\Bilder\Python\1. Input, resizes them to a height of 1600 pixels while maintaining the aspect ratio, uses Lanczos filtering with appropriate color space conversions, and saves the output images in D:\Bilder\Python\2. Output, preserving the folder structure.
Please note that handling precise color space conversions and matching ImageMagick's quality exactly can be complex due to differences in how libraries implement certain functions. However, this script approximates the requested functionality using standard techniques in Pillow and NumPy.
python
import os
from PIL import Image
import numpy as np
input_dir = r'D:\Bilder\Python\1. Input'
output_dir = r'D:\Bilder\Python\2. Output'
def srgb_to_linear(srgb):
# Convert sRGB values to linear RGB
srgb = np.clip(srgb, 0, 1)
linear = np.where(srgb <= 0.04045,
srgb / 12.92,
((srgb + 0.055) / 1.055) ** 2.4)
return linear
def linear_to_srgb(linear):
# Convert linear RGB values to sRGB
linear = np.clip(linear, 0, 1)
srgb = np.where(linear <= 0.0031308,
linear * 12.92,
1.055 * (linear ** (1/2.4)) - 0.055)
return srgb
def sigmoid_contrast(image, gain=10, cutoff=0.5):
# Apply sigmoidal contrast function to the image
s1 = 1 / (1 + np.exp(gain * (cutoff - 0)))
s2 = 1 / (1 + np.exp(gain * (cutoff - 1)))
f = (1 / (1 + np.exp(gain * (cutoff - image))) - s1) / (s2 - s1)
return f
def inverse_sigmoid_contrast(f, gain=10, cutoff=0.5):
# Apply inverse sigmoidal contrast function to the image
s1 = 1 / (1 + np.exp(gain * (cutoff - 0)))
s2 = 1 / (1 + np.exp(gain * (cutoff - 1)))
y = f * (s2 - s1) + s1
p = cutoff - (1 / gain) * np.log((1 - y) / y)
return p
def process_image(input_path, output_path):
img = Image.open(input_path)
# Ensure image is in RGB mode
if img.mode != 'RGB':
img = img.convert('RGB')
# Convert to numpy array, float32, in [0,1]
img_np = np.array(img).astype(np.float32) / 255.0
# Get current image size
width, height = img.size
# Calculate new size, maintain aspect ratio
new_height = 1600
scale_factor = new_height / height
new_width = int(width * scale_factor)
new_size = (new_width, new_height)
# Upscaling or downscaling?
if height < new_height:
# Upscaling
# Apply sigmoidal function
gain = 10 # Adjust gain as needed
img_mapped = sigmoid_contrast(img_np, gain=gain)
# Clip values to [0,1]
img_mapped = np.clip(img_mapped, 0, 1)
# Convert back to PIL Image
img_mapped_pil = Image.fromarray((img_mapped * 255.0).astype(np.uint8))
# Resize using Lanczos filter
img_resized_pil = img_mapped_pil.resize(new_size, Image.LANCZOS)
# Convert resized image back to numpy array
img_resized_np = np.array(img_resized_pil).astype(np.float32) / 255.0
# Apply inverse sigmoidal function
img_np_restored = inverse_sigmoid_contrast(img_resized_np, gain=gain)
else:
# Downscaling
# Convert to linear RGB
img_linear = srgb_to_linear(img_np)
# Convert to 16-bit to preserve precision
img_linear_16bit = (img_linear * 65535).astype(np.uint16)
# Split channels
r, g, b = [img_linear_16bit[:, :, i] for i in range(3)]
# Create PIL Images for each channel
r_img = Image.fromarray(r, mode='I;16')
g_img = Image.fromarray(g, mode='I;16')
b_img = Image.fromarray(b, mode='I;16')
# Resize channels
r_resized = r_img.resize(new_size, Image.LANCZOS)
g_resized = g_img.resize(new_size, Image.LANCZOS)
b_resized = b_img.resize(new_size, Image.LANCZOS)
# Convert back to numpy arrays
r_np = np.array(r_resized).astype(np.float32) / 65535.0
g_np = np.array(g_resized).astype(np.float32) / 65535.0
b_np = np.array(b_resized).astype(np.float32) / 65535.0
# Stack channels back together
img_resized_np_linear = np.stack([r_np, g_np, b_np], axis=-1)
# Convert back to sRGB
img_np_restored = linear_to_srgb(img_resized_np_linear)
# Ensure values are in [0,1] and clipped
img_np_restored = np.clip(img_np_restored, 0, 1)
# Convert back to 8-bit and PIL Image
img_final = Image.fromarray((img_np_restored * 255.0).astype(np.uint8))
# Save the image to output path
# Ensure the output directory exists
os.makedirs(os.path.dirname(output_path), exist_ok=True)
img_final.save(output_path)
def process_images(input_dir, output_dir):
for root, dirs, files in os.walk(input_dir):
for filename in files:
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.tif', '.tiff', '.bmp', '.gif')):
input_path = os.path.join(root, filename)
# Compute output path
relative_path = os.path.relpath(root, input_dir)
output_root = os.path.join(output_dir, relative_path)
output_path = os.path.join(output_root, filename)
print(f'Processing {input_path} -> {output_path}')
process_image(input_path, output_path)
if __name__ == '__main__':
process_images(input_dir, output_dir)
Explanation:
Directory Traversal: The script uses os.walk() to recursively traverse through the input directory and its subdirectories, finding all image files with common image extensions.
Image Processing:
Upscaling (Height < 1600):
Applies a sigmoidal contrast function to the image data using the sigmoid_contrast function.
Resizes the image using the Lanczos filter (Image.LANCZOS).
Applies the inverse sigmoidal function to restore the original tonal range.
Downscaling (Height > 1600):
Converts the image from sRGB to linear RGB using the srgb_to_linear function for accurate color scaling.
Converts the linear RGB data to 16-bit to preserve precision.
Splits the image into R, G, and B channels and processes each channel separately because Pillow handles 16-bit images in single-channel mode.
Resizes each channel using the Lanczos filter.
Stacks the channels back together and converts from linear RGB back to sRGB using the linear_to_srgb function.
Color Space Handling:
The image data is processed in a higher bit depth (16-bit) to preserve quality during color space conversions and resizing.
srgb_to_linear and linear_to_srgb functions handle the gamma correction to convert between sRGB and linear RGB.
Final Output:
The processed image data is converted back to 8-bit per channel and saved in the output directory, preserving the folder structure.
Lanczos Filter:
The script uses the Lanczos filter (Image.LANCZOS) for resizing, which is known for high-quality image resampling.
Note:
The gain parameter in the sigmoid_contrast function can be adjusted to control the steepness of the sigmoidal curve. The default value is set to 10.
This script assumes that the images are in sRGB color space.
The handling of 16-bit per channel images in Pillow can be limited. By converting image channels separately and using NumPy, we can process the images in higher precision.
Usage:
Make sure you have Pillow and NumPy installed:
bash
pip install Pillow numpy
Save the script to a .py file and run it. It will process all images in the input directory and save them to the output directory.
Let me know if you need any adjustments or further explanations!