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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With