Life2Coding
Change the Brightness and Contrast of Images using OpenCV Python

This post will be helpful in learning OpenCV using Python programming. Here I will show how to implement OpenCV functions and apply them in various aspects using some great examples. Then the output will be visualized along with the comparisons.

We will also discuss the basic of image processing and provide the detail explanation related to the OpenCV functions.

An image must have the proper brightness and contrast for easy viewing. Brightness refers to the overall lightness or darkness of the image. Contrast is the difference in brightness between objects or regions. For example, a white rabbit running across a snowy field has poor contrast, while a black dog against the same white background has good contrast.

Requirements:

First, you need to setup your Python Environment with OpenCV. You can easily do it by following Life2Coding’s tutorial on YouTube: Linking OpenCV with Python 3

Goals:

The goal is to make you understand how to change the brightness and contrast of the image using Opencv python library.

Documentation:

getTrackbarPos()

retval=cv.getTrackbarPos(trackbarname, winname)

Returns the trackbar position.

Parameters
trackbarname Name of the trackbar.
winname Name of the window that is the parent of the trackbar.

imshow()

None=cv.imshow(winname, mat)

Displays an image in the specified window.

Parameters
winname Name of the window.
mat Image to be shown.

addWeighted()

dst=cv.addWeighted(src1, alpha, src2, beta, gamma[, dst[, dtype]])

Calculates the weighted sum of two arrays.

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.
dst output array that has the same size and number of channels as the input arrays.
dtype optional depth of the output array; when both input arrays have the same depth, dtype can be set to -1, which will be equivalent to src1.depth().

putText()

img=cv.putText(img, text, org, fontFace, fontScale, color[, thickness[, lineType[, bottomLeftOrigin]]])

Draws a text string.

Parameters
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.

imread()

retval=cv.imread(filename[, flags])

Loads an image from a file.

Parameters
filename Name of file to be loaded.
flags Flag that can take values of cv::ImreadModes

namedWindow()

None=cv.namedWindow(winname[, flags])

Creates a window.

Parameters
winname Name of the window in the window caption that may be used as a window identifier.
flags Flags of the window. The supported flags are: (cv::WindowFlags)

waitKey()

retval=cv.waitKey([, delay])

Waits for a pressed key.

Parameters
delay Delay in milliseconds. 0 is the special value that means “forever”.

Steps:

  • Open the image using cv2.imread()
  • Create the brightness and contrast trackbar using cv2.createTrackbar()
  • Map the brightness and contrast value using the defined map() function
  • Define the proper function to change the brightness and contrast in order to use the cv2.addWeighted()
  • Display all the modified image using cv2.imshow()
  • Exit window and destroy all windows using cv2.destroyAllWindows()

Example Code:

import cv2

def funcBrightContrast(bright=0):
    bright = cv2.getTrackbarPos('bright', 'Life2Coding')
    contrast = cv2.getTrackbarPos('contrast', 'Life2Coding')

    effect = apply_brightness_contrast(img,bright,contrast)
    cv2.imshow('Effect', effect)

def apply_brightness_contrast(input_img, brightness = 255, contrast = 127):
    brightness = map(brightness, 0, 510, -255, 255)
    contrast = map(contrast, 0, 254, -127, 127)

    if brightness != 0:
        if brightness > 0:
            shadow = brightness
            highlight = 255
        else:
            shadow = 0
            highlight = 255 + brightness
        alpha_b = (highlight - shadow)/255
        gamma_b = shadow

        buf = cv2.addWeighted(input_img, alpha_b, input_img, 0, gamma_b)
    else:
        buf = input_img.copy()

    if contrast != 0:
        f = float(131 * (contrast + 127)) / (127 * (131 - contrast))
        alpha_c = f
        gamma_c = 127*(1-f)

        buf = cv2.addWeighted(buf, alpha_c, buf, 0, gamma_c)

    cv2.putText(buf,'B:{},C:{}'.format(brightness,contrast),(10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
    return buf

def map(x, in_min, in_max, out_min, out_max):
    return int((x-in_min) * (out_max-out_min) / (in_max-in_min) + out_min)

if __name__ == '__main__':

    original = cv2.imread("./hanif.jpg", 1)
    img = original.copy()

    cv2.namedWindow('Life2Coding',1)

    bright = 255
    contrast = 127

    #Brightness value range -255 to 255
    #Contrast value range -127 to 127

    cv2.createTrackbar('bright', 'Life2Coding', bright, 2*255, funcBrightContrast)
    cv2.createTrackbar('contrast', 'Life2Coding', contrast, 2*127, funcBrightContrast)
    funcBrightContrast(0)
    cv2.imshow('Life2Coding', original)


cv2.waitKey(0)

Output:

5cc146c99b654 Change the Brightness and Contrast of Images using OpenCV Python
life2coding_icon [] Change the Brightness and Contrast of Images using OpenCV Python

2 thoughts on “Change the Brightness and Contrast of Images using OpenCV Python

  1. Mariel

    Hi!! I´m not able to use the trackbars properly. If I want to change the value I cannot and always returns to the values of bright = 255 and contrast = 127. In many words, trackbars do not make any change to Effect.
    What would I do in this case?
    Thank you!!! 😀

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.