python數字圖像處理實現直方圖與均衡化
在圖像處理中,直方圖是非常重要,也是非常有用的一個處理要素。
在skimage庫中對直方圖的處理,是放在exposure這個模塊中。
1、計算直方圖
函數:skimage.exposure.histogram(image,nbins=256)
在numpy包中,也提供了一個計算直方圖的函數histogram(),兩者大同小義。
返回一個tuple(hist, bins_center), 前一個數組是直方圖的統(tǒng)計量,后一個數組是每個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的統(tǒng)計量是一樣的,但numpy返回的是每個bin的兩端的范圍值,而skimage返回的是每個bin的中間值
2、繪制直方圖
繪圖都可以調用matplotlib.pyplot庫來進行,其中的hist函數可以直接繪制直方圖。
調用方式:
hist的參數非常多,但常用的就這六個,只有第一個是必須的,后面四個可選
arr: 需要計算直方圖的一維數組
bins: 直方圖的柱數,可選項,默認為10
normed: 是否將得到的直方圖向量歸一化。默認為0
facecolor: 直方圖顏色
edgecolor: 直方圖邊框顏色
alpha: 透明度
histtype: 直方圖類型,‘bar', ‘barstacked', ‘step', ‘stepfilled'
返回值 :
n: 直方圖向量,是否歸一化由參數normed設定
bins: 返回各個bin的區(qū)間范圍
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、直方圖均衡化
如果一副圖像的像素占有很多的灰度級而且分布均勻,那么這樣的圖像往往有高對比度和多變的灰度色調。直方圖均衡化就是一種能僅靠輸入圖像直方圖信息自動達到這種效果的變換函數。它的基本思想是對圖像中像素個數多的灰度級進行展寬,而對圖像中像素個數少的灰度進行壓縮,從而擴展取值的動態(tài)范圍,提高了對比度和灰度色調的變化,使圖像更加清晰。
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()
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Python調用win10toast框架實現定時調起系統(tǒng)通知
win10toast是一個windows通知的出發(fā)框架,使用它可以輕松的調起系統(tǒng)通知。通過它可以很方便的做一個定時通知的功能應用。本文將調用win10toast實現定時調起系統(tǒng)通知功能,需要的可以參考一下2022-01-01Django中使用 Closure Table 儲存無限分級數據
對于數據量大的情況(比如用戶之間有邀請鏈,有點三級分銷的意思),就要用到 closure table 的結構來進行存儲。這篇文章主要介紹了Django中使用 Closure Table 儲存無限分級數據,需要的朋友可以參考下2019-06-06