Opencv 在 Python 中检测四边形

Opencv detect quadrilateral in Python

我正在使用 Python 2.7 和 OpenCV 3.0。我正在做一个 检测汽车牌照 的项目。

我现在正在检查轮廓的顶点数。如果有4个顶点(元素个数约),那么更可能是矩形/平行四边形/四边形 .

(cnts, _) = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnts=sorted(cnts, key = cv2.contourArea, reverse = True)[:10]

# loop over our contours
for c in cnts:
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.02 * peri, True)
    if len(approx) == 4 and ratio(approx):
        cv2.drawContours(image, [approx], -1, (0,255,0), 3)

然后我得到了两个带数组的四边形。

但是,你可以看到,有一个不规则多边形。这是数组:

[[[209 198]]

 [[466  94]]

 [[259 153]]

 [[247   1]]]

请教如何省略不规则四边形谢谢

根据https://whosebug.com/users/4606294/user89161 in his comment 的建议 也许您可以在 approx 上添加一个测试,例如:

hull = cv2.convexHull(approx,returnPoints = False)
defects = cv2.convexityDefects(approx,hull)

sum_of_defects=0
for i in range(defects.shape[0]):
    s,e,f,d = defects[i,0]
    sum_of_defects=sum_of_defects+d

if sum_of_defects <= threshold:
    print "approx is convex"
else:
    print "approx is not convex"

并且你必须正确选择 threshold,我将从 threshold=3 或类似的开始。理论上 threshold 应该为零。

注意:如果您知道您的多项式应该有多少条边,例如,如果您正在寻找图像中的凸四边形,那么您只需要调用:

hull = cv2.convexHull(approx, returnPoints = False)

然后你只需要检查len(hull) == num_expected_sides,在四边形的情况下:

len(cv2.convexHull(approx, returnPoints = False)) == 4