从二值 Mask 获取外接矩形坐标
从二值 Mask 获取外接矩形坐标
语雀:https://www.yuque.com/lart/blog/lxnpun
Numpy-Based
np.where(condition)
/ np.nonzero(condition)
- https://numpy.org/doc/stable/reference/generated/numpy.where.html
- https://numpy.org/doc/stable/reference/generated/numpy.nonzero.html#numpy.nonzero
该方法只适用于获得标准的,即非倾斜的外接矩形。
这里的 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)
- https://docs.opencv.org/4.5.5/d3/dc0/group__imgproc__shape.html#ga3d476a3417130ae5154aea421ca7ead9
这可以获得最小的外接矩形,其会得到一个尽可能保卫对应轮廓的矩形,甚至是倾斜的。
核心代码为:
"""
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)