灰度圖的直方圖均衡化(Histogram Equalization)原理與 Python 實現
阿新 • • 發佈:2018-10-31
原理
直方圖均衡化是一種通過使用影象直方圖,調整對比度的影象處理方法;通過對影象的強度(intensity)進行某種非線性變換,使得變換後的影象直方圖為近似均勻分佈,從而,達到提高影象對比度和增強圖片的目的。普通的直方圖均衡化採用如下形式的非線性變換:
設 f 為原始灰度影象,g 為直方圖均衡化的灰度影象,則 g 和 f 的每個畫素的對映關係如下:
其中,L 為灰度級,通常為 256,表明了影象畫素的強度的範圍為 0 ~ L-1;
pn 等於影象 f 中強度為 n 的畫素數佔總畫素數的比例,即原始灰度圖直方圖的概率密度函式;
fi,j 表示在影象 f 中,第 i 行,第 j 列的畫素強度;gi,j 表示在影象 g 中,第 i 行,第 j 列的畫素強度.
Python 實現
#!/usr/bin/env python
# -*- coding: utf8 -*-
"""
# Author: klchang
# Date: 2018.10
# Description:
histogram equalization of a gray image.
"""
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
def histequ(gray, nlevels=256):
# Compute histogram
histogram = np.bincount(gray.flatten(), minlength=nlevels)
print ("histogram: ", histogram)
# Mapping function
uniform_hist = (nlevels - 1) * (np.cumsum(histogram)/(gray.size * 1.0))
uniform_hist = uniform_hist.astype('uint8')
print ("uniform hist: ", uniform_hist)
# Set the intensity of the pixel in the raw gray to its corresponding new intensity
height, width = gray.shape
uniform_gray = np.zeros(gray.shape, dtype='uint8') # Note the type of elements
for i in range(height):
for j in range(width):
uniform_gray[i,j] = uniform_hist[gray[i,j]]
return uniform_gray
if __name__ == '__main__':
fname = "320px-Unequalized_Hawkes_Bay_NZ.png" # Gray image
# Note, matplotlib natively only read png images.
gray = plt.imread(fname, format=np.uint8)
if gray is None:
print ("Image {} does not exist!".format(fname))
exit(-1)
# Histogram equalization
uniform_gray = histequ(gray)
# Display the result
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.set_title("Raw Image")
ax1.imshow(gray, 'gray')
ax1.set_xticks([]), ax1.set_yticks([])
ax2.set_title("Histogram Equalized Image")
ax2.imshow(uniform_gray, 'gray')
ax2.set_xticks([]), ax2.set_yticks([])
fig.tight_layout()
plt.show()
原始圖片 320px-Unequalized_Hawkes_Bay_NZ.png
結果顯示
參考資料
[1]. Histogram_equalization - Wikipedia. https://en.wikipedia.org/wiki/Histogram_equalization
[2]. Histogram Equalization. https://www.math.uci.edu/icamp/courses/math77c/demos/hist_eq.pdf