OpenCV求最小外接圆、最小外接矩形、椭圆拟合、直线拟合

import cv2
import numpy as np

if __name__ == "__main__":
    orig = cv2.imread('mask.jpg', flags=cv2.IMREAD_COLOR)
    mask = cv2.cvtColor(orig, cv2.COLOR_BGR2GRAY)
    _, mask = cv2.threshold(mask, 200, 255, 0)
    image = orig.copy()
    contours, hierarchy = cv2.findContours(mask, mode=cv2.RETR_LIST, method=cv2.CHAIN_APPROX_SIMPLE)
    for c in contours:
        # 绘制轮廓
        image = cv2.drawContours(image, [c], 0, (255, 0, 0), 2)
        # 外接矩形框,没有方向角
        x, y, w, h = cv2.boundingRect(c)
        cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
        # 最小外接矩形框,有方向角
        rect = cv2.minAreaRect(c)
        print(rect)
        box = np.int0(cv2.boxPoints(rect))
        cv2.drawContours(image, [box], 0, (0, 0, 255), 2)
        # 绘制最小外接圆
        (x, y), radius = cv2.minEnclosingCircle(c)
        center = (int(x), int(y))
        radius = int(radius)
        cv2.circle(image, center, radius, (0, 255, 255), 2)
        # 用轮廓数据来拟合椭圆
        ellipse = cv2.fitEllipse(c)
        cv2.ellipse(image, ellipse, (255, 0, 255), 2)
        # 直线拟合
        rows, cols = image.shape[:2]
        [vx, vy, x, y] = cv2.fitLine(c, cv2.DIST_L2, 0, 0.01, 0.01)
        lefty = int((-x * vy / vx) + y)
        righty = int(((cols - x) * vy / vx) + y)
        image = cv2.line(image, (cols - 1, righty), (0, lefty), (0, 0, 255), 2)
        cv2.imshow("image", image)
        cv2.waitKey(0)

原图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI吃大瓜

尊重原创,感谢支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值