improve the scribt by using the highest quality available scaling algorithm in pillow.…
- User
improve the scribt by using the highest quality available scaling algorithm in pillow. keep everything else the same. Code: import os from PIL import Image import numpy as np
def srgb_to_linear(srgb): """Convert sRGB values to linear RGB.""" threshold = 0.04045 linear = np.where( srgb <= threshold, srgb / 12.92, ((srgb + 0.055) / 1.055) ** 2.4 ) return linear
def linear_to_srgb(linear): """Convert linear RGB values to sRGB.""" threshold = 0.0031308 srgb = np.where( linear <= threshold, linear * 12.92, 1.055 * (linear ** (1 / 2.4)) - 0.055 ) return srgb
def resize_in_linear_light(img, new_size): """ Resize a PIL image in linear light.
Parameters: - img: PIL Image instance. - new_size: tuple, the desired size (width, height). Returns: - final_img: PIL Image instance of the resized image. """ # Convert image data to a NumPy array and scale to [0, 1] img_np = np.array(img, dtype=np.float32) / 255.0 # Convert from sRGB to linear RGB linear_rgb = srgb_to_linear(img_np) # Convert linear RGB back to an image object for resizing # Multiply by 255 to scale back to [0, 255] linear_img = Image.fromarray(np.uint8(np.clip(linear_rgb * 255.0, 0, 255)), mode='RGB') # Resize the image using a high-quality downsampling filter resized_linear_img = linear_img.resize(new_size, resample=Image.LANCZOS) # Convert resized linear RGB image back to NumPy array and scale to [0, 1] resized_linear_np = np.array(resized_linear_img, dtype=np.float32) / 255.0 # Convert from linear RGB back to sRGB resized_srgb = linear_to_srgb(resized_linear_np) # Scale to [0, 255] and clip any out-of-range values final_img_np = np.uint8(np.clip(resized_srgb * 255.0, 0, 255)) # Create and return the final image final_img = Image.fromarray(final_img_np, mode='RGB') return final_imgdef process_images(input_dir, output_dir, target_height): """ Process all images in input_dir (recursively), downscale them to target_height while maintaining aspect ratio, and save to output_dir, keeping the folder structure.
Parameters: - input_dir: str, path to the input directory. - output_dir: str, path to the output directory. - target_height: int, the target height for the resized images. """ for root, dirs, files in os.walk(input_dir): for filename in files: # Check if the file is an image if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.tif', '.tiff', '.gif')): input_file_path = os.path.join(root, filename) # Construct the output file path relative_path = os.path.relpath(root, input_dir) output_folder = os.path.join(output_dir, relative_path) os.makedirs(output_folder, exist_ok=True) # Change the extension to .png name, _ = os.path.splitext(filename) output_file_name = name + '.png' output_file_path = os.path.join(output_folder, output_file_name) # Open the image try: with Image.open(input_file_path) as img: img = img.convert('RGB') # Ensure image is in RGB mode # Calculate new size width, height = img.size aspect_ratio = width / height new_height = target_height new_width = int(new_height * aspect_ratio) new_size = (new_width, new_height) # Resize in linear light resized_img = resize_in_linear_light(img, new_size) # Save the image resized_img.save(output_file_path, format='PNG') print(f"Processed image: {input_file_path} -> {output_file_path}") except Exception as e: print(f"Failed to process image {input_file_path}: {e}") - Assistant