Python PIL – Adjust contrast of an image

In this post we will be creating a Python script that will adjust the contrast of an existing image, to do this we will be using the Python Imaging Library also known as PIL enabling us to image processing capabilities.

See the sample of Python code where we utilise the PIL library to adjust the contrast of an image and save it as a new file. To help us achieve this we utilize the ‘ImageEnhance’ module which contains a number of classes that can be used for image enhancement. In particular we will be using the ‘ImageEnhance.Contrast()’ method which adjusts the image contrast.

Below we have applied a contrast enhancement with a value of 2.5

from PIL import Image, ImageEnhance

img=Image.open('image.png')

enhancer = ImageEnhance.Contrast(img)

img = enhancer.enhance(2.5)

img.save('adjusted_image.png')

See below our image before the adjustment.

Python PIL - Adjust contrast of an image BEFORE

See below our image after the adjustment.

Python PIL - Adjust contrast of an image AFTER

Take a look at some of our other content around the Python programming language by clicking here.

Leave a Reply