How are the images transformed when using the PIL.ImageEnhance
enhance feature for brightness, color and contrast respectively? As in, what is the mathematical formula for transforming the pixel values for each of the transformations?
From the source code on ImageEnhance.py
, we see that there is no direct "mathematical formula" for any of the transformations. For each modality (brightness, color, etc.), a modified image is generated and then this modified image is blended with the original image by the given factor from 0.0 ... 1.0
, cf. Image.blend
.
Here's some comparison code, rebuilding the named functions from ImageEnhancer
on-the-fly for some RGB image:
from matplotlib import pyplot as plt
from PIL import Image, ImageEnhance, ImageStat
# Read image, set up factor
image = Image.open('path/to/your/image.png')
factor = 0.25
# ImageEnhance
br_enhancer = ImageEnhance.Brightness(image)
cl_enhancer = ImageEnhance.Color(image)
cn_enhancer = ImageEnhance.Contrast(image)
# Rebuild ImageEnhance.Brightness on-the-fly
br_image_pre = Image.new(image.mode, image.size, 0)
br_image = Image.blend(br_image_pre, image, factor)
# Rebuild ImageEnhance.Color on-the-fly
cl_image_pre = image.convert('L').convert('RGB')
cl_image = Image.blend(cl_image_pre, image, factor)
# Rebuild ImageEnhance.Contrast on-the-fly
mean = int(ImageStat.Stat(image.convert('L')).mean[0] + 0.5)
cn_image_pre = Image.new('L', image.size, mean).convert(image.mode)
cn_image = Image.blend(cn_image_pre, image, factor)
# Visualization
plt.figure(1, figsize=(14, 9))
plt.subplot(3, 4, 1), plt.imshow(image), plt.title('Original image')
plt.subplot(3, 4, 2), plt.imshow(br_enhancer.enhance(factor)), plt.title('ImageEnhance.Brightness(0.25)')
plt.subplot(3, 4, 3), plt.imshow(cl_enhancer.enhance(factor)), plt.title('ImageEnhance.Color(0.25)')
plt.subplot(3, 4, 4), plt.imshow(cn_enhancer.enhance(factor)), plt.title('ImageEnhance.Contrast(0.25)')
plt.subplot(3, 4, 5), plt.imshow(image), plt.title('Original image (0.25)')
plt.subplot(3, 4, 6), plt.imshow(br_image_pre), plt.title('+ brightness modified image (0.75)')
plt.subplot(3, 4, 7), plt.imshow(cl_image_pre), plt.title('+ color modified image (0.75)')
plt.subplot(3, 4, 8), plt.imshow(cn_image_pre), plt.title('+ contrast modified image (0.75)')
plt.subplot(3, 4, 10), plt.imshow(br_image), plt.title('= rebuilt ImageEnhance.Brightness(0.25)')
plt.subplot(3, 4, 11), plt.imshow(cl_image), plt.title('= rebuilt ImageEnhance.Color(0.25)')
plt.subplot(3, 4, 12), plt.imshow(cn_image), plt.title('= rebuilt ImageEnhance.Contrast(0.25)')
plt.tight_layout()
plt.show()
And, that's the output for my standard test image:
Hope that helps understanding!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.