直方图均衡化
1.大致思路
- 首先求出原图片的直方图,即图片中每个灰度值的具体像素点数量,具体函数为
cv2.calcHist([img],[0],None,[256],[0,255])
,再除以该图片的总像素点(h*w)求出其概率,并将结果放置hist数组。
- 利用累积分布函数,设置一个新的数组sum_hist,求出从0到i的所有灰度值所对应的像素点数的概率,即 sum_hist[i] = sum(hist[0:i+1])。
- 对于新建立的sum_hist,要对其乘上(L-1),并且由于灰度值是整数,所以要对结果进行四舍五入。注意此时的数组存放的键值对,是对于每个原始图片的灰度值->处理之后的图片灰度值。
- 最后新建图片equal_img,存放结果数据。
2. 具体代码实现
import matplotlib.pyplot as plt
import cv2
import numpy as np
img = "part-00264-919.jpg"
def def_equalizehist(img,L=256):
img = cv2.imread(img,0)
cv2.imshow("ori",img)
h, w = img.shape
hist = cv2.calcHist([img],[0],None,[256],[0,255])
hist[0:255] = hist[0:255] / (h*w)
sum_hist = np.zeros(hist.shape)
for i in range(256):
sum_hist[i] = sum(hist[0:i+1])
equal_hist = np.zeros(sum_hist.shape)
for i in range(256):
equal_hist[i] = int(((L - 1) - 0) * sum_hist[i] + 0.5)
equal_img = img.copy()
for i in range(h):
for j in range(w):
equal_img[i, j] = equal_hist[img[i, j]]
equal_hist = cv2.calcHist([equal_img], [0], None, [256], [0, 256])
equal_hist[0:255] = equal_hist[0:255] / (h * w)
cv2.imshow("inverse", equal_img)
plt.plot(hist, color='b')
plt.show()
plt.plot(equal_hist, color='r')
plt.show()
cv2.waitKey()
return [equal_img, equal_hist]
def_equalizehist(img)