I get the following error: Processing D:\Bilder\Python\1. Input\01.png
Failed to process D:\Bilder\Python\1. Input\01.png: image has wrong mode Programm: import os
import numpy as np
from PIL import Image
from PIL import ImageOps
def gamma_decode(img_np, gamma=2.2):
"""Convert sRGB to linear RGB."""
return img_np ** gamma
def gamma_encode(img_np, gamma=2.2):
"""Convert linear RGB to sRGB."""
return img_np ** (1 / gamma)
def process_directory(input_dir, output_dir):
for root, dirs, files in os.walk(input_dir):
# Calculate the relative path
rel_path = os.path.relpath(root, input_dir)
# Create corresponding directory in output
output_subdir = os.path.join(output_dir, rel_path)
os.makedirs(output_subdir, exist_ok=True)
code
for file in files:
if file.lower().endswith(('.jpg', '.jpeg', '.png', '.tif', '.tiff', '.bmp', '.gif')):
input_path = os.path.join(root, file)
output_path = os.path.join(output_subdir, file)
try:
print(f"Processing {input_path}")
process_image(input_path, output_path)
except Exception as e:
print(f"Failed to process {input_path}: {e}")
Run the script
process_directory(input_dir, output_dir)
The error message you're encountering:
code
Failed to process D:\Bilder\Python\1. Input\01.png: image has wrong mode
occurs because the Image.resize() function from the Pillow library doesn't support resizing images in the 'I;16' mode using the Image.LANCZOS resampling filter. The 'I;16' mode represents a 16-bit grayscale image, and certain operations, including resizing with some filters, are not supported for this mode in Pillow.
Pillow raises an error because it cannot perform Lanczos resampling on an image in 'I;16' mode. The Lanczos filter (Image.LANCZOS) is supported for images in modes such as 'L' (8-bit grayscale), 'RGB', and 'RGBA', but not for 'I;16'.
How to Fix the Error
To resolve this issue, you can modify your code to ensure that the image is in a mode compatible with the resize() function and the Lanczos filter. Here are some steps you can take:
Convert the Image to a Compatible Mode Before Resizing
Since you need to work with high bit-depth images (16-bit per channel), and Pillow doesn't natively support 16-bit per channel RGB images, you can process your images using NumPy arrays and use a library that supports resizing high bit-depth images.
Alternatively, you can convert your image to a floating-point mode that supports the operations you need.
Use NumPy and an External Library for Resizing
Libraries like scikit-image or OpenCV support high bit-depth images and can perform resizing with Lanczos resampling on NumPy arrays.
Here's how you might modify your process_image function:
python
import os
import numpy as np
from PIL import Image
from skimage.transform import resize # You need to install scikit-image
def process_image(image_path, output_path):
# Open the image and convert to RGB (if not already)
img = Image.open(image_path).convert('RGB')
# Convert the image to a NumPy array and normalize to [0, 1]
img_np = np.array(img, dtype=np.float64) / 255.0
# Get the original dimensions
orig_height, orig_width = img_np.shape[:2]
# Desired height
desired_height = 1600
# Determine if upscaling or downscaling
if orig_height < desired_height:
# Upscaling - use Lanczos with sigmoidal light
# Apply sigmoidal contrast mapping before resizing
contrast = 7.5 # You can adjust this value
img_np = sigmoidize(img_np, contrast)
# Calculate new dimensions while maintaining aspect ratio
scale_factor = desired_height / orig_height
new_width = int(orig_width * scale_factor)
# Resize using Lanczos filter via skimage
img_np = resize(
img_np, (desired_height, new_width), order=3, mode='reflect', anti_aliasing=True
)
# Apply inverse sigmoidal contrast mapping after resizing
img_np = inverse_sigmoidize(img_np, contrast)
else:
# Downscaling - use Lanczos in linear light
# Convert to linear light (gamma correction with gamma=2.2)
img_np = gamma_decode(img_np)
# Calculate new dimensions while maintaining aspect ratio
scale_factor = desired_height / orig_height
new_width = int(orig_width * scale_factor)
# Resize using Lanczos filter via skimage
img_np = resize(
img_np, (desired_height, new_width), order=3, mode='reflect', anti_aliasing=True
)
# Convert back to sRGB (gamma encode with gamma=1/2.2)
img_np = gamma_encode(img_np)
# Clip values to [0, 1]
img_np = np.clip(img_np, 0, 1)
# Convert back to 16-bit unsigned integers
img_np = (img_np * 65535).astype(np.uint16)
# Convert back to image
img_out = Image.fromarray(img_np, mode='RGB')
# Save the image in PNG format to preserve 16-bit depth
img_out.save(output_path, 'PNG')
Notes:
Resizing with scikit-image: The resize function from skimage.transform allows you to resize NumPy arrays with Lanczos resampling (order=3) while preserving high bit-depth data.
Data Types: When you create img_np, ensure it's of type float64 to maintain precision during processing.
Scaling Pixel Values: After processing, you scale pixel values to the range [0, 65535] and convert them to uint16 to preserve 16-bit depth.
Image Modes in Pillow: Pillow doesn't support 'RGB;16', so when converting the NumPy array back to an image, you can use mode 'RGB' and ensure your data is in uint16 format.
Using OpenCV for Resizing
Alternatively, you can use OpenCV, which natively supports images with higher bit depths and provides Lanczos resampling.
Here's how you might incorporate OpenCV:
python
import os
import numpy as np
from PIL import Image
import cv2 # You need to install opencv-python
def process_image(image_path, output_path):
# Open the image and convert to RGB
img = Image.open(image_path).convert('RGB')
# Convert to NumPy array
img_np = np.array(img, dtype=np.uint16)
# Normalize the pixel values to [0, 1]
img_np = img_np.astype(np.float64) / 255.0 # Assuming the original image is 8-bit per channel
# Get original dimensions
orig_height, orig_width = img_np.shape[:2]
# Desired height
desired_height = 1600
# Determine if upscaling or downscaling
if orig_height < desired_height:
# Upscaling with sigmoidal light
contrast = 7.5
img_np = sigmoidize(img_np, contrast)
# Calculate new dimensions
scale_factor = desired_height / orig_height
new_width = int(orig_width * scale_factor)
new_size = (new_width, desired_height)
# Resize using Lanczos filter via OpenCV
img_np = cv2.resize(
img_np, (new_width, desired_height), interpolation=cv2.INTER_LANCZOS4
)
img_np = inverse_sigmoidize(img_np, contrast)
else:
# Downscaling in linear light
img_np = gamma_decode(img_np)
scale_factor = desired_height / orig_height
new_width = int(orig_width * scale_factor)
# Resize using Lanczos filter via OpenCV
img_np = cv2.resize(
img_np, (new_width, desired_height), interpolation=cv2.INTER_LANCZOS4
)
img_np = gamma_encode(img_np)
# Clip values and convert back to uint16
img_np = np.clip(img_np * 65535, 0, 65535).astype(np.uint16)
# Convert back to image
img_out = Image.fromarray(img_np, mode='RGB')
# Save the image
img_out.save(output_path, 'PNG')
Notes:
Data Conversion: Ensure you correctly handle data types and scaling between OpenCV and Pillow.
Interpolation: cv2.INTER_LANCZOS4 corresponds to the Lanczos filter in OpenCV.
Additional Considerations
16-bit Images in Pillow: Pillow has limited support for handling 16-bit per channel images in RGB mode. While you can create 'I;16' images for single-channel 16-bit data, it doesn't support 'RGB;16'. Using external libraries like OpenCV or scikit-image can help circumvent this limitation.
Image Modes and Data Types: When working with high bit-depth images, it’s crucial to ensure that data types and image modes align correctly to prevent data loss or errors.
Summary
The error you're experiencing stems from attempting to resize an image in a mode that's not supported by the Pillow resize() function with the Lanczos filter. By adjusting your code to use libraries that support high bit-depth images and appropriate image modes, you can successfully process your images without encountering the "image has wrong mode" error.
Remember: When working with image processing libraries, always check the documentation for limitations regarding image modes and supported data types for various operations. This will help you avoid similar issues in the future.