Python如何以C速度在numpy中循环数组并存储一些位置

2024-05-14 16:16:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我不熟悉python、numpy和opencv。我在玩来自here的哈里斯角探测器的第一个例子。我的目标是得到所有角落的有序清单。通过这个简单的代码,我可以得到角点的X和Y坐标及其值:

height, width, depth = img.shape
print height, width
for i in range(0, height): #looping at python speed
  for j in range(0, (width)): 
    if dst[i,j] > 0.9*dst.max():
      print i, j, dst[i,j]

然而,这是非常缓慢的。我不知道这是如何调用的,但很显然,使用numpy,可以以C速度循环数组,甚至可以赋值,例如:

^{pr2}$

我可以循环一个数组并在另一个变量中指定感兴趣的值的位置吗?一、 我可以在我的代码中使用这个来加快速度吗?在


Tags: 代码innumpy目标forhererange数组
2条回答

您可以获得传递IF条件语句的元素掩码。接下来,如果需要通过条件的索引,请在掩码上使用^{}^{}。对于有效的dst元素,使用相同的掩码索引dst,因此使用^{}。实现应该是这样的-

mask = dst > 0.9*dst.max()
out = np.column_stack((np.argwhere(mask),dst[mask]))

如果您想分别获得这三个打印输出,您可以-

^{pr2}$

最后,如果您想编辑基于2Dmask的3D数组img,那么可以-

img[mask] = 0

这样,您就可以一次性更改img中所有通道中的相应元素。在

首先,如果您使用的是python2.X,那么应该使用xrange而不是{},这样可以加快速度。^python3.X中的{}与python2.X中的xrange具有相同的实现

如果你想迭代numpy数组,为什么不使用numpy枚举器进行迭代呢?在

# creating a sample img array with size 2x2 and RGB values
# so the shape is (2, 2, 3)
> img = np.random.randint(0, 255, (2,2,3))

> img
> array([[[228,  61, 154],
          [108,  25,  52]],

          [[237, 207, 127],
           [246, 223, 101]]])

# iterate over the values, getting key and value at the same time
# additionally, no nasty nested for loops
> for key, val in np.ndenumerate(img):
>     print key, val

# this prints the following
> (0, 0, 0) 228
> (0, 0, 1) 61
> (0, 0, 2) 154
> (0, 1, 0) 108
> (0, 1, 1) 25
> (0, 1, 2) 52
> (1, 0, 0) 237
> (1, 0, 1) 207
> (1, 0, 2) 127
> (1, 1, 0) 246
> (1, 1, 1) 223
> (1, 1, 2) 101

相关问题 更多 >

    热门问题