How to find top_left, top_right, bottom_left, right coordinates in 2d mask where cell has specified value?

后端 未结 3 786
走了就别回头了
走了就别回头了 2021-01-21 07:47

I have 2D numpy array which is a mask from an image. Each cell has 0 or 1 value. So I would like to find top:left,right, bottom:left,right in an array

3条回答
  •  情话喂你
    2021-01-21 08:25

    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.

提交回复
热议问题