Use the highest quality scaling available in opencv instead of imagemagick: def resize_images(input_folder: Path, output_folder: Path, image_processor: 'ImageProcessor'):
"""Resize images in the input folder and save them to the output folder."""
try:
check_executable(Config.IMAGEMAGICK, "ImageMagick")
except FileNotFoundError as e:
log_error(str(e))
return
code
tasks = [input_path for input_path in input_folder.rglob('*')
if input_path.is_file() and input_path.suffix.lower() in Config.IMAGE_EXTENSIONS]
if not tasks:
log_error(f"No image files found in '{input_folder}'")
return
with create_temp_folder() as temp_folder:
run_with_thread_pool(tasks, process_file, time.time(), len(tasks), image_processor, temp_folder, True)
def resize_image(input_path: Path, output_path: Path) -> Path:
"""Resize an image using ImageMagick."""
output_path = output_path.with_suffix('.png')
code
Assistant
identify_command = [
str(Config.IMAGEMAGICK),
str(input_path),
'-format', '%wx%h',
'info:'
]
try:
result = subprocess.run(
identify_command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
check=True
)
current_width, current_height = map(int, result.stdout.strip().split('x'))
except subprocess.CalledProcessError as e:
log_error(f"ImageMagick identify failed for {input_path}: {e.stderr.strip()}")
return output_path
resize_mode = app.RESIZE_MODE.get()
maintain_aspect = app.maintain_aspect_ratio.get()
if resize_mode == "Fit":
target_width = int(app.RESIZE_WIDTH.get() or 0)
target_height = int(app.RESIZE_HEIGHT.get() or 0)
if maintain_aspect:
if target_width == 0 and target_height > 0:
target_width = int(target_height * current_width / current_height)
elif target_height == 0 and target_width > 0:
target_height = int(target_width * current_height / current_width)
resize_arg = f'{target_width}x{target_height}!'
else: # Shortest Side
target_size = int(app.RESIZE_SIDE.get())
resize_arg = f'{target_size}x{target_size}^'
is_upscaling = (
(resize_mode == "Fit" and (target_width > current_width or target_height > current_height)) or
(resize_mode == "Shortest Side" and target_size > min(current_width, current_height))
)
command = [
str(Config.IMAGEMAGICK),
str(input_path),
]
if is_upscaling:
command += [
'-filter', 'LanczosSharp',
'-distort', 'Resize', resize_arg,
]
else:
command += [
'-colorspace', 'RGB',
'-filter', 'Lanczos2Sharp',
'-resize', resize_arg,
'-colorspace', 'sRGB',
]
command += [
'-define', 'png:compression-level=5',
str(output_path)
]
try:
result = subprocess.run(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
check=True
)
if result.stderr:
log_error(f"ImageMagick: {result.stderr.strip()}")
except subprocess.CalledProcessError as e:
log_error(f"ImageMagick resize failed for {input_path}: {e.stderr.strip()}")
return output_path
To use OpenCV with the highest quality scaling instead of ImageMagick, you can modify your resize_image function to utilize OpenCV's cv2.resize function with the cv2.INTER_LANCZOS4 interpolation method. This interpolation mode provides high-quality results suitable for both upscaling and downscaling images.
Here's the updated code:
python
import cv2
import time
from pathlib import Path
def resize_images(input_folder: Path, output_folder: Path, image_processor: 'ImageProcessor'):
"""Resize images in the input folder and save them to the output folder using OpenCV."""
tasks = [input_path for input_path in input_folder.rglob('*')
if input_path.is_file() and input_path.suffix.lower() in Config.IMAGE_EXTENSIONS]
if not tasks:
log_error(f"No image files found in '{input_folder}'")
return
with create_temp_folder() as temp_folder:
run_with_thread_pool(tasks, process_file, time.time(), len(tasks), image_processor, temp_folder, True)
def resize_image(input_path: Path, output_path: Path) -> Path:
"""Resize an image using OpenCV with high-quality scaling."""
output_path = output_path.with_suffix('.png')
# Load the image
image = cv2.imread(str(input_path))
if image is None:
log_error(f"Failed to read image {input_path}")
return output_path
current_height, current_width = image.shape[:2]
resize_mode = app.RESIZE_MODE.get()
maintain_aspect = app.maintain_aspect_ratio.get()
if resize_mode == "Fit":
target_width = int(app.RESIZE_WIDTH.get() or 0)
target_height = int(app.RESIZE_HEIGHT.get() or 0)
if maintain_aspect:
# Calculate target dimensions while maintaining aspect ratio
if target_width == 0 and target_height > 0:
target_width = int(target_height * current_width / current_height)
elif target_height == 0 and target_width > 0:
target_height = int(target_width * current_height / current_width)
else:
# Adjust target dimensions to maintain aspect ratio
aspect_ratio = current_width / current_height
if (target_width / target_height) > aspect_ratio:
target_width = int(target_height * aspect_ratio)
else:
target_height = int(target_width / aspect_ratio)
else:
# If not maintaining aspect ratio, ensure dimensions are not zero
if target_width == 0:
target_width = current_width
if target_height == 0:
target_height = current_height
# Resize the image using high-quality interpolation
resized_image = cv2.resize(
image,
(target_width, target_height),
interpolation=cv2.INTER_LANCZOS4
)
else: # Shortest Side
target_size = int(app.RESIZE_SIDE.get())
aspect_ratio = current_width / current_height
if current_width < current_height:
# Width is the shorter side
target_width = target_size
target_height = int(target_size / aspect_ratio)
else:
# Height is the shorter side
target_height = target_size
target_width = int(target_size * aspect_ratio)
if maintain_aspect:
resized_image = cv2.resize(
image,
(target_width, target_height),
interpolation=cv2.INTER_LANCZOS4
)
else:
# Resize without maintaining aspect ratio
resized_image = cv2.resize(
image,
(target_size, target_size),
interpolation=cv2.INTER_LANCZOS4
)
# Save the resized image with compression
# For PNG, the compression level ranges from 0 (no compression) to 9 (maximum compression)
compression_params = [cv2.IMWRITE_PNG_COMPRESSION, 5]
success = cv2.imwrite(str(output_path), resized_image, compression_params)
if not success:
log_error(f"Failed to write image {output_path}")
return output_path
Explanation:
Image Loading:
The image is read using cv2.imread(). If the image cannot be loaded, an error is logged, and the function returns.
Current Dimensions:
The current width and height of the image are obtained from the shape of the NumPy array.
Resize Mode Handling:
The code checks the resize_mode from the application settings (app.RESIZE_MODE.get()), which can be either "Fit" or "Shortest Side".
Maintain Aspect Ratio:
If maintain_aspect is True, the target dimensions are adjusted to maintain the original aspect ratio.
Calculations are made to ensure that neither the width nor the height is zero and that the aspect ratio is preserved.
Resizing the Image:
The cv2.resize() function resizes the image to the calculated dimensions.
interpolation=cv2.INTER_LANCZOS4 is used for high-quality resizing, which is particularly good for reducing aliasing artifacts in both upscaling and downscaling scenarios.
Saving the Image:
The resized image is saved in PNG format using cv2.imwrite().
A compression level of 5 is set for a balance between file size and quality (cv2.IMWRITE_PNG_COMPRESSION, 5).
If saving fails, an error is logged.
Additional Notes:
Install OpenCV:
Ensure that OpenCV is installed in your Python environment:
bash
pip install opencv-python
Dependencies and Definitions:
The code assumes that the functions and variables like log_error, Config, app, create_temp_folder, run_with_thread_pool, and process_file are defined elsewhere in your codebase.
Replace these placeholders with your actual implementations.
Application Settings (app):
It is assumed that app is an object or module that contains the application's settings and configurations.
Methods like app.RESIZE_MODE.get() and app.RESIZE_WIDTH.get() should return the appropriate values.
Handling Zero Dimensions:
The code includes checks to handle cases where the target width or height may be zero, defaulting to the original dimensions if necessary.
Performance Considerations:
While cv2.INTER_LANCZOS4 offers high-quality results, it is computationally more intensive than simpler interpolation methods. If performance becomes an issue with large images or a high volume of images, you might consider using cv2.INTER_CUBIC or cv2.INTER_AREA as alternatives.
Compression Parameters:
Adjust the compression level in compression_params if you need smaller file sizes or higher quality.
Example Usage:
Assuming you have an ImageProcessor class and the necessary environment, you can call resize_images like this:
This will process all images in the input_folder, resize them according to the specified settings, and save them to the output_folder.
Conclusion:
By switching to OpenCV and using the cv2.INTER_LANCZOS4 interpolation method, you can achieve high-quality image resizing without relying on external tools like ImageMagick. This approach simplifies your dependency management and can lead to performance improvements, especially when processing a large number of images.
Feel free to adjust the code further to suit your specific application needs or to integrate additional features.