Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast indexing with Numpy

I have an array containing some pixel indices, and a binary image. I would like to filter the first array based on the value of the image at the corresponding image point. Currently I am doing following:

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

Definitely not the best way to do it. Is there a faster way?

like image 962
oezguensi Avatar asked Mar 08 '26 03:03

oezguensi


1 Answers

With both of them as arrays, simply index into mask with those img_pts -

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

Alternatively -

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

To get the final output as int, append with .view('i1'). Or for float, convert to float with .astype(float).

like image 136
Divakar Avatar answered Mar 09 '26 16:03

Divakar