Certainly! Below is a Python program that uses OpenCV to downscale images to a height of 1600 pixels while maintaining the aspect ratio. It employs Lanczos interpolation (INTER_LANCZOS4) and performs the downscaling in linear light, similar to how ImageMagick handles it.
Key Features of the Program:
- Image Loading: Uses OpenCV to read the image in BGR format.
- Color Space Conversion:
- Converts the image from sRGB to linear RGB to ensure linear light processing.
- After resizing, converts the image back from linear RGB to sRGB.
- Resizing:
- Calculates the new width to maintain the aspect ratio based on the desired height of 1600 pixels.
- Utilizes Lanczos interpolation (
INTER_LANCZOS4) for high-quality downscaling.
- Image Saving: Saves the processed image using OpenCV.
Prerequisites:
- Python 3.x
- OpenCV Library: Install via
pip install opencv-python
- NumPy Library: Install via
pip install numpy
Program Code:
import cv2
import numpy as np
import os
import sys
def srgb_to_linear(srgb):
"""
Convert sRGB image to linear RGB.
"""
srgb = srgb / 255.0
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 image to sRGB.
"""
srgb = np.where(linear <= 0.0031308,
linear * 12.92,
1.055 * (linear ** (1/2.4)) - 0.055)
srgb = np.clip(srgb * 255.0, 0, 255).astype(np.uint8)
return srgb
def resize_image_linear(input_path, output_path, target_height=1600):
"""
Resize the image to the target height while maintaining aspect ratio.
Uses Lanczos4 interpolation and processes in linear light.
"""
# Load image in BGR format
image_bgr = cv2.imread(input_path, cv2.IMREAD_COLOR)
if image_bgr is None:
print(f"Error: Unable to load image '{input_path}'.")
return
# Convert to RGB
image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB).astype(np.float32)
# Convert sRGB to linear RGB
image_linear = srgb_to_linear(image_rgb)
# Get original dimensions
original_height, original_width = image_linear.shape[:2]
# Calculate new dimensions
scale_ratio = target_height / original_height
new_width = int(original_width * scale_ratio)
new_height = target_height
# Resize in linear space
# OpenCV expects images in [0,1] or [0,255], but since we're using float32, it's fine
resized_linear = cv2.resize(
image_linear,
(new_width, new_height),
interpolation=cv2.INTER_LANCZOS4
)
# Convert back from linear RGB to sRGB
resized_srgb = linear_to_srgb(resized_linear)
# Convert RGB back to BGR for OpenCV
resized_bgr = cv2.cvtColor(resized_srgb, cv2.COLOR_RGB2BGR)
# Save the image
success = cv2.imwrite(output_path, resized_bgr)
if success:
print(f"Image successfully resized and saved to '{output_path}'.")
else:
print(f"Error: Failed to save image to '{output_path}'.")
def batch_resize(input_dir, output_dir, target_height=1600):
"""
Batch resize all images in the input directory and save to the output directory.
"""
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# Supported image extensions
supported_extensions = ('.jpg', '.jpeg', '.png', '.bmp', '.tiff', '.tif')
for filename in os.listdir(input_dir):
if filename.lower().endswith(supported_extensions):
input_path = os.path.join(input_dir, filename)
output_path = os.path.join(output_dir, filename)
print(f"Processing '{filename}'...")
resize_image_linear(input_path, output_path, target_height)
print("Batch processing completed.")
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Downscale images to a height of 1600px using OpenCV with Lanczos4 interpolation in linear light.")
parser.add_argument('input', help="Path to the input image or directory.")
parser.add_argument('output', help="Path to save the resized image or output directory.")
parser.add_argument('--height', type=int, default=1600, help="Target height in pixels (default: 1600).")
parser.add_argument('--batch', action='store_true', help="Process all supported images in the input directory.")
args = parser.parse_args()
if args.batch:
if not os.path.isdir(args.input):
print("Error: When using --batch, the input path must be a directory.")
sys.exit(1)
batch_resize(args.input, args.output, args.height)
else:
if os.path.isdir(args.input):
print("Error: When not using --batch, the input path must be a file.")
sys.exit(1)
resize_image_linear(args.input, args.output, args.height)
How to Use the Program:
-
Save the Script:
- Save the above code to a file named, for example,
downscale_images.py.
-
Run the Script:
-
Parameters:
input: Path to the input image file or input directory.
output: Path to save the resized image file or output directory.
--height: (Optional) Target height in pixels. Default is 1600.
--batch: (Optional) If set, the script processes all supported images in the input directory.
Explanation of Key Components:
-
sRGB to Linear RGB Conversion (srgb_to_linear):
- sRGB images are gamma-encoded. To perform linear light operations (like accurate resizing), it's essential to convert them to linear RGB by applying the inverse gamma correction.
-
Linear RGB to sRGB Conversion (linear_to_srgb):
- After processing in linear light, the image is converted back to sRGB by applying gamma correction to ensure correct color representation when viewing the image.
-
Resizing with Lanczos4 Interpolation:
- The Lanczos4 (
INTER_LANCZOS4) interpolation method is used for high-quality downscaling. It's especially effective for reducing image sizes while preserving details.
-
Batch Processing:
- The
batch_resize function allows processing multiple images within a directory, making it convenient for handling large sets of images.
Notes:
-
Color Accuracy:
- Processing images in linear light can help maintain color accuracy and detail during resizing, which is beneficial for applications requiring high-quality image manipulation.
-
Image Formats:
- The script supports common image formats like JPEG, PNG, BMP, and TIFF. Ensure that the input images are in one of these formats.
-
Error Handling:
- The script includes basic error handling to notify the user if an image cannot be loaded or saved.
Dependencies Installation:
Ensure you have Python installed on your system. Then, install the required libraries using pip:
pip install opencv-python numpy
Conclusion:
This program provides a reliable way to downscale images while maintaining aspect ratios and color accuracy by processing in linear light. The use of Lanczos4 interpolation ensures high-quality results suitable for professional applications.