Change Contrast of an Image in Python
After reading this article, you will be able to Change Contrast of an Existing Image in Python. We simply use Python Imaging Library (PIL) Module to Change Contrast of an Image. We mainly require Image and ImageEnhance Classes from PIL module in order to Change the Contrast of an Image in Python.
How to Change Contrast of an Image in Python
Hence, the first line of our script will be as follows.
from PIL import Image,ImageEnhance
Here, we have imported Image and ImageEnhance Classes from Python Imaging Library (PIL). Image class is used to perform some basic Operations on Images like Opening, Saving, Closing etc.
Whereas, ImageEnhance Class is used to enhance the Properties of an Image like Brightness,Contrast, Color etc. So, let’s have a look at Opening an Image using Image Class.
img=Image.open("Path_to_Your_Image")
From the Above, img is an Image Object which is able to Perform Operations on Image. Where, “Path_to_Your_Image” is the path where the Image is located in Your Computer. Now, we have to create an object for ImageEnhance.Contrast Class in order to change the Contrast of your Image.
It can be done as follows
img_contr_obj=ImageEnhance.Contrast(img)
Where, img_contr_obj is the Object created for Contrast Class for an Image. Then, we use enhance method to Enhance the Contrast of an Image. It can be done as follows.
e_img=img_contr_obj.enhance(factor)
In here, e_img is the Object for Enhanced Image. factor is a floating-point number which enhances the Contrast of an Image.
Factor can have several values. Hence, they can be written as follows
- If factor > 1 Increases Contrast according to the given factor Values
- If factor < 1 Decreases Contrast according to the given factor Values
and if the value of factor is 1 (i.e. factor=1) then the Contrast of the Image remains Same. The Enhanced Image can either be Viewed or Saved.
To Show Enhanced Image:
For Viewing the Enhanced Image, we use the Following Code.
e_img.show()
show() method uses Command Prompt (cmd) to display the Enhanced Image.
To Save Enhanced Image:
To save the Enhanced Image, we use save() method as follows
e_img.save("Destination_of_Enhanced_Image")
The save() method saves the Modified Image at the Specified Path (i.e. “Destination_of_Enhanced_Image”). You can Open and View Enhanced Image later.
Example to Show Enhanced Image:
Input:
from PIL import Image,ImageEnhance img=Image.open("Path_to_Your_Image") img_contr_obj=ImageEnhance.Contrast(img) factor=3 e_img=img_contr_obj.enhance(factor) e_img.show()
Output:
In this way, we can Increase or Decrease the Contrast of a given Image.
For further reference on Image Processing using PILLOW or PIL Module Click Here -> Image Module – PILLOW
Leave a Reply