Filter 2d coordinate numpy array by mask

Question:

As shown below, I would like to quickly extract only the part where the value of the mask is zero through NumPy.

Is there a quick way to handle it with 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]]
Asked By: KimBomm

||

Answers:

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).

Then for each of your points, it checks if the value for the mask at that point is equal to 0.

Finally, it takes the subset of points where the mask equals 0.

Answered By: Adam Oppenheimer

Numpy indexing is the best way to do so :

# 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]]
Answered By: Ali_Sh

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:

array([[1, 1],
       [2, 2],
       [3, 3]])
Answered By: Jeril
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.