2015-04-25 47 views
2

我將圖像加載到一個numpy數組中,並且想要在直方圖中繪製其顏色值。numpy圖像中灰度值的直方圖

import numpy as np 

from skimage import io 
from skimage import color 

img = io.imread('img.jpg') 
img = color.rgb2gray(img) 

unq = np.unique(img) 
unq = np.sort(unq) 

當我們檢查的unq的價值,我們會看到類似

array([ 5.65490196e-04, 8.33333333e-04, 1.13098039e-03, ..., 
     7.07550980e-01, 7.09225490e-01, 7.10073725e-01]) 

到現在還太值matplotlib所以我的想法是遍歷unq和刪除所有這些偏差僅x值從它的前身。

dels = [] 

for i in range(1, len(unq)): 
    if abs(unq[i]-unq[i-1]) < 0.0003: 
     dels.append(i) 

unq = np.delete(unq, dels) 

雖然這種方法可行是因爲它確實非常低效不使用numpy的經過優化的實現。

是否有一個numpy功能可以爲我做這個?

只是注意到我的算法丟失了顏色出現頻率的信息。讓我試着修復這個

+2

爲什麼不使用['np.histogram(img,bins)'](http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html)(或['plt.hist (img.ravel(),bin)'](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.hist)如果你只是想繪製它)? –

+0

@ali_m是的,這會回答我的問題。 – bodokaiser

回答

5

如果你只是想計算的直方圖,可以使用np.histogram

bin_counts, bin_edges = np.histogram(img, bins, ...) 

這裏,bins既可以是窗口的數量,或指定上下倉邊緣的載體。

如果你想繪製直方圖,最簡單的方法是使用plt.hist

bin_counts, bin_edges, patches = plt.hist(img.ravel(), bins, ...) 

請注意,我用img.ravel()計算直方圖之前被拉平的圖像陣列。如果您將二維數組傳遞給plt.hist(),則它會將每行視爲一個單獨的數據系列,這不是您想要的。

+1

感謝您使用'plt.hist(img.ravel())'!「!如何從直方圖中讀取灰度值(比例尺只能從0到0.8)? – bodokaiser

+0

不確定你的意思。 x軸表示灰度值,y軸表示頻率。如果x比例從0到0.8,那麼所有灰度值都位於0和0.8之間,這與您在'unq'中顯示的值看起來一致。 –

+0

啊,這是有道理的。 – bodokaiser