从二值 Mask 获取外接矩形坐标

从二值 Mask 获取外接矩形坐标

语雀:https://www.yuque.com/lart/blog/lxnpun

Numpy-Based

np.where(condition) / np.nonzero(condition)

该方法只适用于获得标准的,即非倾斜的外接矩形。

这里的 condition 可以使自定义的等式,或者直接是一个确定的数组。使用后者时返回每个不等于 0 的位置的坐标。该坐标结果包含两个数组,为了便于理解这两个数组的含义,可以参考官方提供的例子:

>>> x = np.array([[3, 0, 0], [0, 4, 0], [5, 6, 0]])
>>> x
array([[3, 0, 0],
       [0, 4, 0],
       [5, 6, 0]])
>>> np.nonzero(x)
(array([0, 1, 2, 2]), array([0, 1, 0, 1]))

可以看到,返回的两个数组,第一个是第 0 维度的坐标,第二个是第 1 维度的坐标。也就是 按照索引维度由前向后依此对应

y_coords, x_coords = np.nonzero(ori_mask)  
x_min = x_coords.min()  
x_max = x_coords.max()  
y_min = y_coords.min()  
y_max = y_coords.max()

由于会返回非零区域内像素坐标,所以同时这两个函数可以被用来计算质心坐标,可见我的另一篇文档:https://www.yuque.com/lart/blog/gpbigm

OpenCV-Based

cv2.minAreaRect(contour)

这可以获得最小的外接矩形,其会得到一个尽可能保卫对应轮廓的矩形,甚至是倾斜的。

核心代码为:

"""
rect[0]返回矩形的中心点,(x,y),实际上为y行x列的像素点
rect[1]返回矩形的长和宽,顺序一定不要弄错了,在旋转角度上有很重要的作用
rect[2]返回矩形的旋转角度,角度范围是[-90,0)
"""
rect = cv2.minAreaRect(contour)
box = cv2.boxPoints(rect) # 将边界框表示转化为四点坐标形式

一个典型的例子如下,要注意这里 cv2.minAreaRect 在返回点的时候的顺序有些特别。一般情况下最好不要对点的顺序有特别的要求。

def detect_rect(contours):
    squares = []
    for c in contours:
        rect = cv2.minAreaRect(c)
        """
        The lowest point of the rectangle(does not matter left or right) 
        will always be the first sub-list of the "box" ndarray. 
        Now this point will be the reference point to decide 
        what the next sub-list represents. 
        Meaning, the next sub-list will always represent the point 
        that you first get when you move in the clockwise direction.
        """
        box = cv2.boxPoints(rect)  
        squares.append(clockwise_box)
    return np.asarray(squares, dtype=np.int32)

contours, hierarchy = cv2.findContours(image, mode=cv2.RETR_LIST, method=cv2.CHAIN_APPROX_SIMPLE)
squares = detect_rect(contours=contours)
  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值