2013-07-03 109 views
3

我有一个非常困难的时间向量,我似乎无法考虑数学那种方式呢。我现在有这个权利:迭代numpy数组

#!/usr/bin/env python 

import numpy as np 
import math 

grid = np.zeros((2,2)) 
aList = np.arange(1,5).reshape(2,2) 

i,j = np.indices((2,2)) 

iArray = (i - aList[:,0:1]) 
jArray = (j - aList[:,1:2]) 

print np.power(np.power(iArray, 2) + np.power(jArray, 2), .5) 

我打印出来是这样的:

[[ 2.23606798 1.41421356] 
[ 4.47213595 3.60555128]] 

我所要做的就是把像素值,网格的二维数组,并说多远每个像素来自重要像素列表aList。

# # @ 
# # # 
* # * 

一个例子是,如果* S(0,2)和(2,2)是重要的像素和我目前在@(2,0)像素,我对@像素值会:

[(0-2)^2 + (2-0)^2]^.5 + [(2-2)^2 + (0-2)^2]^.5 

所有网格的作用是保持的像素值,所以我需要得到每个像素值的指数距离相关联。然而,我的Alist数组拥有[x,y]坐标,所以这很容易。我想我现在我有两个问题:1。 我没有得到正确的indeces 2. 我不是循环遍历ALIST正确

+1

请注意:如果您的示例使用数组索引,则* s的坐标为(2,0),(2,2),而@为((0,2))。 – wflynny

+0

您可以尝试为每个“重要点”创建一个距离阵列。 (index_array [0] -i)** 2 +(index_array [1] -j)** 2',其中index_array = np.indices((N,N))''dist2 = lambda index_array,i,j: 。这产生了一个网格,其中每个点是距重要点'(i,j)'的距离^ 2。为每个重要点创建一个,然后'np.sqrt(sum(dist_arrays))'从所有重要点获得组合距离。 – wflynny

回答

1

我的做法坐标:

import numpy as np 

n = 3 

aList = np.zeros([n,n]) 
distance = np.zeros([n,n]) 

I,J = np.indices([n,n]) 

aList[2,2] = 1; aList[0,2] = 1 #Importan pixels 
important = np.where(aList == 1) #Where the important pixels are 

for i,j in zip(I[important],J[important]): #This part could be improved... 
    distance += np.sqrt((i-I)**2+(j-J)**2) 

print distance 

最后“为”有待改进,但如果你只有几个重要的像素,性能会好......


与检查:

import matplotlib.pyplot as plt 

n = 500 

... 

aList[249+100,349] = 1; aList[249-100,349] = 1 ;aList[249,50] = 1 

... 

plt.plot(I[important],J[important],'rx',markersize=20) 
plt.imshow(distance.T,origin='lower', 
      cmap=plt.cm.gray) 
plt.show() 

结果是很舒服:

enter image description here

3

与广播一点点帮助,我得到这个,有数据根据您的最后一个例子:

import numpy as np 

grid = np.zeros((3, 3)) 
aList = np.array([[2, 0], [2, 2]]) 

important_rows, important_cols = aList.T 
rows, cols = np.indices(grid.shape) 

dist = np.sqrt((important_rows - rows.ravel()[:, None])**2 + 
       (important_cols - cols.ravel()[:, None])**2).sum(axis=-1) 
dist = dist.reshape(grid.shape) 

>>> dist 
array([[ 4.82842712, 4.47213595, 4.82842712], 
     [ 3.23606798, 2.82842712, 3.23606798], 
     [ 2.  , 2.  , 2.  ]]) 

你可以通过这样做获得更高的内存效率:

important_rows, important_cols = aList.T 
rows, cols = np.meshgrid(np.arange(grid.shape[0]), 
         np.arange(grid.shape[1]), 
         sparse=True, indexing='ij') 
dist2 = np.sqrt((rows[..., None] - important_rows)**2 + 
       (cols[..., None] - important_cols)**2).sum(axis=-1) 
+0

非常好的答案!对于3000x3000的数组,至少比我的解决方案快1.73倍... – Pablo