python數字圖像處理(9):直方圖與均衡化


在圖像處理中,直方圖是非常重要,也是非常有用的一個處理要素。

在skimage庫中對直方圖的處理,是放在exposure這個模塊中。

1、計算直方圖

函數:skimage.exposure.histogram(imagenbins=256)

在numpy包中,也提供了一個計算直方圖的函數histogram(),兩者大同小義。

返回一個tuple(hist, bins_center), 前一個數組是直方圖的統計量,后一個數組是每個bin的中間值

import numpy as np
from skimage import exposure,data
image =data.camera()*1.0
hist1=np.histogram(image, bins=2)   #用numpy包計算直方圖
hist2=exposure.histogram(image, nbins=2)  #用skimage計算直方圖
print(hist1)
print(hist2)

輸出:

(array([107432, 154712], dtype=int64), array([ 0. , 127.5, 255. ]))
(array([107432, 154712], dtype=int64), array([ 63.75, 191.25]))

分成兩個bin,每個bin的統計量是一樣的,但numpy返回的是每個bin的兩端的范圍值,而skimage返回的是每個bin的中間值

2、繪制直方圖

繪圖都可以調用matplotlib.pyplot庫來進行,其中的hist函數可以直接繪制直方圖。

調用方式:

n, bins, patches = plt.hist(arr, bins=10, normed=0, facecolor='black', edgecolor='black',alpha=1,histtype='bar')

hist的參數非常多,但常用的就這六個,只有第一個是必須的,后面四個可選

arr: 需要計算直方圖的一維數組

bins: 直方圖的柱數,可選項,默認為10

normed: 是否將得到的直方圖向量歸一化。默認為0

facecolor: 直方圖顏色

edgecolor: 直方圖邊框顏色

alpha: 透明度

histtype: 直方圖類型,‘bar’, ‘barstacked’, ‘step’, ‘stepfilled’

返回值 :

n: 直方圖向量,是否歸一化由參數normed設定

bins: 返回各個bin的區間范圍

patches: 返回每個bin里面包含的數據,是一個list

from skimage import data
import matplotlib.pyplot as plt
img=data.camera()
plt.figure("hist")
arr=img.flatten()
n, bins, patches = plt.hist(arr, bins=256, normed=1,edgecolor='None',facecolor='red')  
plt.show()

其中的flatten()函數是numpy包里面的,用於將二維數組序列化成一維數組。

是按行序列,如

mat=[[1 2 3

     4 5 6]]

經過 mat.flatten()后,就變成了

mat=[1 2 3 4 5 6]

3、彩色圖片三通道直方圖

一般來說直方圖都是征對灰度圖的,如果要畫rgb圖像的三通道直方圖,實際上就是三個直方圖的疊加。

from skimage import data
import matplotlib.pyplot as plt
img=data.lena()
ar=img[:,:,0].flatten()
plt.hist(ar, bins=256, normed=1,facecolor='r',edgecolor='r',hold=1)
ag=img[:,:,1].flatten()
plt.hist(ag, bins=256, normed=1, facecolor='g',edgecolor='g',hold=1)
ab=img[:,:,2].flatten()
plt.hist(ab, bins=256, normed=1, facecolor='b',edgecolor='b')
plt.show()

其中,加一個參數hold=1,表示可以疊加

4、直方圖均衡化

如果一副圖像的像素占有很多的灰度級而且分布均勻,那么這樣的圖像往往有高對比度和多變的灰度色調。直方圖均衡化就是一種能僅靠輸入圖像直方圖信息自動達到這種效果的變換函數。它的基本思想是對圖像中像素個數多的灰度級進行展寬,而對圖像中像素個數少的灰度進行壓縮,從而擴展取值的動態范圍,提高了對比度和灰度色調的變化,使圖像更加清晰。

from skimage import data,exposure
import matplotlib.pyplot as plt
img=data.moon()
plt.figure("hist",figsize=(8,8))

arr=img.flatten()
plt.subplot(221)
plt.imshow(img,plt.cm.gray)  #原始圖像
plt.subplot(222)
plt.hist(arr, bins=256, normed=1,edgecolor='None',facecolor='red') #原始圖像直方圖

img1=exposure.equalize_hist(img)
arr1=img1.flatten()
plt.subplot(223)
plt.imshow(img1,plt.cm.gray)  #均衡化圖像
plt.subplot(224)
plt.hist(arr1, bins=256, normed=1,edgecolor='None',facecolor='red') #均衡化直方圖

plt.show()


免責聲明!

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



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