Here are two ways to do that in Python/OpenCV. Both are based upon the ratio of the log(mid-gray)/log(mean). Results are often reasonable, especially for dark image, but do not work in all cases. For bright image, invert the gray or value image, process as for dark images, then invert again and recombine if using the value image.

  • Read the input
  • Convert to gray or HSV value
  • Compute the ratio log(mid-gray)/log(mean) on the gray or value channel
  • Raise the input or value to the power of the ratio
  • If using the value channel, combine the new value channel with the hue and saturation channels and convert back to RGB

Input:

import cv2
import numpy as np
import math

# read image
img = cv2.imread('lioncuddle1.jpg')

# METHOD 1: RGB

# convert img to gray
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# compute gamma = log(mid*255)/log(mean)
mid = 0.5
mean = np.mean(gray)
gamma = math.log(mid*255)/math.log(mean)
print(gamma)

# do gamma correction
img_gamma1 = np.power(img, gamma).clip(0,255).astype(np.uint8)



# METHOD 2: HSV (or other color spaces)

# convert img to HSV
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
hue, sat, val = cv2.split(hsv)

# compute gamma = log(mid*255)/log(mean)
mid = 0.5
mean = np.mean(val)
gamma = math.log(mid*255)/math.log(mean)
print(gamma)

# do gamma correction on value channel
val_gamma = np.power(val, gamma).clip(0,255).astype(np.uint8)

# combine new value channel with original hue and sat channels
hsv_gamma = cv2.merge([hue, sat, val_gamma])
img_gamma2 = cv2.cvtColor(hsv_gamma, cv2.COLOR_HSV2BGR)

# show results
cv2.imshow('input', img)
cv2.imshow('result1', img_gamma1)
cv2.imshow('result2', img_gamma2)
cv2.waitKey(0)
cv2.destroyAllWindows()

# save results
cv2.imwrite('lioncuddle1_gamma1.jpg', img_gamma1)
cv2.imwrite('lioncuddle1_gamma2.jpg', img_gamma2)


Result from method 1:

Result from method 2:

Answer from fmw42 on Stack Overflow
๐ŸŒ
PyImageSearch
pyimagesearch.com โ€บ home โ€บ blog โ€บ opencv gamma correction
OpenCV Gamma Correction - PyImageSearch
April 22, 2021 - There are two (easy) ways to apply gamma correction using OpenCV and Python. The first method is to simply leverage the fact that Python + OpenCV represents images as NumPy arrays.
Top answer
1 of 1
14

Here are two ways to do that in Python/OpenCV. Both are based upon the ratio of the log(mid-gray)/log(mean). Results are often reasonable, especially for dark image, but do not work in all cases. For bright image, invert the gray or value image, process as for dark images, then invert again and recombine if using the value image.

  • Read the input
  • Convert to gray or HSV value
  • Compute the ratio log(mid-gray)/log(mean) on the gray or value channel
  • Raise the input or value to the power of the ratio
  • If using the value channel, combine the new value channel with the hue and saturation channels and convert back to RGB

Input:

import cv2
import numpy as np
import math

# read image
img = cv2.imread('lioncuddle1.jpg')

# METHOD 1: RGB

# convert img to gray
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# compute gamma = log(mid*255)/log(mean)
mid = 0.5
mean = np.mean(gray)
gamma = math.log(mid*255)/math.log(mean)
print(gamma)

# do gamma correction
img_gamma1 = np.power(img, gamma).clip(0,255).astype(np.uint8)



# METHOD 2: HSV (or other color spaces)

# convert img to HSV
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
hue, sat, val = cv2.split(hsv)

# compute gamma = log(mid*255)/log(mean)
mid = 0.5
mean = np.mean(val)
gamma = math.log(mid*255)/math.log(mean)
print(gamma)

# do gamma correction on value channel
val_gamma = np.power(val, gamma).clip(0,255).astype(np.uint8)

# combine new value channel with original hue and sat channels
hsv_gamma = cv2.merge([hue, sat, val_gamma])
img_gamma2 = cv2.cvtColor(hsv_gamma, cv2.COLOR_HSV2BGR)

# show results
cv2.imshow('input', img)
cv2.imshow('result1', img_gamma1)
cv2.imshow('result2', img_gamma2)
cv2.waitKey(0)
cv2.destroyAllWindows()

# save results
cv2.imwrite('lioncuddle1_gamma1.jpg', img_gamma1)
cv2.imwrite('lioncuddle1_gamma2.jpg', img_gamma2)


Result from method 1:

Result from method 2:

๐ŸŒ
Lindevs
lindevs.com โ€บ apply-gamma-correction-to-an-image-using-opencv
Apply Gamma Correction to an Image using OpenCV | Lindevs
November 2, 2022 - import cv2 import numpy as np def gammaCorrection(src, gamma): invGamma = 1 / gamma table = [((i / 255) ** invGamma) * 255 for i in range(256)] table = np.array(table, np.uint8) return cv2.LUT(src, table) img = cv2.imread('test.jpg') gammaImg = gammaCorrection(img, 2.2) cv2.imshow('Original image', img) cv2.imshow('Gamma corrected image', gammaImg) cv2.waitKey(0) cv2.destroyAllWindows() #include <opencv2/opencv.hpp> using namespace cv; void gammaCorrection(const Mat &src, Mat &dst, const float gamma) { float invGamma = 1 / gamma; Mat table(1, 256, CV_8U); uchar *p = table.ptr(); for (int i = 0
๐ŸŒ
GitHub
github.com โ€บ atapour โ€บ ip-python-opencv โ€บ blob โ€บ main โ€บ gamma_correction.py
ip-python-opencv/gamma_correction.py at main ยท atapour/ip-python-opencv
Examples and code demonstrations for the Image Processing module at Durham University - ip-python-opencv/gamma_correction.py at main ยท atapour/ip-python-opencv
Author: atapour
๐ŸŒ
Medium
medium.com โ€บ @daniel.lepold โ€บ image-processing-in-python-gamma-correction-homography-transformation-and-face-detection-with-7c806a587186
Face Detection from ID Cards in Python using OpenCV: Gamma Correction & Homography | by Daniel Lepold | Medium
May 6, 2025 - Gamma correction is a method that allows nonlinear adjustment of an imageโ€™s brightness. The adjust_gamma() function applies gamma correction using a precomputed lookup table. A gamma value > 1 makes the image brighter, while a gamma value ...
๐ŸŒ
DEV Community
dev.to โ€บ tinazhouhui โ€บ discovering-opencv-with-python-gamma-correction-3cnh
Discovering OpenCV with Python: Gamma correction - DEV Community
January 11, 2023 - Another practical exercise that I had quite some fun with was gamma correction. This concept is mainly used when we want to adjust the brightness of an image. We could also use it to restore the faded pictures to their previous depth of colour. Since I am just a Python Padawan, we will be demonstrating this on grayscale pictures but I promise, the concept works on coloured images as well.
๐ŸŒ
Medium
medium.com โ€บ @sinhaaa003 โ€บ transforming-images-rgb-to-grayscale-and-gamma-correction-with-python-fe5a0afa12b9
Transforming Images: RGB to Grayscale and Gamma Correction with Python | by Aditya Sinha | Medium
July 30, 2024 - Python Programming ยท Machine Learning ยท Data Science ยท Opencv ยท Aditya Sinha ยท 4 min read ยท ยทJul 30, 2024 ยท -- Listen ยท Share ยท By Aditya Sinha and Bhumikamohan ยท Welcome to the fascinating world of image processing! In this article, we, Aditya Sinha and Bhumika M, will guide you through two fundamental yet powerful transformations: converting an RGB image to grayscale and applying gamma correction.
๐ŸŒ
YouTube
youtube.com โ€บ watch
OpenCV 13: Gamma Correction to Increase or Decrease Brightness | Python | OpenCV - YouTube
OpenCV 13: Gamma Correction to Increase or Decrease Brightness | Python | OpenCVGitHub JupyterNotebook: https://github.com/siddiquiamir/OpenCVGitHub Data: ht...
Published: August 21, 2023
Find elsewhere
Top answer
1 of 3
36

I know I am late, but I would suggest using gamma correction.

Now what is gamma correction?

I will make it clear in layman's terms:

  • To display image on a screen, input voltage is needed.
  • This voltage is output as light intensity.
  • In perfect world, input voltage would be linear to output intensity.
  • But the real screen output is close to an exponential curve, the exponent being gamma.

Since the computer screen applies a gamma value to the image on screen, the process of applying inverse gamma to counter this effect is called gamma correction.

Here is the code for the same using OpenCV 3.0.0 and python:

import cv2
import numpy as np

def adjust_gamma(image, gamma=1.0):

   invGamma = 1.0 / gamma
   table = np.array([((i / 255.0) ** invGamma) * 255
      for i in np.arange(0, 256)]).astype("uint8")

   return cv2.LUT(image, table)

x = 'C:/Users/524316/Desktop/stack/test.jpg'  #location of the image
original = cv2.imread(x, 1)
cv2.imshow('original',original)

gamma = 0.5                                   # change the value here to get different result
adjusted = adjust_gamma(original, gamma=gamma)
cv2.putText(adjusted, "g={}".format(gamma), (10, 30),cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 3)
cv2.imshow("gammam image 1", adjusted)

cv2.waitKey(0)
cv2.destroyAllWindows()

Here is the original image:

Applying gamma of value 0.5 will yield:

Applying gamma of value 1.5 will yield:

Applying gamma of value 2.5 will yield:

Applying gamma of value 1.0 will yield the same image.

Code was borrowed from this link

2 of 3
5

I think you can done this with opencv. Here is my suggestion

import cv2
import numpy as np

img1 = cv2.imread('abc.jpg')
a = np.double(img1)
b = a + 15
img2 = np.uint8(b)
cv2.imshow("frame",img1)
cv2.imshow("frame2",img2)
cv2.waitKey(0)
cv2.destroyAllWindows()

Here i increased the brightness of image. If you use subtraction that will makes darker.

๐ŸŒ
LinuxTut
linuxtut.com โ€บ en โ€บ c3cd5475663c41d9f154
Gamma correction without using OpenCV
May 13, 2020 - The image processing library OpenCV also has a gamma correction function. As you can see from the formula, it's so easy that you can create a gamma correction function with just numpy. ... Let's create a gamma correction function based on the formula. For a moment.
๐ŸŒ
OpenCV
forum.opencv.org โ€บ python
Auto selection of Gamma value for image brightness - Python - OpenCV
January 19, 2021 - I have a sequence of images or live video and I want to check if the image is darker or brighter, then adjust the brightness using gamma correction i.e. Image ^ gamma. gamma = 1 do nothing and smaller than 1 value of gaโ€ฆ
๐ŸŒ
GitHub
github.com โ€บ leowang7 โ€บ iagcwd
GitHub - leowang7/iagcwd: An improved contrast enhancement method for image. :camera: ยท GitHub
This is an python implementation of the paper "Contrast enhancement of brightness-distorted images by improved adaptive gamma correction." at https://arxiv.org/abs/1709.04427. The purpose of the algorithm is to improve the contrast of the image ...
Starred by 69 users
Forked by 18 users
Languages: Python
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 59802257 โ€บ problem-on-gamma-correction-with-opencv-python
Problem on gamma correction with OpenCV python - Stack Overflow
January 18, 2020 - # USAGE # python adjust_gamma.py # import the necessary packages from __future__ import print_function import numpy as np import argparse import cv2 def adjust_gamma(image, gamma=1.0): # build a lookup table mapping the pixel values [0, 255] to # their adjusted gamma values invGamma = 1.0 / gamma table = np.array([((i / 255.0) ** invGamma) * 255 for i in np.arange(0, 256)]).astype("uint8") # apply gamma correction using the lookup table return cv2.LUT(image, table) # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=Tr
๐ŸŒ
Hakky Handbook
book.st-hakky.com โ€บ hakky handbook โ€บ data science โ€บ gamma correction: a guide for data scientists
Gamma Correction: A Guide for Data Scientists | Hakky Handbook
1 month ago - Explains how to implement gamma correction using Python and OpenCV, highlighting RGB value ranges and clipping considerations.
๐ŸŒ
YouTube
youtube.com โ€บ watch
Lecture 7 Image Gamma transformation OpenCV Python - YouTube
Image gamma transformation or power law transformation
Published: January 16, 2018
๐ŸŒ
OpenCV
docs.opencv.org โ€บ 3.4.20 โ€บ d3 โ€บ dc1 โ€บ tutorial_basic_linear_transform.html
OpenCV: Changing the contrast and brightness of an image!
After \( \alpha \), \( \beta \) ... in the right. After gamma correction, the histogram is shifted to the right but the pixels in the dark regions are more shifted (see the gamma curves figure) than those in the bright regions....
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-intensity-transformation-operations-on-images
Python | Intensity Transformation Operations on Images | GeeksforGeeks
January 4, 2023 - import cv2 import numpy as np # Open the image. img = cv2.imread('sample.jpg') # Trying 4 gamma values. for gamma in [0.1, 0.5, 1.2, 2.2]: # Apply gamma correction. gamma_corrected = np.array(255*(img / 255) ** gamma, dtype = 'uint8') # Save edited ...
๐ŸŒ
Medium
medium.com โ€บ @pontus.bergmark โ€บ intro-to-image-processing-in-opencv-with-python-1c7f94af18a7
Intro to Image Processing in OpenCV with Python | by Pontus Bergmark | Medium
October 11, 2018 - The above transformation uses r ... we have different results. So the gamma correction is the process of choosing the best value for gamma to have the best output image....