OpenCV python 轮廓(连通域)最小外接矩形

OpenCV python 轮廓(连通域)最小外接矩形

OpenCV python 轮廓(连通域)最小外接矩形_第1张图片

import cv2
import numpy as np


def main():

    # 1.导入图片
    img_src = cv2.imread("cc.jpg")

    # 2.灰度化,二值化
    img_gray = cv2.cvtColor(img_src, cv2.COLOR_BGR2GRAY)
    ret, img_bin = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)

    # 3.连通域分析
    img_bin, contours, hierarchy = cv2.findContours(img_bin,
                                                    cv2.RETR_LIST,
                                                    cv2.CHAIN_APPROX_SIMPLE)

    # 4.获取最小外接矩形并打印
    min_rect = cv2.minAreaRect(contours[0])
    print("返回值min_rect:\n", min_rect)
    rect_points = cv2.boxPoints(min_rect)
    print("返回值rect_points:\n", rect_points)
    rect_points = np.int0(rect_points)

    # 5.绘制最小外接矩形
    img_result = img_src.copy()
    cv2.drawContours(img_result, [rect_points], 0, (255, 255, 255), 2)

    # 6.显示结果图片
    cv2.imshow("img_src", img_src)
    cv2.imshow("img_result", img_result)

    cv2.waitKey()
    cv2.destroyAllWindows()


if __name__ == '__main__':
    main()

结果图片:[img_result.jpg]
OpenCV python 轮廓(连通域)最小外接矩形_第2张图片

你可能感兴趣的:(Opencv-python)