灰度圖的直方圖均衡化(Histogram Equalization)原理與 Python 實現


原理

  直方圖均衡化是一種通過使用圖像直方圖,調整對比度的圖像處理方法;通過對圖像的強度(intensity)進行某種非線性變換,使得變換后的圖像直方圖為近似均勻分布,從而,達到提高圖像對比度和增強圖片的目的。普通的直方圖均衡化采用如下形式的非線性變換:

  設 為原始灰度圖像,為直方圖均衡化的灰度圖像,則 和 的每個像素的映射關系如下:

 

  

  其中,為灰度級,通常為 256,表明了圖像像素的強度的范圍為 0 ~ L-1;

  p等於圖像 中強度為 的像素數占總像素數的比例,即原始灰度圖直方圖的概率密度函數;

  fi,j 表示在圖像 中,第 行,第 列的像素強度;gi,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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM