图像直方图均衡化算法实现 python和matlab

一. 直方图均衡化:

        直方图均衡化是使图像直方图变得平坦的操作。直方图均衡化能够有效地解决图像整体过暗、过亮的问题,增加图像的清晰度。

        具体流程如下所示。其中S是总的像素数,Zmax是像素的最大取值(8位灰度图像为255),h(i)为图像像素取值为 i 及 小于 i 的像素的总数。


直方图均衡化算法 ↑
 

二. python实现直方图均衡化操作

 1 import cv2
 2 import numpy as np
 3 import matplotlib.pyplot as plt
 4 
 5 # histogram equalization
 6 def hist_equal(img, z_max=255):
 7     H, W = img.shape
 8     # S is the total of pixels
 9     S = H * W  * 1.
10 
11     out = img.copy()
12 
13     sum_h = 0.
14 
15     for i in range(1, 255):
16         ind = np.where(img == i)
17         sum_h += len(img[ind])
18         z_prime = z_max / S * sum_h
19         out[ind] = z_prime
20 
21     out = out.astype(np.uint8)
22 
23     return out
24 
25 
26 # Read image
27 img = cv2.imread("../head_g_n.jpg",0).astype(np.float)
28 
29 # histogram normalization
30 out = hist_equal(img)
31 
32 # Display histogram
33 plt.hist(out.ravel(), bins=255, rwidth=0.8, range=(0, 255))
34 plt.savefig("out_his.png")
35 plt.show()
36 
37 # Save result
38 cv2.imshow("result", out)
39 cv2.imwrite("out.jpg", out)
40 cv2.waitKey(0)
41 cv2.destroyAllWindows()

三. 实验结果:


原图 ↑

原图的像素分布直方图 ↑
 

直方图均衡化后图像 ↑

均衡化后图像的直方图 ↑
 

        可以看到,直方图均衡化后的图像看起来比原来的图像更加清晰。对于图像亮度整体偏暗或者偏亮的图像,我们可以采用直方图均衡化的方法处理图像,使得它们看上去更加清晰。


四. matlab 实现图像直方图均衡化:

        可以参考一篇优秀的博文:        https://blog.csdn.net/Ibelievesunshine/article/details/79961027


五. 参考内容:

  https://www.jianshu.com/p/792b0ae5ba6d

原文地址:https://www.cnblogs.com/wojianxin/p/12510797.html