def gray_histogram_equalization(img_arr):
# 根据像素灰度统计结果来显示灰度直方图
hist, bins = np.histogram(img_arr.flatten(), 4096, [0, 4095])
cdf = hist.cumsum()
cdf_normalized = cdf * hist.max() / cdf.max()
cdf_m = np.ma.masked_equal(cdf, 0)
cdf_m = (cdf_m - cdf_m.min())*255/(cdf_m.max()-cdf_m.min())
cdf = np.ma.filled(cdf_m, 0).astype('uint8')
print('cdf img arr', img_arr)
print('cdf img arr dtype:', img_arr.dtype)
equalized_img = cdf[img_arr]
equalized_img = equalized_img.astype('uint16')
print('max equalized img:', equalized_img.max())
print('min equalized img:', equalized_img.min())
return equalized_img
cv2本身自带的直方图均衡化函数库只能用于8位的图像(0-255),这分代码参考官网上关于均衡化8位图像的另一种写法,其他位数的灰度图像做出相应改动即可。