2013-06-21 28 views
2

我使用蟒,與SciPy的,numpy的1D直方圖等numpy的:基於二維像素歐幾里得距離從中心

我想計算灰度圖像的強度值的直方圖,基於距離的像素到圖像的質量中心。以下解決方案的工作,但速度很慢:

import matplotlib.pyplot as plt 
from scipy import ndimage 
import numpy as np 
import math 

# img is a 2-dimensionsl numpy array 
img = np.random.rand(300, 300) 
# center of mass of the pixels is easy to get 
centerOfMass = np.array(list(ndimage.measurements.center_of_mass(img))) 

# declare histogram buckets 
histogram = np.zeros(100) 

# declare histogram range, which is half the diagonal length of the image, enough in this case. 
maxDist = len(img)/math.sqrt(2.0) 

# size of the bucket might be less than the width of a pixel, which is fine. 
bucketSize = maxDist/len(histogram) 

# fill the histogram buckets 
for i in range(len(img)): 
    for j in range(len(img[i])): 
     dist = np.linalg.norm(centerOfMass - np.array([i,j])) 
     if(dist/bucketSize < len(histogram)): 
      histogram[int(dist/bucketSize)] += img[i, j] 

# plot the img array 
plt.subplot(121) 
imgplot = plt.imshow(img) 
imgplot.set_cmap('hot') 
plt.colorbar() 
plt.draw() 

# plot the histogram 
plt.subplot(122) 
plt.plot(histogram) 
plt.draw() 

plt.show() 

正如我之前所說,這個工作,但速度很慢,因爲你沒有以這種方式在numpy的應該是雙迴路陣列。有沒有更有效的方法來做同樣的事情?我假設我需要在所有數組元素上應用一些函數,但我也需要索引座標。我怎樣才能做到這一點?目前,1kx1k圖像需要幾秒鐘的時間,速度很慢。 。

回答

2

所有numpy的分級功能(bincounthistogramhistogram2d ...有你可以用來做很奇怪的事情,比如你的一個weights關鍵字參數這是我會怎麼做:

rows, cols = 300, 300 
img = np.random.rand(rows, cols) 

# calculate center of mass position 
row_com = np.sum(np.arange(rows)[:, None] * img)/np.sum(img) 
col_com = np.sum(np.arange(cols) * img)/np.sum(img) 

# create array of distances to center of mass 
dist = np.sqrt(((np.arange(rows) - row_com)**2)[:, None] + 
       (np.arange(cols) - col_com)**2) 

# build histogram, with intensities as weights 
bins = 100 
hist, edges = np.histogram(dist, bins=bins, weights=img) 

# to reproduce your exact results, you must specify the bin edges 
bins = np.linspace(0, len(img)/math.sqrt(2.0), 101) 
hist2, edges2 = np.histogram(dist, bins=bins, weights=img) 

沒有計時兩種方法,但從終端運行時延遲來看,這顯然更快。

+0

更好的答案,然後我的。有趣的,但並不意外的回顧,np.histogram可以採取多維陣列。 – Daniel

+0

@Ophion它需要你的一切行,但在處理之前它總是變平。 – Jaime

+0

非常感謝你,我正在玩一系列的距離,因爲它似乎是要走的路,但我無法讓它工作。 –

相關問題