因此,我一直试图获取轮廓及其外壳的缺陷。在研究了一些教程之后,我遇到了类似的代码,但是无论我如何实现,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)
[如果有人遇到类似问题或知道我要去哪里错,那将是很大的帮助。
所以您没有看到任何错误的原因是由于您尝试了catch块。通常,使用catch块需要“捕获”错误。您可以通过两种方法查看错误:
删除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语句,您应该能够找到问题并搜索解决方案。