2012-06-07 90 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