python image auto gamma correction
About Gamma
Gamma correction is a nonlinear store/reduce algorithm for luminance in the dynamic range, i.e., a nonlinear operation performed on the input value so that the output value is exponential with respect to the input value;
Gamma correction adjusts the overall brightness of an image in terms of its effect. An uncorrected image may look too bright or too dark, so Gamma correction is important if you want the image to display more perfectly.
The Gamma correction is calculated as follows:
output=〖input〗^(1/Gamma)
Transform the RGB values of each pixel using the exponential function above.
Specifically perform the following conversion formulas (assuming pixel values in the range of 0 to 255):
R=〖255X(R/255)〗^((1/gamma)) G=〖255X(G/255)〗^((1/gamma)) B=〖255X(B/255)〗^((1/gamma))
Generally dealing with gamma correction is accomplished by manually adjusting the gamma value of
But if there are a lot of images, setting the gamma value manually seems too cumbersome.
This is where automatic Gamma correction is employed to convert the RGB image to grayscale, the
Calculate the mean value of the data for the grayscale plot and calculate the gamma value by using the following formula.
gamma_val = math.log10(0.5) / math.log10(mean / 255)
python implementation
import cv2 import numpy as np import math import os def gamma_trans(img, gamma): # gamma function handling gamma_table = [(x / 255.0, gamma) * 255.0 for x in range(256)] # Establishment of mapping tables gamma_table = ((gamma_table)).astype(np.uint8) # Color values are integers return (img, gamma_table) # Image color lookup table. Alternatively adaptive algorithms can be designed based on the principle of light intensity (color) homogenization. def nothing(x): pass data_base_dir = r'./1' # Enter the path to the folder outfile_dir = r'./2' # Path to the output folder list = (data_base_dir) () list2 = (outfile_dir) () for file in list: # Iterate over target folder images read_img_name = data_base_dir + '/' + () # Fetch the full path of the image image = (read_img_name) # Read in the picture img_gray = (read_img_name, 0) # grayscale map reads for gamma calculation mean = (img_gray) gamma_val = math.log10(0.5) / math.log10(mean / 255) # The formula calculates gamma image_gamma_correct = gamma_trans(image, gamma_val) # gamma transform out_img_name = outfile_dir + '/' + () (out_img_name, image_gamma_correct) print("The photo which is processed is {}".format(file))
summarize
The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.