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

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

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

import cv2
import numpy as np


def get_contour(img):
    """获取连通域

    :param img: 输入图片
    :return: 最大连通域
    """
    # 灰度化, 二值化, 连通域分析
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    ret, img_bin = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)

    img_contour, contours, hierarchy = cv2.findContours(img_bin, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)

    return contours[0]


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

    # 2.获取连通域
    contour_src = get_contour(img_src)

    # 3.获取外接正矩形
    st_x, st_y, width, height = cv2.boundingRect(contour_src)

    print("x=", st_x)
    print("y=", st_y)
    print("w=", width)
    print("h=", height)

    rect = cv2.boundingRect(contour_src)
    print("rect=", rect)

    # 4.绘制外接正矩形
    bound_rect = np.array([[[st_x, st_y]], [[st_x + width, st_y]],
                           [[st_x + width, st_y + height]], [[st_x, st_y+height]]])

    cv2.drawContours(img_src, [bound_rect], -1, (255, 255, 255), 2)

    # 5.显示结果
    cv2.imshow("img_src", img_src)

    cv2.waitKey()
    cv2.destroyAllWindows()


if __name__ == '__main__':
    main()

处理结果图片:[img_src.jpg]
OpenCV python 轮廓(连通域)外接正矩形_第2张图片

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