Opencv3 错误:轮廓不是 numpy 数组,也不是标量



>我正在尝试匹配形状组中的单个形状图像 图像。我能够找到轮廓,但它无法匹配形状 从形状组图像。

这是我面临的错误:-

TypeError                                 Traceback (most recent call last)
<ipython-input-3-83126d2189ca> in <module>()
36         closest_contour = []
37 
---> 38 cv2.drawContours(target,[closest_contour], -1, (0,255,0), 3)
39 cv2.imshow('Output',target)
40 cv2.waitKey()
TypeError: contours is not a numpy array, neither a scalar

下面是代码:

template = cv2.imread('shape_match/star.png',0)
#template = cv2.cvtColor(template,cv2.COLOR_BGR2GRAY)
cv2.imshow('Template',template)
cv2.waitKey()
#load the target image with the shapes we're trying to match
target = cv2.imread('shape_match/matchshapes.jpg')
target_gray = cv2.cvtColor(target,cv2.COLOR_BGR2GRAY)
# Threshold both images first before using cv2.findContours
ret, thresh1 = cv2.threshold(template,127, 255, 0)
ret, thresh2 = cv2.threshold(target_gray, 127, 255, 0)
# Find contours in template
_, contours, hierarchy = cv2.findContours(thresh1, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
# we need to sort the contours by area so that we can remove the largest
#contours which is the image outline
sorted_contours = sorted(contours,key=cv2.contourArea, reverse=True)
# we extract the second largest contour which will be our template contour
template_contour = contours[1]
# Extract contours from second target image
_, contours,hierarchy = cv2.findContours(thresh2,cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
# Iterate through each contour in the target image and 
# use cv2.matchShapes tocompare contour shapes
match = cv2.matchShapes(template_contour,c,1,0.0)
print(match)
# if the match value is  less than 0.15 we
if match <0.15:
closest_contour = c
else:
closest_contour = []
cv2.drawContours(target,[closest_contour], -1, (0,255,0), 3)
cv2.imshow('Output',target)
cv2.waitKey()
cv2.destroyAllWindows()

我是计算机视觉的初学者,请帮助我。

我认为这里发生的事情是,最接近的轮廓正在获取导致函数错误的空列表的值。在我看来,一旦找到符合您标准的轮廓,您就想打破您的 for 循环,所以请尝试以下操作:

closest_contour = None
for c in contours:
# Iterate through each contour in the target image and 
# use cv2.matchShapes tocompare contour shapes
match = cv2.matchShapes(template_contour,c,1,0.0)
print(match)
# if the match value is  less than 0.15 we
if match <0.15:
closest_contour = c
break
if closest_contour is not None:
cv2.drawContours(target,[closest_contour], -1, (0,255,0), 3)
else:
print("No closest contour found")
cv2.imshow('Output',target)
cv2.waitKey()
cv2.destroyAllWindows()

相关内容

最新更新