Changing the contrast and brightness of an image using Python - OpenCV
Last Updated :
03 Jan, 2023
Changing the Brightness and Contrast level of any image is the most basic thing everyone does with an image. It is meant to change the value of each and every pixel of an image it can be done by either multiplying or dividing the pixels value of an image. In this article, we will see how we can implement our theory in a beautiful code using OpenCV Python,
Before starting let's try to understand some basic concepts like, what is brightness? What is a contrast? What are pixels? And what is OpenCV?
- Brightness: When the brightness is adjusted, the entire range of tones within the image is raised or lowered accordingly.
- Contrast: When the contrast adjustment is raised, the middle tones are eliminated. The image will have a higher percentage of darks or blacks and whites or highlights with minimal mid-tone.
- Pixels: Pixels are typically used to refer to the display resolution of a computer monitor or screen. The greater the pixels, the greater the detail in the image.
- OpenCV: OpenCV is the huge open-source library for computer vision, machine learning, and image processing and now it plays a major role in real-time operation
Agenda: To learn how to adjust the brightness and contrast level of an image using OpenCV.
Requirement: OpenCV
Installation:
pip install openCV
Approach:
- Import required module.
- Define the main function, Define required data in it.
- Create a function brightness_contrast, to create a track bar to adjust brightness and contrast.
- Create another function to change the brightness and contrast.
- Display the original and edited image.
- Terminate the program with 'ESC' or simply close the window.
Let's implement this step-wise:
Step 1: Here we will load an image and create a trackbar.
Syntax: imread(filename): filename(Name of the image file).
namedWindow(winname): winname(Name of the window).
Code:
Python3
if __name__ == '__main__':
# The function imread loads an
# image from the specified file and returns it.
original = cv2.imread("pic.jpeg")
# Making another copy of an image.
img = original.copy()
# The function namedWindow creates
# a window that can be used as
# a placeholder for images.
cv2.namedWindow('GEEK')
# The function imshow displays
# an image in the specified window.
cv2.imshow('GEEK', original)
# createTrackbar(trackbarName,
# windowName, value, count, onChange)
# Brightness range -255 to 255
cv2.createTrackbar('Brightness', 'GEEK',
255, 2 * 255,
BrightnessContrast)
# Contrast range -127 to 127
cv2.createTrackbar('Contrast', 'GEEK',
127, 2 * 127,
BrightnessContrast)
BrightnessContrast(0)
# The function waitKey waits for
# a key event infinitely or for
# delay milliseconds, when it is positive.
cv2.waitKey(0)
Step 2: By calling the controller function, it will return the edited image, After that imshow() function will display the affected image.
Syntax: getTrackbarPos(trackbarname, winname): trackbarname(Name of the trackbar), winname( Name of the window)
Code:
Python3
def BrightnessContrast(brightness=0):
# getTrackbarPos returns the
# current position of the specified trackbar.
brightness = cv2.getTrackbarPos('Brightness',
'GEEK')
contrast = cv2.getTrackbarPos('Contrast',
'GEEK')
effect = controller(img,
brightness,
contrast)
# The function imshow displays
# an image in the specified window
cv2.imshow('Effect', effect)
Step 3: The controller function will control the Brightness and Contrast of an image according to the trackbar position and return the edited image.
Syntax: addWeighted(src1, alpha, src2, beta, gamma)
Parameters:
src1: first input array.
alpha: (weight of the first array elements.
src2: second input array of the same size and channel number as src1.
beta: weight of the second array elements.
gamma: scalar added to each sum.
putText(img, text, org, fontFace, fontScale, color, thickness, lineType, bottomLeftOrigin)
img: Image.
text: Text string to be drawn.
org: Bottom-left corner of the text string in the image.
fontFace: Font type, see #HersheyFonts.
fontScale: Font scale factor that is multiplied by the font-specific base size.
color: Text color.
thickness: Thickness of the lines used to draw a text.
lineType: Line type. See #LineTypes.
bottomLeftOrigin: When true, the image data origin is at the bottom-left corner. Otherwise, it is at the top-left corner.
Python3
def controller(img, brightness=255, contrast=127):
brightness = int((brightness - 0) * (255 - (-255)) / (510 - 0) + (-255))
contrast = int((contrast - 0) * (127 - (-127)) / (254 - 0) + (-127))
if brightness != 0:
if brightness > 0:
shadow = brightness
max = 255
else:
shadow = 0
max = 255 + brightness
al_pha = (max - shadow) / 255
ga_mma = shadow
# The function addWeighted
# calculates the weighted sum
# of two arrays
cal = cv2.addWeighted(img, al_pha,
img, 0, ga_mma)
else:
cal = img
if contrast != 0:
Alpha = float(131 * (contrast + 127)) / (127 * (131 - contrast))
Gamma = 127 * (1 - Alpha)
# The function addWeighted calculates
# the weighted sum of two arrays
cal = cv2.addWeighted(cal, Alpha,
cal, 0, Gamma)
# putText renders the specified
# text string in the image.
cv2.putText(cal, 'B:{},C:{}'.format(brightness,
contrast),
(10, 30), cv2.FONT_HERSHEY_SIMPLEX,
1, (0, 0, 255), 2)
return cal
Below is the full Implementation:
Python3
import cv2
def BrightnessContrast(brightness=0):
# getTrackbarPos returns the current
# position of the specified trackbar.
brightness = cv2.getTrackbarPos('Brightness',
'GEEK')
contrast = cv2.getTrackbarPos('Contrast',
'GEEK')
effect = controller(img, brightness,
contrast)
# The function imshow displays an image
# in the specified window
cv2.imshow('Effect', effect)
def controller(img, brightness=255,
contrast=127):
brightness = int((brightness - 0) * (255 - (-255)) / (510 - 0) + (-255))
contrast = int((contrast - 0) * (127 - (-127)) / (254 - 0) + (-127))
if brightness != 0:
if brightness > 0:
shadow = brightness
max = 255
else:
shadow = 0
max = 255 + brightness
al_pha = (max - shadow) / 255
ga_mma = shadow
# The function addWeighted calculates
# the weighted sum of two arrays
cal = cv2.addWeighted(img, al_pha,
img, 0, ga_mma)
else:
cal = img
if contrast != 0:
Alpha = float(131 * (contrast + 127)) / (127 * (131 - contrast))
Gamma = 127 * (1 - Alpha)
# The function addWeighted calculates
# the weighted sum of two arrays
cal = cv2.addWeighted(cal, Alpha,
cal, 0, Gamma)
# putText renders the specified text string in the image.
cv2.putText(cal, 'B:{},C:{}'.format(brightness,
contrast), (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
return cal
if __name__ == '__main__':
# The function imread loads an image
# from the specified file and returns it.
original = cv2.imread("pic.jpeg")
# Making another copy of an image.
img = original.copy()
# The function namedWindow creates a
# window that can be used as a placeholder
# for images.
cv2.namedWindow('GEEK')
# The function imshow displays an
# image in the specified window.
cv2.imshow('GEEK', original)
# createTrackbar(trackbarName,
# windowName, value, count, onChange)
# Brightness range -255 to 255
cv2.createTrackbar('Brightness',
'GEEK', 255, 2 * 255,
BrightnessContrast)
# Contrast range -127 to 127
cv2.createTrackbar('Contrast', 'GEEK',
127, 2 * 127,
BrightnessContrast)
BrightnessContrast(0)
# The function waitKey waits for
# a key event infinitely or for delay
# milliseconds, when it is positive.
cv2.waitKey(0)
Output:
Similar Reads
How to Randomly change the brightness, contrast, saturation and hue of an image in PyTorch In this article, we are going to discuss How to Randomly change the brightness, contrast, saturation, and hue of an image in PyTorch. we can randomly change the brightness, contrast, saturation, and hue of an image by using ColorJitter() method of torchvision.transforms module. ColorJitter() method:
2 min read
Addition and Blending of images using OpenCV in Python When we talk about images, we know its all about the matrix either binary image(0, 1), gray scale image(0-255) or RGB image(255 255 255). So additions of the image is adding the numbers of two matrices. In OpenCV, we have a command cv2.add() to add the images. Below is code for Addition of two image
2 min read
Erosion and Dilation of images using OpenCV in python Morphological operations are a set of operations that process images based on shapes. They apply a structuring element to an input image and generate an output image. The most basic morphological operations are two: Erosion and Dilation Basics of Erosion: Erodes away the boundaries of the foreground
2 min read
Adding borders to the images using Python - OpenCV Image processing is an interesting field in today's era of Artificial Intelligence and Machine Learning. We can see the applications of image processing in our day-to-day life, like whenever we apply filter over any image (selfie) or when we want to apply some effect like blurring the image, etc. I
1 min read
Negative transformation of an image using Python and OpenCV Image is also known as a set of pixels. When we store an image in computers or digitally, itâs corresponding pixel values are stored. So, when we read an image to a variable using OpenCV in Python, the variable stores the pixel values of the image. When we try to negatively transform an image, the b
4 min read