Use transpose
and nonzero
from numpy
, like:
im=np.array([[0,0,0,0,0],
[0,1,1,1,0],
[0,1,1,0,0],
[0,0,0,0,0]])
print(np.transpose(np.nonzero(im)))
yields:
array([[1, 1],
[1, 2],
[1, 3],
[2, 1],
[2, 2]])
Update:
Still not perfect, but as long as the mask is continuous within its rows, you could evaluate np.diff()
to get an idea where the 0->1
and 1->0
transitions are:
leftedge=np.transpose(np.nonzero(np.diff(im,prepend=0)==1))
rightedge=np.transpose(np.nonzero(np.diff(im,append=0)==-1))
top_left = leftedge[0]
bottom_left = leftedge[-1]
bottom_right = rightedge[-1]
top_right = rightedge[0]
pts=[list(x) for x in [top_left,top_right,bottom_left,bottom_right]]
yields: [[1, 1], [1, 3], [2, 1], [2, 2]]
I'd suggest to use Chris' answer instead.