简体   繁体   English

通过掩码过滤二维坐标 numpy 数组

[英]Filter 2d coordinate numpy array by mask

As shown below, I would like to quickly extract only the part where the value of the mask is zero through NumPy.如下图,我想通过NumPy快速只提取mask值为零的部分。

Is there a quick way to handle it with NumPy?有没有用 NumPy 快速处理它的方法?

import numpy as np

mask = np.array([[0, 0, 0, 255, 255],
                 [0, 0, 0, 0, 255],
                 [0, 0, 0, 0, 0],
                 [0, 0, 0, 0, 0],
                 [255, 255, 0, 0, 0]])

pts0 = np.array([[1, 1], [1, 4], [0, 4], [2, 2], [3, 3]])


def cond_func(pt):
    return mask[pt[1]][pt[0]] == 0


bloom = np.array(list(map(cond_func, pts0)))

pts0 = pts0[bloom]

print(pts0)  # [[1,1], [2,2], [3,3]]

Numpy indexing is the best way to do so: Numpy 索引是最好的方法:

# zeros = mask[pts0[:, 0], pts0[:, 1]]
zeros = mask[tuple(pts0.T)]
# [  0 255 255   0   0]

pts0 = pts0[zeros == 0]
# [[1 1]
#  [2 2]
#  [3 3]]

Try this:尝试这个:

valid_indices = (np.take(mask, pts0[:, 0] + len(pts0) * pts0[:, 1])) == 0

pts0 = pts0[valid_indices, :]

What this does is convert the indices from pts0 into entries in the flattened matrix ( pts0[:, 0] + len(pts0) * pts0[:, 1] takes on values from 0 to 24 in this example).这样做是将 pts0 中的索引转换为扁平矩阵中的条目( pts0[:, 0] + len(pts0) * pts0[:, 1]在本例中取值从 0 到 24)。

Then for each of your points, it checks if the value for the mask at that point is equal to 0.然后对于您的每个点,它会检查该点的掩码值是否等于 0。

Finally, it takes the subset of points where the mask equals 0.最后,它采用掩码等于 0 的点的子集。

Can you try the following:您可以尝试以下方法:

import numpy as np

mask = np.array([[0, 0, 0, 255, 255],
                 [0, 0, 0, 0, 255],
                 [0, 0, 0, 0, 0],
                 [0, 0, 0, 0, 0],
                 [255, 255, 0, 0, 0]])
pts0 = np.array([[1, 1], [1, 4], [0, 4], [2, 2], [3, 3]])

# get indexes of 0
ind_zeros = np.asarray(np.where(mask == 0)).T

# get similiar index from pts0
results = ind_zeros[(ind_zeros[:, None] == pts0).all(-1).any(1)]
print(results)

Output: Output:

array([[1, 1],
       [2, 2],
       [3, 3]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM