Python – Change Image Contrast – PIL
Contrast is the kind of distance between the colors. If you increase the contrast, the colors are more vivid.
In this tutorial, we shall learn how to change the contrast of image using ImageEnhance class of PIL library.
Steps to Adjust Image Contrast
To adjust image contrast using Python Pillow,
- Read the image using Image.open().
- Create ImageEnhance.Contrast() enhancer for the image.
- Enhance the image contrast using enhance() method, by the required factor.
By adjusting the factor you can adjust the contrast of the image.
While a factor of 1 gives original image. Making the factor towards 0 makes the image greyer, while factor>1 increases the contrast of the image.
Python Pillow Example – Adjust Image Contrast
In the following example, we will change the image contrast with a factor of 1, which gives our original image. Then with a factor of 1.5, which increases the image’s contrast. And then with a factor of 0.5, which greys out the image.
from PIL import Image, ImageEnhance #read the image im = Image.open("sample-image.png") #image brightness enhancer enhancer = ImageEnhance.Contrast(im) factor = 1 #gives original image im_output = enhancer.enhance(factor) im_output.save('original-image.png') factor = 0.5 #decrease constrast im_output = enhancer.enhance(factor) im_output.save('less-contrast-image.png') factor = 1.5 #increase contrast im_output = enhancer.enhance(factor) im_output.save('more-contrast-image.png')
Image with Increase in Contrast
Dull Image – With decreased contrast
In this tutorial of Python Examples, we learned how to change the contrast of image, using Pillow library, with the help of well detailed example programs.