直方图均衡化算法
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
# 直方图均衡化
def histeq(imarr):
hist, bins = np.histogram(imarr, 255)
cdf = np.cumsum(hist)
cdf = 255 * (cdf / cdf[-1])
res = np.interp(imarr.flatten(), bins[:-1], cdf)
res = res.reshape(imarr.shape)
return res, hist
img = Image.open("E:/pythontupian/6.jpg")
gray_image = img.convert('L')
gray_arr = np.array(gray_image)
plt.imshow(Image.fromarray(gray_arr),cmap='gray')
plt.axis("off")
plt.show()
plt.hist(gray_arr.flatten(), 256) # flatten可以将矩阵转化成一维序列
plt.show()
res, hist = histeq(gray_arr)
plt.imshow(Image.fromarray(res))
plt.axis("off")
plt.show()
plt.hist(res.flatten(), 256) # flatten可以将矩阵转化成一维序列
plt.show()
结果显示
原始灰度图:
原始灰度图的直方图:
均衡化后灰度图:
均衡化后的直方图:
使用plt.imshow()显示的时候要注意,设置cmap参数为‘gray’,如果不用的话可能会出现下面的错误:
具体原因可以了解一下cmap的用法。