Get The Coordinates Of Non-zero Binary Mask In Certain Range

- 1 answer

I'm trying to get the non-zero values of a binary mask(that has been indexed by a certain range, the range here defined by the lower and upper x,y values)

At first, I did this

region = np.transpose(np.nonzero(mask_belt[lower_Y[i]:upper_Y[i],lower_X[i]:upper_X[i]]))

but then I realized that the region coordinate was giving me the coordinate of the mask that been cropped by the range, so I had to do this after.

region[:,1] = region[:,1]+lower_X[i]
region[:,0] = region[:,0] + lower_Y[i]

But I feel like this is error-prone. Is there a cleaner way to get the non-zero values of a binary mask(not on the entire mask but in a certain range of X and Y values)



We can do those summations in one step and also bring in np.argwhere to get those indices at the first step. Hence, one way would be -

region = np.argwhere(mask_belt[lower_Y[i]:upper_Y[i],lower_X[i]:upper_X[i]]) 
region += [lower_Y[i],lower_X[i]]