0 votes
in Python Flask by
How can PIL be used to adjust the brightness or contrast of an image?

1 Answer

0 votes
by

PIL, or Python Imaging Library, can be used to adjust the brightness and contrast of an image through its ImageEnhance module. This module provides methods for adjusting color balance, contrast, brightness, and sharpness.

To adjust brightness, you instantiate a Brightness class with your image as argument, then call the enhance method on this object passing in a factor. A factor greater than 1 increases brightness, less than 1 decreases it.

Contrast adjustment is similar. Instantiate a Contrast class with your image, then call enhance with a factor. Greater than 1 increases contrast, less than 1 reduces it.

Here’s a code example:

from PIL import Image, ImageEnhance

# Open an image file

with Image.open('image.jpg') as img:

    enhancer = ImageEnhance.Brightness(img)

    img_bright = enhancer.enhance(1.5) # Increase brightness

    enhancer = ImageEnhance.Contrast(img)

    img_contrast = enhancer.enhance(2.0) # Increase contrast

...