Hello! In this post, you will be learning how to change the brightness and contrast of an image using the PIL library package. You can check out the video below to learn more.
We will continue to build out previous code. Let us start by importing the required library package.
from PIL import ImageEnhance
The ImageEnhance package will be used to change the brightness and contrast of an image. Now, we will be writing a few lines to the brightness_callback() method.
def brightness_callback(brightness_pos):
brightness_pos = float(brightness_pos)
global outputImage
enhancer = ImageEnhance.Brightness(originalImage)
outputImage = enhancer.enhance(brightness_pos)
dispayImage(outputImage)
brightness_callback() method requires an argument to be passed. This argument holds the current position of the slider and is of string type. The ImageEnhance library package needs a variable of float type. So that is why in the first line we have converted the brightness_pos variable to float type. In the next line, we have declared a global outputImage variable. This is because while saving the image we want the output image to be saved and not the original image(unlike the previous post where we saved the original image). The same variable will be used throughout all the callback methods.
ImageEnhance.Brightness() method is used to control the brightness of an image. enhancer.enhance() changes the brightness by a given factor. This is where the brightness_pos variable comes into the picture. A value of 0.0 will give you a black image and a value of 1.0 will give you the original image. The edited image is stored in outputImage variable. And at last, we call the displayImage() method for displaying the edited image on the GUI window.
Similar to the previous case we will be writing the code for contrast_callback() method.
def contrast_callback(contrast_pos):
contrast_pos = float(contrast_pos)
global outputImage
enhancer = ImageEnhance.Contrast(originalImage)
outputImage = enhancer.enhance(contrast_pos)
dispayImage(outputImage)
The only difference here is, for changing the contrast we are using ImageEnhance.Contrast() method. The rest of the code remains the same.
For saving the edited image, you have to make a little change in the code. Instead of originalImage you have to replace it with outputImage as shown below.
def saveButton_callback():
savefile = filedialog.asksaveasfile(defaultextension=".jpg")
outputImage.save(savefile)
That is it. Your code is ready to run.
Enjoy Coding...!!!
For full code click here.
Comments
Post a Comment