获取所有轮廓的外接矩形

获取所有轮廓的外接矩形

示例代码

import cv2
def get_contours_rectangle(mask):
    h, w = mask.shape

    contours, _ = cv2.findContours(
        mask, 
        cv2.RETR_EXTERNAL, 
        cv2.CHAIN_APPROX_SIMPLE
    )
    # 获取所有轮廓的外接矩形
    min_y, max_y = h, 0
    min_x, max_x = w, 0

    for contour in contours:
        x, y, w, h = cv2.boundingRect(contour)
        min_y = min(min_y, y)
        min_x = min(min_x, x)
        max_y = max(max_y, y + h)
        max_x = max(max_x, x + w)
    w = max_x - min_x
    h = max_y - min_y

    mask_contour_rectangle = mask[min_y:max_y, min_x:max_x]
    return mask_contour_rectangle
if __name__ == '__main__':
	mask_path = "./test.png"
    mask = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE)
    mask_1 = get_contours_rectangle(mask)
    cv2.imwrite("mask_contour.png", mask_1)
获取轮廓的最小外接矩形,可以使用OpenCV库中的`cv2.minAreaRect()`函数。该函数将给定的轮廓作为参数,并返回一个包围该轮廓的最小外接矩形。 下面是一个示例代码,展示了如何获取轮廓的最小外接矩形: ```python import cv2 # 假设你已经得到了轮廓 contours # 创建一个空白图像作为背景 img = np.zeros((500, 500, 3), dtype=np.uint8) # 绘制轮廓 cv2.drawContours(img, contours, -1, (0, 255, 0), 2) # 获取所有轮廓的最小外接矩形 rectangles = [] for contour in contours: # 获取最小外接矩形 rect = cv2.minAreaRect(contour) rectangles.append(rect) # 在图像上绘制最小外接矩形 for rect in rectangles: # 将浮点坐标转换为整数坐标 box = cv2.boxPoints(rect) box = np.int0(box) # 绘制矩形 cv2.drawContours(img, [box], 0, (0, 0, 255), 2) # 显示图像 cv2.imshow("Contours and Minimum Bounding Rectangles", img) cv2.waitKey(0) cv2.destroyAllWindows() ``` 这段代码首先绘制了所有的轮廓,然后使用`cv2.minAreaRect()`函数获取每个轮廓的最小外接矩形,并将结果存储在`rectangles`列表中。最后,使用`cv2.drawContours()`函数将最小外接矩形绘制在图像上。 请注意,`cv2.minAreaRect()`函数返回的是一个包含矩形中心坐标、尺寸和旋转角度的元组。如果需要绘制矩形,使用`cv2.boxPoints()`函数将矩形转换为四个角点的坐标,然后使用`cv2.drawContours()`函数绘制矩形。 希望这可以帮助到你!如有更多问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值