Change Brightness of an Image in Python
In this tutorial, you will learn how to change the brightness of an existing image with Python.
Here, we are going to use the Python Imaging Library ( PIL ) Module to change the Brightness of our image. PIL consists of various Classes. We require Image and ImageEnhance Classes. Hence, our first line of the script will be as follows:
from PIL import Image,ImageEnhance
The Image Class is used to do some certain operations on Images such as Opening, Closing and Saving etc. Let’s have a look at Opening an Image
img=Image.open("C:\\Path_to_Your_Image")
Image.open() method Opens Image that exists at specified Path (i.e. Path_to_Your_Image). Now, we have to create an object for ImageEnhance.Brightness Class in order to adjust the brightness of your image. It can be done as follows
img_brightness_obj=ImageEnhance.Brightness(img) #img is the Image Object
Here, img_brightness_obj is the Object created for Brightness Class for an Image. Then, we use enhance the method to enhance the brightness of an Image. It will be implemented as follows
enhanced_img=img_brightness_obj.enhance(factor)
In here, factor is a floating-point number that enhances brightness of an Image. It has no length limitation. It has several Values. They are as follows
factor > 1 Brightness of Image increases according to given factor
factor < 1 Brightness of Image decreases according to given factor
and if factor is equal to 1 then Brightness of Image remains same
It can either be shown or saved. For showing the Enhanced Image, we use the following code.
enhanced_img.show()
show() method uses Command Prompt (cmd) to display Modified or Enhanced Image.
To save the Enhanced Image, we use save() method as follows
enhanced_img.save("C:\\Path_to_save_Modified_Image")
It saves the modified Image in the specified Path (i.e. “C:\\Path_to_save_Modified_Image”). Later You can open and View Modified or Enhanced Image.
1. Example to Save Enhanced Image:
Input:
Code:
from PIL import Image,ImageEnhance img=Image.open("D:\\night.jpg") img_brightness_obj=ImageEnhance.Brightness(img) factor=int(input()) enhanced_img=img_brightness_obj.enhance(factor) enhanced_img.save("D:\\Mod_Night.jpg")
Output:
At the Destination, you can Check the Modified or Enhanced Image of Original Image. In this way, we can Save an Enhanced Image.
2. Example to View Enhanced Image:
Input:
Code:
from PIL import Image,ImageEnhance img=Image.open("D:\\night.jpg") img_brightness_obj=ImageEnhance.Brightness(img) factor=int(input()) enhanced_img=img_brightness_obj.enhance(factor) enhanced_img.show()
Output:
In this way, we can change the Brightness of an image in Python
Also, read:
Leave a Reply