尝试修改 OpenCV 轮廓会导致错误



我正在尝试制作一个自定义算法来拉直轮廓,但是我目前做事的方式使我的程序崩溃。

程序本身是:

import numpy as np
import cv2
import copy
from matplotlib import pyplot as plt

def IsInLine(point, origin, dir):
    if dir[0][0] == 0 or dir[0][1] == 0:
        return False
    t1 = (point[0][0] - origin[0][0]) / dir[0][0]
    t2 = (point[0][1] - origin[0][1]) / dir[0][1]
    if abs(t1 - t2) < 10:
        return True
    else:
        return False
def StraightenContour(contour):
    new_contour = []
    if len(contour) < 100:
        return
    for i in range(0, len(contour)):
        line1 = contour[i-1] - contour[i-2]
        line2 = contour[(i+2)%len(contour)] - contour[(i+1)%len(contour)]
        if IsInLine(contour[i], contour[i-1], line1) and IsInLine(contour[i], contour[(i+2)%len(contour)], line2):
            new_contour.append([[0,0]])
    print(contour)
    return contour

img = cv2.imread('Kitchen.png')
imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(img, 100, 200)
kernel = np.ones((5,5),np.uint8)
edges = cv2.morphologyEx(
    edges, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5)), iterations = 5)
ret, thresh = cv2.threshold(edges, 127, 255, 0)
im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
img_area = im2.shape[0] * im2.shape[1]
for contour in contours:
    contour = StraightenContour(contour)
    if cv2.contourArea(contour) / img_area > 0.22:
        cv2.drawContours(img, [contour], 0, (0, 255, 0), 3)
    else:
        cv2.drawContours(img, [contour], 0, (0, 0, 255), 3)
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

当我尝试在StraightenContour()结束时返回原始轮廓时,特别会出现此问题

我的程序崩溃并显示消息:

Traceback (most recent call last):
  File "cexp.py", line 79, in <module>
    if cv2.contourArea(contour) / img_area > 0.22:
cv2.error: OpenCV(3.4.5) /io/opencv/modules/imgproc/src/shapedescr.cpp:272: error: (-215:Assertion failed) npoints >= 0 && (depth == CV_32F || depth == CV_32S) in function 'contourArea'

相反,如果我修改该行,以便:

 contour = StraightenContour(contour)

成为: 拉直轮廓(轮廓)

没有出现这样的问题。

我很困惑,因为我甚至没有触摸轮廓,只是将其归还。

我需要解决这个问题,或者找到一种方法从轮廓中删除点。

提前谢谢。

当您像 contour = StraightenContour(contour) 一样保存输出时,如果轮廓小于 100,则可能会返回 NULL。

对 NULL 的后续操作会产生您得到的错误。尝试通过将 print(len(contour)) 放在 StraightenContour(contour) 函数的开头进行调试,很可能轮廓将小于 100,从而使函数返回 NULL。

当您不将StraightenContour(contour)的输出保存在变量轮廓中时,当 len(contour) <100 时,返回时不会在任何地方保存 NULL,其余代码将正常运行。

解决方案是在其长度小于 100 时简单地return contour。也许您想考虑通过运行一些实验来找到最佳值,将 100 更改为其他值。

最新更新