你在正确的轨道上。找到轮廓后,您需要使用cv2.approxPolyDP + cv2.arcLength 执行轮廓逼近。您可以检查来自cv2.approxPolyDP 的返回值,这将为您提供多边形曲线形状近似值。如果这个值是五,那么你可以假设它是一个五边形。这是一个简单的方法:
获取二值图像。加载图像,灰度,bilateral filter,Otsu's threshold
查找轮廓并执行轮廓逼近。 使用cv2.findContours 查找轮廓,然后执行轮廓逼近。如果轮廓通过此过滤器,我们将使用cv2.boundingRect 提取边界矩形坐标,并使用 Numpy 切片提取/保存 ROI。
检测到的 ROI 是蓝绿色的
提取/保存的 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()