opencv外接矩形cv2.boundingRect和cv2.minAreaRect区别

时间:2024-10-13 12:46:08

在OpenCV中,cv2.boundingRectcv2.minAreaRect是两个用于获取图像中形状边界的函数,但它们在功能和返回结果上有所不同。以下是两者的详细区别:

1. cv2.boundingRect 和 cv2.minAreaRect 功能描述

cv2.boundingRect 主要是用来计算图像轮廓的最小正矩形(即矩形的边界与图像边界平行),而cv2.minAreaRect 用来计算最小旋转矩形(斜矩形)

2. 示例代码

下面是一段直观显示这两个方法的例子: 

import cv2
import numpy as np

def main():
    image_path = 'test.png'
    img = cv2.imread(image_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    _, binary = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY)

    outs = cv2.findContours(binary.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    if len(outs) == 3:
        cnts = outs[1]
    elif len(outs) == 2:
        cnts = outs[0]
    c = sorted(cnts, key=cv2.contourArea, reverse=True)[0]

    # 最小旋转矩形
    rect = cv2.minAreaRect(c)
    box = np.int64(cv2.boxPoints(rect))
    draw_img = cv2.drawContours(img.copy(), [box], -1, (0, 0, 255), thickness=2)
    
    # 最小正矩形
    x0, y0, w, h = cv2.boundingRect(c)
    cv2.rectangle(draw_img, (x0, y0), (x0+w, y0+h), (0, 255, 0), thickness=2)

    cv2.imshow("draw_img", draw_img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

if __name__ == '__main__':
    main()

绿色矩形框是cv2.boundingRect效果,是一个最小正矩形。红色矩形框是cv2.minAreaRect 的效果,是一个最小斜矩形。

3. 扩展

如果我们要计算轮廓的最小闭合圆,可以使用 cv2.minEnclosingCircle 来计算,代码和效果如下:

    outs = cv2.findContours(binary.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    c = sorted(cnts, key=cv2.contourArea, reverse=True)[0]

    # 最小闭合圆
    (x, y), radius = cv2.minEnclosingCircle(c)
    center = (int(x), int(y))
    radius = int(radius)
    cv2.circle(draw_img, center, radius, (0, 255, 0), thickness=2)