2012-06-07 89 views
2

我有一個包含數據的圖像的每個像素數據立方體這個(非常像高光譜成像)。 我試圖以一種有效的方式在圖像的每個像素上劃一條線。 現在,我這樣做:優化嵌套循環操作

我的datacube是一個6X1024x1024 numpy數組,我有另一個變量包含我的數據的自變量。

map = np.zeros((1024,1024)) 
for i in np.mgrid[1:1024]: 
    for j in np.mgrid[1:1024]: 
     x = independent_variable # This is my independent variable 
     y = spec_cube[:,i,j] # The Y data to be fitted is the power at each scale, for a pixel 
     index = polyfit(x,y,1) # Outputs the slope and the offset 
     map[i,j] = index[0] # The pixel value is the index 

我知道嵌套for循環通常是最糟糕的事情,但我想不出更好的辦法。

我嘗試以下,但它給出了這樣的錯誤: 「ValueError異常:值過多解壓」

map = np.zeros((1024,1024)) 
for i,j in map: 
    x = independent_variable # This is my independent variable 
    y = spec_cube[:,i,j] # The Y data to be fitted is the power at each scale, for a pixel 
    index = polyfit(x,y,1) # Outputs the slope and the offset 
    map[i,j] = index[0] # The pixel value is the index 
+0

這與相關的問題表現出與Python/numpy的一個共同的問題,當你有沒有類似numpy的矢量操作,那麼你基本上是停留無論你怎麼努力優化緊湊的內部循環。在這些類型的情況下,應該認真考慮其他選擇,例如C-extensions或更好的Cython。 –

回答

3

由於循環內的操作是找到斜率的一條線,我去了一個不太精確的方法,但使用數組操作。基本上,要找到我所做的斜率:每個相鄰點的三角洲Y /三角洲X,然後平均所有的斜坡。

原來它需要幾分之一秒。

這裏的新代碼:

map = np.zeros((spec_cube.shape[1],spec_cube.shape[2])) # This will be the power index map 
x = scale_array 
for i in np.mgrid[1:spec_cupe.shape[0]]: 
    spec_cube[i-1] = (spec_cube[i]-spec_cube[i-1])/(scale_array[i]-scale_array[i-1]) 
    map += spec_cube[i-1] 
map /= (spec_cube.shape[0]-1) 

我的腳本420S去9.66s!

+0

祝賀修復!如果可以,請確保將您的答案標記爲「已接受」,以便其他人能夠從您的成功中學習。乾杯〜 –

4

一種方法加快速度:使用itertools.product

for (i, j) in itertools.product(np.mgrid[1:1024], np.mgrid[1:1024]): 
    ... stuff ... 

的改善( Python 2.7.1):

 
In [2]: def multiline(): 
    ...:  for i in np.mgrid[1:1024]: 
    ...:   for j in np.mgrid[1:1024]: 
    ...:    pass 
    ...:   

In [3]: def single_line(): 
    ...:  for i, j in product(np.mgrid[1:1024], np.mgrid[1:1024]): 
    ...:   pass 
    ...:  

In [4]: from itertools import product 

In [5]: %timeit multiline() 
10 loops, best of 3: 138 ms per loop 

In [6]: %timeit single_line() 
10 loops, best of 3: 75.6 ms per loop 
+0

謝謝,它確實簡化了代碼並給出了一些速度。 這對我的目的來說不夠重要,我想每3秒執行一次我需要412秒... 我將不得不找到一種方法來避免這種計算。 – PhilMacKay