How to control the brightness of an image in Python

The Python Imaging Library, known as “PIL” or “pillow,” is a library for image processing in Python. This library has powerful image processing capabilities, supports a large number of file types, and is built for an effective internal representation of picture data.

There are many modules in PIL library for different purposes. One such module is the ImageEnhance module. As the name suggests, the ImageEnhance module in PIL contains a number of different classes that can be used for the enhancement of the images.

The Brightness class

The Brightness class is used to adjust the image brightness. The brightness is controlled using the enhance() method, which takes an enhancement factor as its parameter.

By changing the factor, we make the image brighter or darker. The original image is produced by a factor of one. When the factor is set to 0, the picture is dark. However, when it is set to a value higher than 1, the image becomes brighter.

Syntax

img_enhancer = ImageEnhance.Brightness(image)
img_enhancer.enhance(factor)

Parameter

  • image: This is the image to brighten.
  • factor: This is the brightness scale.

Code Example

Let’s look at the code below:

from PIL import Image, ImageEnhance
img = Image.open("/test.png").convert("RGB")
img_enhancer = ImageEnhance.Brightness(img)
factor = 1
enhanced_output = img_enhancer.enhance(factor)
enhanced_output.save("output/original-image.png")
factor = 0.5
enhanced_output = img_enhancer.enhance(factor)
enhanced_output.save("output/dark-image.png")
factor = 1.5
enhanced_output = img_enhancer.enhance(factor)
enhanced_output.save("output/bright-image.png")

Code explanation

In the above code, we’ll use the following:

  1. The test.png image
  2. ImageEnhance and Image modules
  3. Different factors for different brightness
  • Line 1: The ImageEnhance and Image modules are imported.
  • Line 3: The test.png is read into memory using open() in Image module.
  • Line 5: The enhancer object is returned by passing the image to the Brightness class constructor.

  • Line 7: We define the factor of enhancement.

  • Lines 8-9: The brightness is adjusted using the enhance() method by passing the factor as the argument to the method. The resulting image is saved as original-image.png.

  • Lines 11-17: These lines are repeated for different enhancement factors.

Copyright ©2024 Educative, Inc. All rights reserved