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, ImageEnhanceimg = Image.open("/test.png").convert("RGB")img_enhancer = ImageEnhance.Brightness(img)factor = 1enhanced_output = img_enhancer.enhance(factor)enhanced_output.save("output/original-image.png")factor = 0.5enhanced_output = img_enhancer.enhance(factor)enhanced_output.save("output/dark-image.png")factor = 1.5enhanced_output = img_enhancer.enhance(factor)enhanced_output.save("output/bright-image.png")
Code explanation
In the above code, we’ll use the following:
- The
test.pngimage ImageEnhanceandImagemodules- Different factors for different brightness
- Line 1: The
ImageEnhanceandImagemodules are imported.
- Line 3: The
test.pngis read into memory usingopen()inImagemodule.
-
Line 5: The
enhancerobject is returned by passing the image to theBrightnessclass constructor. -
Line 7: We define the
factorof enhancement. -
Lines 8-9: The brightness is adjusted using the
enhance()method by passing thefactoras the argument to the method. The resulting image is saved asoriginal-image.png. -
Lines 11-17: These lines are repeated for different enhancement factors.
Free Resources