# 5.2. 直方图-2：直方图均衡化¶

## 5.2.1. 目标¶

• 我们将学习直方图均衡化的概念，并使用它来提高图像的对比度。

## 5.2.2. 理论¶

>>> %matplotlib inline
>>>
>>> import cv2
>>> import numpy as np
>>> from matplotlib import pyplot as plt
>>>
>>>
>>> hist,bins = np.histogram(img.flatten(),256,[0,256])
>>>
>>> cdf = hist.cumsum()
>>> cdf_normalized = cdf * hist.max()/ cdf.max()
>>>
>>> plt.plot(cdf_normalized, color = 'b')
>>> plt.hist(img.flatten(),256,[0,256], color = 'r')
>>> plt.xlim([0,256])
>>> plt.legend(('cdf','histogram'), loc = 'upper left')
>>> plt.show()


>>> 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')


>>> img2 = cdf[img]

>>> plt.imshow(img)

<matplotlib.image.AxesImage at 0x7f0cb73a5860>


## 5.2.3. OpenCV中的直方图均衡¶

OpenCV有这样的功能， 均衡器（） . 它的输入只是灰度图像，输出是我们的直方图均衡化图像。

>>> img = cv2.imread('/cvdata/wiki.jpg',0)
>>> equ = cv2.equalizeHist(img)
>>> res = np.hstack((img,equ)) #stacking images side-by-side
>>> cv2.imwrite('res.png',res)

True


## 5.2.4. 对比度受限的自适应直方图均衡化¶

>>> import numpy as np
>>> import cv2
>>>
>>>
>>>
>>> # create a CLAHE object (Arguments are optional).
>>> clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
>>> cl1 = clahe.apply(img)
>>>
>>> cv2.imwrite('xx_clahe_2.jpg',cl1)

True