To perform linear light downscaling in Python—similar to how ImageMagick handles it—you need to:
-
Convert the image from sRGB (standard RGB) to linear RGB. This step removes the gamma correction applied in sRGB, bringing the image into a linear color space where pixel values correspond linearly to light intensity.
-
Resize the image in the linear color space. By operating in linear light, interpolation during resizing is physically correct, preserving gradients and preventing color artifacts.
-
Convert the image back from linear RGB to sRGB. This reapplies the gamma correction so the image displays correctly on standard monitors and devices.
Below is a step-by-step guide using Python's Pillow library (PIL fork) and NumPy for numerical operations.
Step-by-Step Implementation
1. Import Necessary Libraries
from PIL import Image
import numpy as np
2. Define Conversion Functions
sRGB to Linear RGB Conversion:
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
Linear RGB to sRGB Conversion:
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
3. Implement the Resizing Function
def resize_in_linear_light(image_path, output_path, new_size):
"""
Resize an image in linear light.
Parameters:
- image_path: str, path to the input image.
- output_path: str, path to save the resized image.
- new_size: tuple, the desired size (width, height).
"""
# Open the image and ensure it's in RGB mode
with Image.open(image_path) as img:
img = img.convert('RGB')
# 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)))
# 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 save the final image
final_img = Image.fromarray(final_img_np, mode='RGB')
final_img.save(output_path)
4. Example Usage
# Specify the input image path, output image path, and new size
input_image = 'input.jpg'
output_image = 'output.jpg'
new_size = (800, 600) # Width, Height
# Perform the resizing
resize_in_linear_light(input_image, output_image, new_size)
Explanation of the Process
sRGB and Linear RGB
- sRGB is a standard color space that uses a non-linear gamma curve to allocate more bits to darker tones, based on human perception.
- Linear RGB represents color values proportional to actual light intensity (radiometric quantities).
Why Convert to Linear Light?
Performing operations like resizing or blurring in sRGB space can lead to incorrect results because the non-linear encoding skews the math. For instance, averaging two pixel values in sRGB does not equate to the average light intensity between them.
By converting to linear light:
- Accurate Interpolation: Interpolations during resizing are physically accurate.
- Preserved Gradients: Prevents banding and preserves smooth gradients.
- Color Fidelity: Maintains the correct relationships between colors.
Conversion Details
-
sRGB to Linear RGB Conversion follows the standard sRGB companding function:
For ( 0 \leq V_{\text{sRGB}} \leq 0.04045 ):
[
V_{\text{linear}} = \frac{V_{\text{sRGB}}}{12.92}
]
For ( V_{\text{sRGB}} > 0.04045 ):
[
V_{\text{linear}} = \left( \frac{V_{\text{sRGB}} + 0.055}{1.055} \right)^{2.4}
]
-
Linear RGB to sRGB Conversion uses the inverse of the above function:
For ( 0 \leq V_{\text{linear}} \leq 0.0031308 ):
[
V_{\text{sRGB}} = 12.92 \times V_{\text{linear}}
]
For ( V_{\text{linear}} > 0.0031308 ):
[
V_{\text{sRGB}} = 1.055 \times V_{\text{linear}}^{1/2.4} - 0.055
]
Important Considerations
- Data Types: Ensure that image data is in
float32 and scaled between 0 and 1 for accurate computations.
- Clipping: After conversions, clip values to the valid range [0, 1] to avoid artifacts due to numerical errors.
- Color Profiles: This method assumes the image uses the sRGB color space without embedded profiles.
Alternative Using OpenCV
You can also perform linear light downscaling using OpenCV, which may offer performance benefits:
import cv2
def resize_in_linear_light_cv(image_path, output_path, new_size):
# Load image using OpenCV
img = cv2.imread(image_path, cv2.IMREAD_COLOR)
if img is None:
raise IOError("Image not found or cannot be opened.")
# Convert image from BGR to RGB and scale to [0, 1]
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB).astype(np.float32) / 255.0
# Convert to linear RGB
linear_rgb = srgb_to_linear(img)
# Resize the image
resized_linear = cv2.resize(linear_rgb, new_size, interpolation=cv2.INTER_LANCZOS4)
# Convert back to sRGB
resized_srgb = linear_to_srgb(resized_linear)
# Convert back to [0, 255] and uint8
final_img = np.uint8(np.clip(resized_srgb * 255.0, 0, 255))
# Convert from RGB to BGR before saving
final_img = cv2.cvtColor(final_img, cv2.COLOR_RGB2BGR)
cv2.imwrite(output_path, final_img)
Performance Tips
- When dealing with large images or batch processing, consider using OpenCV or leveraging GPU acceleration with libraries like CuPy.
- For professional applications requiring precise color management, integrate with color management systems like OpenColorIO.
Conclusion
Performing image resizing in linear light ensures that the mathematical operations reflect real-world light behavior, leading to higher-quality results. By converting images to linear RGB before processing and back to sRGB afterward, you align with best practices in image processing, similar to the operations performed by tools like ImageMagick.
References
Feel free to adjust the functions or integration to suit your specific use case. If you encounter any issues or have further questions, don't hesitate to ask!