Changing Image Contrast with Python and Pillow
In the last article, you learned how to adjust an image’s color balance. Today you will learn how to change the contrast in an image.
Contrast is defined as the difference between dark and light in an image. A high-contrast image will have bright highlights and nice, dark shadows. Colors are usually bold and display texture. A low-contrast image, on the other hand, will seem dull or flat in comparison. The colors will be muted as well.
Changing an Image’s Contrast
In Pillow, you will need to create an instance of ImageEnhance.Contrast() and then use it to apply an enhancement factor to your image. If you apply an enhancement factor of 0.0 as you did in the previous example, you will get a solid gray image. A factor of 1.0 returns a copy of the original image, which is what happens with all enhancers.
To see how it works, you will use a couple of other enhancement factors that change how the image looks. For this example, you will be using this photo of a Madison County bridge:
Now create a file named enhance_contrast.py and add this code to it:
This code is nearly identical to the code from the last section. You change the name of the function from enhance_color() to enhance_contrast(). You also use the Contrast() class here instead of the Color() class from earlier.
When you run this example against the photo of the bridge, you will end up with the following:
This looks quite a bit different than the original. The colors are brighter and the contrast is way up. You should try running this code with some different enhancement factor amounts. You will quickly discover how to mute or enhance your photos' contrast using this handy tool.
Wrapping Up
You now know the basics of changing an image’s contrast with the Pillow package and Python. You can do many other editing tasks and enhancements with Pillow or other Python packages.
Start practicing now and you’ll soon be able to edit thousands of files easily!




