【问题标题】:Fast indexing with Numpy使用 Numpy 快速索引
【发布时间】:2020-10-19 10:51:33
【问题描述】:

我有一个包含一些像素索引的数组和一个二进制图像。我想根据相应图像点的图像值过滤第一个数组。 目前我正在做以下事情:

mask = np.random.rand(512, 512)
mask[mask < 0.5] = 0
mask[mask >= 0.5] = 1

x = np.random.randint(0, mask.shape[0], 10)
y = np.random.randint(0, mask.shape[1], 10)
img_pts = np.vstack([x, y]).T

occ = np.zeros(len(img_pts))
for i, img_pt in enumerate(img_pts):
    if mask[img_pt[1], img_pt[0]]:
        occ[i] = 1

绝对不是最好的方法。有更快的方法吗?

【问题讨论】:

    标签: python performance numpy indexing


    【解决方案1】:

    将它们都作为数组,只需使用 img_pts 索引到 mask -

    occ = mask[tuple(img_pts.T[::-1])]
    

    或者-

    occ = mask[img_pts[:,1],img_pts[:,0]]
    

    要获得int 的最终输出,请附加.view('i1')。或者对于float,使用.astype(float) 转换为浮点数。

    【讨论】:

      猜你喜欢
      • 2013-01-01
      • 2015-03-21
      • 2016-12-21
      • 1970-01-01
      • 2021-03-01
      • 2020-05-16
      • 2012-08-01
      • 1970-01-01
      • 2011-11-29
      相关资源
      最近更新 更多