SoFunction
Updated on 2025-03-02

A brief discussion on the use of gamma transformation in Python Opencv

Gamma transformation is used for image enhancement, which improves the dark details. Simply put, it is to use nonlinear transformation to make the image more closely related to the response of the human eye feel through the linear transformation of the exposure intensity, that is, to correct the image that is bleached (camera exposure) or too dark (underexposed).

The basic form of gamma transformation is as follows:

When it is greater than 1, the grayscale distribution histogram of the image has a tensile effect (extending the grayscale to a high grayscale value), while when it is less than 1, the grayscale distribution histogram of the image has a shrinking effect (to bring the grayscale closer to the low grayscale value).

#Segment of the histogram of each channelimg0 = ('')
hist_b = ([img0],[0],None,[256],[0,256])
hist_g = ([img0],[1],None,[256],[0,256])
hist_r = ([img0],[2],None,[256],[0,256])
def gamma_trans(img,gamma):
 #The specific method is normalized to 1 first, and then gamma is used as the exponent value to find the new pixel value and then restore it gamma_table = [(x/255.0,gamma)*255.0 for x in range(256)]
 gamma_table = ((gamma_table)).astype(np.uint8)
 #The mapping uses Opencv's table lookup function return (img0,gamma_table)
img0_corrted = gamma_trans(img0, 0.5)
('img0',img0)
('gamma_image',img0_corrted)
('gamma_image.png',img0_corrted)
#Calculate the histogram after Gamma correction by channelhist_b_c =([img0_corrted],[0],None,[256],[0,256])
hist_g_c =([img0_corrted],[1],None,[256],[0,256])
hist_r_c =([img0_corrted],[2],None,[256],[0,256])
fig = ('gamma')
pix_hists = [[hist_b, hist_g, hist_r],
    [hist_b_c, hist_g_c, hist_r_c]]
pix_vals = range(256)
for sub_plt, pix_hist in zip([121, 122], pix_hists):
 ax = fig.add_subplot(sub_plt, projection='3d')
 for c, z, channel_hist in zip(['b', 'g', 'r'], [20, 10, 0], pix_hist):
  cs = [c] * 256
  (pix_vals, channel_hist, zs=z, zdir='y', color=cs, alpha=0.618, edgecolor='none', lw=0)
 ax.set_xlabel('Pixel Values')
 ax.set_xlim([0, 256])
 ax.set_ylabel('Count')
 ax.set_zlabel('Channels')
()
()

The above brief explanation of the use of gamma transformation in Python Opencv is all the content I have shared with you. I hope you can give you a reference and I hope you can support me more.