0

所以我一直在尝试找出轮廓及其外壳的缺陷。在查看了一些教程后,我遇到了类似的代码,但无论我如何实现它,这条线cv2.convexityDefects似乎让我跳出了循环,而不是显示视频。该程序在没有缺陷部分的情况下工作,并且我没有在缺陷部分中遇到任何错误,但它似乎只是结束了代码。

    contours, H = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    contours = sorted(contours, key=cv2.contourArea, reverse=True)

    max_area = 0
    for i in range(len(contours)):  # finding largest contour by area [3]
        contour = contours[i]
        area = cv2.contourArea(contour)
        if area > max_area:
            max_area = area
            ci = i
    if len(contours) > 0:
        (x, y, w, h) = cv2.boundingRect(contours[ci])
        # cv2.rectangle(resized, (x, y), (x + w, y + h), (0, 255, 0), 2)
        moments = cv2.moments(contours[ci])
        if moments['m00'] != 0:  # this gives the centre of the moments [3]
            cx = int(moments['m10'] / moments['m00'])  # cx = M10/M00
            cy = int(moments['m01'] / moments['m00'])  # cy = M01/M00
        center = (cx, cy)
        cv2.circle(resized, center, 5, [0, 0, 255], 2)  # draws small circle at the center moment
        hull = cv2.convexHull(contours[ci])
        defects = cv2.convexityDefects(contours[ci], hull)

        if len(defects) > 0:
            for i in range(defects.shape[0]):
                s, e, f, d = defects[i, 0]
                start = tuple(contours[ci][s][0])
                end = tuple(contours[ci][e][0])
                far = tuple(contours[ci][f][0])
                cv2.line(resized, start, end, [0, 255, 0], 2)
                cv2.circle(resized, far, 5, [0, 0, 255], -1)
        else:
            cv2.drawContours(resized, [contours[ci]], 0, (0, 255, 0), 2)
            cv2.drawContours(resized, [hull], 0, (0, 0, 255), 2)

如果有人遇到过类似的问题或知道我哪里出错了,那将是一个很大的帮助。

4

1 回答 1

0

所以你没有看到任何错误的原因是你的 try, catch 块。通常使用 catch 块,您需要“捕获”错误。您有两个选项可以查看您的错误:

  1. 删除 try、catch 语句。你会在这里看到完整的错误

catch Exception as e:
     print(e)
     break

然后你会看到你有ValueError: too many values to unpack (expected 2). 从我在网上看到的情况来看,您的代码似乎基于使用与您不同版本的 OpenCV 的示例。我不确定您使用的是什么,但请记住,有 OpenCV2、OpenCV3 和 OpenCV4,然后它们有其次要版本。

编辑:
实际上,我刚刚意识到您可能有不同版本的 OpenCV。我正在使用 Opencv 3.4.2 和 Python3,我认为我是用 pip3 安装的。您可能有不同的错误。我实际上发现问题出在cv2.findContours而不是cv2.convexityDefects因此您实际上可能没有 ValueError。捕获异常或删除 try、catch 语句,您应该能够找到您的问题并搜索解决方案。

于 2020-03-12T20:12:51.323 回答