Python opencv 在图像上找到五边形轮廓

Python opencv find pentagon contour on image

我正在尝试从简单的附加图像中读取数字。

为此,我试图找到包含数字的五边形。但是,当我尝试使用 opencv findcontour 函数查找五边形时,它没有给出正确的值。我用那个函数尝试了各种排列。 None 有效。

到目前为止我已经尝试过:

import cv2 as cv
import numpy as np

im = cv.imread(r'out.jpg')
imgray = cv.cvtColor(im, cv.COLOR_BGR2GRAY)
ret, thresh = cv.threshold(imgray, 200, 255, 0)

contours, hierarchy = cv.findContours(thresh, cv.RETR_LIST  , cv.CHAIN_APPROX_SIMPLE)

for c in contours:
    print(len(c))

输出: 1个 1个 1个 1个 1个 1个 1个 1个 38 36 1个 1个 85 87 128 133 55 47 4个 4个 7 4个 4个 4

None这个是5,所以上面的点不可能是五边形。

如果我有任何错误,你能帮助我吗?

你走在正确的轨道上。找到轮廓后,需要使用cv2.approxPolyDP + cv2.arcLength进行轮廓逼近。您可以检查 cv2.approxPolyDP 中的 return 值,这将为您提供多边形曲线形状近似值。如果这个值为五,那么你可以假设它是一个五边形。这是一个简单的方法:

  1. 获取二值图像。加载图像,灰度,bilateral filter, Otsu's threshold

  2. 查找轮廓并执行轮廓近似。使用 Numpy 切片查找具有 cv2.findContours then perfrom contour approximation. If a contour passes this filter we extract the bounding rectangle coordinates with cv2.boundingRect 和 extract/save ROI 的轮廓。


检测到的 ROI 为蓝绿色

Extracted/saved 投资回报率

注意:有两个ROI保存为单独的图像,但它们是相同的。

代码

import cv2
import numpy as np

# Load image, grayscale, bilaterial filter, Otsu's threshold
image = cv2.imread('1.jpg')
original = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.bilateralFilter(gray,9,75,75)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Find contours, perform contour approximation, and extract ROI
ROI_num = 0
cnts = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.04 * peri, True)
    # If has 5 then its a pentagon
    if len(approx) == 5:
        x,y,w,h = cv2.boundingRect(approx)
        cv2.rectangle(image, (x, y), (x + w, y + h), (200,255,12), 2)
        ROI = original[y:y+h, x:x+w]
        cv2.imwrite('ROI_{}.png'.format(ROI_num), ROI)
        ROI_num += 1

cv2.imshow('thresh', thresh)
cv2.imshow('ROI', ROI)
cv2.imshow('image', image)
cv2.waitKey()