I would like to suggest a method using the LAB color space.

LAB color space expresses color variations across three channels. One channel for brightness and two channels for color:

  • L-channel: representing lightness in the image
  • a-channel: representing change in color between red and green
  • b-channel: representing change in color between yellow and blue

In the following I perform adaptive histogram equalization on the L-channel and convert the resulting image back to BGR color space. This enhances the brightness while also limiting contrast sensitivity. I have done the following using OpenCV 3.0.0 and python:

Code:

import cv2
import numpy as np

img = cv2.imread('flower.jpg', 1)
# converting to LAB color space
lab= cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
l_channel, a, b = cv2.split(lab)

# Applying CLAHE to L-channel
# feel free to try different values for the limit and grid size:
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
cl = clahe.apply(l_channel)

# merge the CLAHE enhanced L-channel with the a and b channel
limg = cv2.merge((cl,a,b))

# Converting image from LAB Color model to BGR color spcae
enhanced_img = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)

# Stacking the original image with the enhanced image
result = np.hstack((img, enhanced_img))
cv2.imshow('Result', result)

Result:

The enhanced image is on the right

More info on LAB color space click here

You can run the code as it is. To know what CLAHE (Contrast Limited Adaptive Histogram Equalization) is about, refer this Wikipedia page

Answer from Jeru Luke on Stack Overflow
๐ŸŒ
OpenCV
docs.opencv.org โ€บ 4.13.0 โ€บ d3 โ€บ dc1 โ€บ tutorial_basic_linear_transform.html
OpenCV: Changing the contrast and brightness of an image!
The parameters \(\alpha > 0\) and \(\beta\) are often called the gain and bias parameters; sometimes these parameters are said to control contrast and brightness respectively.
Top answer
1 of 7
93

I would like to suggest a method using the LAB color space.

LAB color space expresses color variations across three channels. One channel for brightness and two channels for color:

  • L-channel: representing lightness in the image
  • a-channel: representing change in color between red and green
  • b-channel: representing change in color between yellow and blue

In the following I perform adaptive histogram equalization on the L-channel and convert the resulting image back to BGR color space. This enhances the brightness while also limiting contrast sensitivity. I have done the following using OpenCV 3.0.0 and python:

Code:

import cv2
import numpy as np

img = cv2.imread('flower.jpg', 1)
# converting to LAB color space
lab= cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
l_channel, a, b = cv2.split(lab)

# Applying CLAHE to L-channel
# feel free to try different values for the limit and grid size:
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
cl = clahe.apply(l_channel)

# merge the CLAHE enhanced L-channel with the a and b channel
limg = cv2.merge((cl,a,b))

# Converting image from LAB Color model to BGR color spcae
enhanced_img = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)

# Stacking the original image with the enhanced image
result = np.hstack((img, enhanced_img))
cv2.imshow('Result', result)

Result:

The enhanced image is on the right

More info on LAB color space click here

You can run the code as it is. To know what CLAHE (Contrast Limited Adaptive Histogram Equalization) is about, refer this Wikipedia page

2 of 7
78

For Python, I haven't found an OpenCV function that provides contrast. As others have suggested, there are some techniques to automatically increase contrast using a very simple formula.

In the official OpenCV docs, it is suggested that this equation can be used to apply both contrast and brightness at the same time:

new_img = alpha*old_img + beta

where alpha corresponds to a contrast and beta is brightness. Different cases

alpha 1  beta 0      --> no change  
0 < alpha < 1        --> lower contrast  
alpha > 1            --> higher contrast  
-127 < beta < +127   --> good range for brightness values

In C/C++, you can implement this equation using cv::Mat::convertTo, but we don't have access to that part of the library from Python. To do it in Python, I would recommend using the cv::addWeighted function, because it is quick and it automatically forces the output to be in the range 0 to 255 (e.g. for a 24 bit color image, 8 bits per channel). You could also use convertScaleAbs as suggested by @nathancy.

import cv2
img = cv2.imread('input.png')
# call addWeighted function. use beta = 0 to effectively only operate one one image
out = cv2.addWeighted( img, contrast, img, 0, brightness)
output = cv2.addWeighted

The above formula and code is quick to write and will make changes to brightness and contrast. But they yield results that are significantly different than photo editing programs. The rest of this answer will yield a result that will reproduce the behavior in the GIMP and also LibreOffice brightness and contrast. It's more lines of code, but it gives a nice result.

Contrast

In the GIMP, contrast levels go from -127 to +127. I adapted the formulas from here to fit in that range.

f = 131*(contrast + 127)/(127*(131-contrast))
new_image = f*(old_image - 127) + 127 = f*(old_image) + 127*(1-f)

To figure out brightness, I figured out the relationship between brightness and levels and used information in this levels post to arrive at a solution.

#pseudo code
if brightness > 0
    shadow = brightness
    highlight = 255
else:
    shadow = 0
    highlight = 255 + brightness
new_img = ((highlight - shadow)/255)*old_img + shadow

brightness and contrast in Python and OpenCV

Putting it all together and adding using the reference "mandrill" image from USC SIPI:

import cv2
import numpy as np

# Open a typical 24 bit color image. For this kind of image there are
# 8 bits (0 to 255) per color channel
img = cv2.imread('mandrill.png')  # mandrill reference image from USC SIPI

s = 128
img = cv2.resize(img, (s,s), 0, 0, cv2.INTER_AREA)

def apply_brightness_contrast(input_img, brightness = 0, contrast = 0):
    
    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 = 131*(contrast + 127)/(127*(131-contrast))
        alpha_c = f
        gamma_c = 127*(1-f)
        
        buf = cv2.addWeighted(buf, alpha_c, buf, 0, gamma_c)

    return buf


font = cv2.FONT_HERSHEY_SIMPLEX
fcolor = (0,0,0)

blist = [0, -127, 127,   0,  0, 64] # list of brightness values
clist = [0,    0,   0, -64, 64, 64] # list of contrast values


out = np.zeros((s*2, s*3, 3), dtype = np.uint8)

for i, b in enumerate(blist):
    c = clist[i]
    print('b, c:  ', b,', ',c)
    row = s*int(i/3)
    col = s*(i%3)
    
    print('row, col:   ', row, ', ', col)
    
    out[row:row+s, col:col+s] = apply_brightness_contrast(img, b, c)
    msg = 'b %d' % b
    cv2.putText(out,msg,(col,row+s-22), font, .7, fcolor,1,cv2.LINE_AA)
    msg = 'c %d' % c
    cv2.putText(out,msg,(col,row+s-4), font, .7, fcolor,1,cv2.LINE_AA)
    
    cv2.putText(out, 'OpenCV',(260,30), font, 1.0, fcolor,2,cv2.LINE_AA)

cv2.imwrite('out.png', out)

I manually processed the images in the GIMP and added text tags in Python/OpenCV:

Note: @UtkarshBhardwaj has suggested that Python 2.x users must cast the contrast correction calculation code into float for getting floating result, like so:

...
if contrast != 0:
        f = float(131*(contrast + 127))/(127*(131-contrast))
...
๐ŸŒ
PyImageSearch
pyimagesearch.com โ€บ home โ€บ blog โ€บ detecting low contrast images with opencv, scikit-image, and python
Detecting low contrast images with OpenCV, scikit-image, and Python - PyImageSearch
April 17, 2021 - In this tutorial you learned how to detect low contrast images in both static scenes and real-time video streams. We used both the OpenCV library and the scikit-image package to develop our low contrast image detector.
๐ŸŒ
Opencv-srf
opencv-srf.com โ€บ 2018 โ€บ 02 โ€บ change-contrast-of-images-and-videos.html
Change Contrast - OpenCV Tutorial C++
Please note that you have to replace "D:/My OpenCV Website/A Herd of Deer Running.mp4" in the code with a valid location to a video in your computer. Then you should see a set of videos with their contrast increased and decreased along with the original video.
๐ŸŒ
Analytics Vidhya
analyticsvidhya.com โ€บ home โ€บ understanding image contrast with opencv in python
Understanding Image Contrast With OpenCV in Python - Analytics Vidhya
October 24, 2024 - Essentially what happens when we enhance contrast is: We try to find the most common pixel value in the image, and attempt to standardize (bring to a common pixel range) most/all pixels on the image, therefore, creating a more uniform visual ...
๐ŸŒ
OpenCV Courses
opencv.courses โ€บ blog โ€บ image-contrast-enhancement-illuminating-perspectives-with-opencv
Image Contrast Enhancement: Illuminating Perspectives with OpenCV | Open CV Courses
In this example, the cv2.normalize function is employed on the Y channel of the image to stretch the contrast of the image, ensuring optimal utilization of the intensity range. Tonal enhancement focuses on refining the finer details within the image, often enhancing specific features or regions of interest. OpenCV provides a plethora of tools for tonal enhancement, including histogram equalization and adaptive histogram equalization.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ opencv-understanding-contrast-in-an-image
OpenCV | Understanding Contrast in an Image | GeeksforGeeks
August 29, 2019 - As here in our output image, the ... of an image is a very basic task to perform. By changing the image contrast, it is meant to change the value of each and every image pixel....
๐ŸŒ
DEV Community
dev.to โ€บ jarvissan22 โ€บ cv2-what-is-an-image-lets-adjust-the-brightness-and-contrast-of-an-image-35po
CV2: What is an Image?, Lets adjust the Brightness and Contrast of an image - DEV Community
November 29, 2024 - Mathematically, brightness and contrast can be adjusted using the formula: ... The cv2.convertScaleAbs() function in OpenCV automates this process.
Find elsewhere
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ opencv-hands-on-image-contrast
OpenCV | Hands on Image Contrast - GeeksforGeeks
April 13, 2021 - Syntax: contrast(n, cb) Parameter: n: This parameter stores the amount to adjust the contrast, a number between -1 and +1cb: This is an optional parameter that is invoked whe ... In this article, we will learn how to Blur an image using Python ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ machine learning โ€บ image-enhancement-techniques-using-opencv-python
Image Enhancement Techniques using OpenCV - Python - GeeksforGeeks
June 15, 2026 - Contrast controls the difference between bright and dark areas. Proper adjustment helps reveal details and improve image quality. OpenCV provides the cv2.addWeighted() function for this purpose.
๐ŸŒ
OpenCV
docs.opencv.org โ€บ 4.x โ€บ d4 โ€บ d32 โ€บ group__photo__decolor.html
OpenCV: Contrast Preserving Decolorization
Contrast Preserving Decolorization ยท Computational Photography ยท Useful links: http://www.cse.cuhk.edu.hk/leojia/projects/color2gray/index.html ยท #include <opencv2/photo.hpp> Transforms a color image to a grayscale image. It is a basic tool in digital printing, stylized black-and-white ...
๐ŸŒ
OpenCV
docs.opencv.org โ€บ 2.4 โ€บ doc โ€บ tutorials โ€บ core โ€บ basic_linear_transform โ€บ basic_linear_transform.html
Changing the contrast and brightness of an image! โ€” OpenCV 2.4.13.7 documentation
December 31, 2019 - #include <cv.h> #include <highgui.h> #include <iostream> using namespace cv; double alpha; /**< Simple contrast control */ int beta; /**< Simple brightness control */ int main( int argc, char** argv ) { /// Read image given by user Mat image = imread( argv[1] ); Mat new_image = Mat::zeros( image.size(), image.type() ); /// Initialize values std::cout<<" Basic Linear Transforms "<<std::endl; std::cout<<"-------------------------"<<std::endl; std::cout<<"* Enter the alpha value [1.0-3.0]: ";std::cin>>alpha; std::cout<<"* Enter the beta value [0-100]: "; std::cin>>beta; /// Do the operation new_i
๐ŸŒ
MakeUseOf
makeuseof.com โ€บ home โ€บ programming โ€บ master image enhancement techniques with opencv
Master Image Enhancement Techniques With OpenCV
June 13, 2023 - The cv2.convertScaleAbs function adjusts the brightness of the image. The alpha parameter controls the contrast, while the beta parameter controls the brightness.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ changing-the-contrast-and-brightness-of-an-image-using-python-opencv
Changing the contrast and brightness of an image using Python - OpenCV - GeeksforGeeks
January 3, 2023 - 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.
๐ŸŒ
YouTube
youtube.com โ€บ watch
Python Computer Vision part 5 - OpenCV Brightness and Contrast - YouTube
Access the complete course: https://academy.zenva.com/product/the-complete-computer-vision-course-with-python/?zva_src=youtube-python-cvWhat if you could lea
Published: June 22, 2016
๐ŸŒ
OpenCV
docs.opencv.org โ€บ 3.4.20 โ€บ d5 โ€บ daf โ€บ tutorial_py_histogram_equalization.html
OpenCV: Histograms - 2: Histogram Equalization
If any histogram bin is above the specified contrast limit (by default 40 in OpenCV), those pixels are clipped and distributed uniformly to other bins before applying histogram equalization.
๐ŸŒ
OpenCV Q&A Forum
answers.opencv.org โ€บ question โ€บ 228920 โ€บ how-can-i-increase-contrast-in-binary-picturepython
How can I increase contrast in binary picture?(python) - OpenCV Q&A Forum
April 12, 2025 - #!/usr/bin/python37 #OpenCV 4.3.0, Raspberry pi 3B+/4B, Buster v10. #Date: 12th April, 2020 import cv2 image = cv2.imread('printed_circuit4_.jpg') alpha = 3.9 # Contrast control (1.0-3.0) beta = 0 # Brightness control (0-100) adjusted = cv2.convertScaleAbs(image, alpha=alpha, beta=beta) cv2.imwrite('Contrast_board.jpg', adjusted) cv2.imshow('Contrast Printed Circuit', adjusted) cv2.waitKey(0)
๐ŸŒ
Jancy Standard Library
vovkos.github.io โ€บ doxyrest-showcase โ€บ opencv โ€บ sphinxdoc โ€บ page_tutorial_basic_linear_transform.html
Changing the contrast and brightness of an image! โ€” OpenCV Documentation
The parameters \(\alpha > 0\) and \(\beta\) are often called the gain and bias parameters; sometimes these parameters are said to control contrast and brightness respectively. You can think of \(f(x)\) as the source image pixels and \(g(x)\) as the output image pixels. Then, more conveniently we can write the expression as: ... #include "opencv2/imgcodecs.hpp" #include "opencv2/highgui.hpp" #include <iostream> using namespace std; using namespace cv; int main( int, char** argv ) { double alpha = 1.0; /*< Simple contrast control */ int beta = 0; /*< Simple brightness control */ Mat image = imre
๐ŸŒ
OpenCV
forum.opencv.org โ€บ c++
How can I change brightness&contrast of image - C++ - OpenCV
February 13, 2023 - I have gui for it and there is 2 sliders in gui: cv::Mat img = ... ; sliderBrightness(int value){ cv::Mat imgB = img + cv::Scalar(value * 255/100.0); //I am currently changing brightness like this but not sure ...