欢迎访问宙启技术站
智能推送

opencv3.0识别并提取图形中的矩形的方法

发布时间:2023-05-15 14:02:46

OpenCV是一个功能强大的计算机视觉库,其中包含了用于识别和提取图形中矩形的方法。本文将介绍如何使用OpenCV3.0中提供的方法来识别和提取图形中的矩形。

1. 图像处理

首先,需要对图像进行处理。这包括读取图像文件、将图像转换为灰度图像,并进行边缘检测。

    # read image file

    img = cv2.imread('input.jpg')

    # convert image to grayscale

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # detect edges in the image

    edges = cv2.Canny(gray, 50, 150)

2. 检测轮廓

为了从图像中提取矩形,需要首先检测出图像中的轮廓。OpenCV提供了函数cv2.findContours()来做这件事。

    # find contours in the image

    contours, hierarchy = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

RETR_EXTERNAL表示仅检测外部轮廓, CHAIN_APPROX_SIMPLE表示只保留轮廓的端点,而删除其他的点,这将产生较小的轮廓表示并节省空间。

3. 筛选轮廓

找到所有轮廓后,需要进一步筛选轮廓以提取矩形。一个矩形的特点是它有四个边和四个角。因此,可以使用函数cv2.approxPolyDP()来检测是否具有四个角的轮廓。其中,偏差值epsilon是表示多边形近似和真实轮廓之间的差异的参数。如果偏差值越小,近似多边形将越接近真实轮廓。

    for contour in contours:

        # approximate the contour with a polygon

        approx = cv2.approxPolyDP(contour, 0.01 * cv2.arcLength(contour, True), True)

        # if the polygon has four sides, it is likely a rectangle

        if len(approx) == 4:

            rectangles.append(approx)

4. 绘制矩形

最后,可以在原始图像上绘制找到的矩形。此外,还可以将矩形分离并保存为单独的图像文件。

    for rectangle in rectangles:

        # draw the rectangle on the image

        cv2.drawContours(img, [rectangle], 0, (0, 0, 255), 2)

        # extract the rectangle and save it to a separate image file

        x, y, w, h = cv2.boundingRect(rectangle)

        roi = img[y:y + h, x:x + w]

        cv2.imwrite('output.jpg', roi)

5. 完整代码

    import cv2

    # read image file

    img = cv2.imread('input.jpg')

    # convert image to grayscale

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # detect edges in the image

    edges = cv2.Canny(gray, 50, 150)

    # find contours in the image

    contours, hierarchy = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    rectangles = []

    for contour in contours:

        # approximate the contour with a polygon

        approx = cv2.approxPolyDP(contour, 0.01 * cv2.arcLength(contour, True), True)

        # if the polygon has four sides, it is likely a rectangle

        if len(approx) == 4:

            rectangles.append(approx)

    for rectangle in rectangles:

        # draw the rectangle on the image

        cv2.drawContours(img, [rectangle], 0, (0, 0, 255), 2)

        # extract the rectangle and save it to a separate image file

        x, y, w, h = cv2.boundingRect(rectangle)

        roi = img[y:y + h, x:x + w]

        cv2.imwrite('output.jpg', roi)

    # show the original and processed images

    cv2.imshow('Original Image', img)

    cv2.imshow('Processed Image', edges)

    cv2.waitKey(0)

    cv2.destroyAllWindows()