天天看點

大白話直方圖均衡

用一句大白話說一下直方圖均衡的概念,直方圖均衡(histogram equalization)是通過讓原圖的每個像素點的灰階值通過某個函數變換成另一個值,來提高原圖的對比度,具體的函數方程為output = L*T(input)其中output為映射後的灰階值,L為灰階級255,T(r)為灰階值r的累積分布機率,計算方法:灰階值為r及以下的像素點總個數數/總像素點數。

對于數學上的一些分析,這裡就不寫了,想了解具體的可以看

這裡

以下是效果圖檔和代碼:

原圖

大白話直方圖均衡
大白話直方圖均衡
直方圖均衡之後
大白話直方圖均衡
大白話直方圖均衡

# img_hist = cv2.calcHist(img, [1], None, [256], [0, 256])另一個計算直方圖的函數
plt.hist(img[:,:,0].flatten(), 256, [0, 256], color = 'r')
# plt.plot(img_hist)
plt.title('original')
plt.show()
img_yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)
# equalize the histogram of the Y channel
img_yuv[:,:,0] = cv2.equalizeHist(img_yuv[:,:,0])   # only for 1 channel
plt.hist(img_yuv[:,:,0].flatten(), 256, [0, 256], color='r')
img_output = cv2.cvtColor(img_yuv, cv2.COLOR_YUV2BGR)   # y: luminance
# img_equalized_hist = cv2.calcHist(img_yuv, [1], None, [256], [0, 256])
# plt.plot(img_equalized_hist)
plt.title('equalized')
plt.show()
# convert the YUV image back to RGB format
cv2.imwrite(path, img_output)
cv2.imshow('Color input image', img)
cv2.imshow('Histogram equalized', img_output)
key = cv2.waitKey(0)
cv2.destroyAllWindows()