Python opencv在图像上查找五边形轮廓
我试图从简单的附加图像中读取数字 为此,我试图找到五角大楼持有的数字。然而,当我试图使用opencv findcontour函数查找五角大楼时,它没有给出正确的值。我试过用这个函数进行各种排列。这些都不管用 到目前为止,我已经尝试了以下几点:Python opencv在图像上查找五边形轮廓,python,image,opencv,image-processing,opencv-contour,Python,Image,Opencv,Image Processing,Opencv Contour,我试图从简单的附加图像中读取数字 为此,我试图找到五角大楼持有的数字。然而,当我试图使用opencv findcontour函数查找五角大楼时,它没有给出正确的值。我试过用这个函数进行各种排列。这些都不管用 到目前为止,我已经尝试了以下几点: import cv2 as cv import numpy as np im = cv.imread(r'out.jpg') imgray = cv.cvtColor(im, cv.COLOR_BGR2GRAY) ret, thresh = cv.th
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.
四,
这些都不是5,所以上面的几点不可能是五角大楼
如果我犯了什么错误,你能帮我一下吗?你说得对。找到轮廓后,需要使用+,执行轮廓近似。您可以从
cv2.approxPolyDP
检查返回值,这将为您提供多边形曲线形状近似值。如果该值为5,则可以假定它是五角大楼。这里有一个简单的方法:
检测到的ROI以teal表示 提取/保存的ROI 注意:有两个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()