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

后端 未结 3 767
走了就别回头了
走了就别回头了 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:41

    Using np.argwhere and itertools.product:

    import numpy as np
    from itertools import product
    
    def corners(np_array):
        ind = np.argwhere(np_array)
        res = []
        for f1, f2 in product([min,max], repeat=2):
            res.append(f1(ind[ind[:, 0] == f2(ind[:, 0])], key=lambda x:x[1]))
        return res
    corners(arr)
    

    Output:

    [array([1, 1], dtype=int64),
     array([2, 1], dtype=int64),
     array([1, 3], dtype=int64),
     array([2, 2], dtype=int64)]
    

提交回复
热议问题