Open In App

Changing the contrast and brightness of an image using Python – OpenCV

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?



Agenda: To learn how to adjust the brightness and contrast level of an image using OpenCV.

Requirement: OpenCV



Installation:

pip install openCV

Approach: 

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:




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:




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.




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:




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:


Article Tags :