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)

原图

猜你喜欢

转载自blog.csdn.net/guyuealian/article/details/123866551