我使用python
遇到了cv2.drawContours()的问题问题:我无法显示单个轮廓。我想获得这条赛道
以下是代码:
original_image = np.array(ImageGrab.grab(bbox))
crop_img = original_image[200:307, :, :]
# Convert BGR to HSV
hsv = cv2.cvtColor(crop_img, cv2.COLOR_BGR2HSV)
# define range of track (grey) color in HSV
lower_grey = np.array([0, 0, 0])
upper_grey = np.array([255, 40, 150])
# Threshold the HSV image to get only gery colors
grey_mask = cv2.inRange(hsv, lower_grey, upper_grey)
grey_mask2 = grey_mask.copy()
_, contours, heir = cv2.findContours(grey_mask2, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(grey_mask2, contours, 0, (0, 255, 0), 3)
cv2.imshow('Orig Image', crop_img)
cv2.imshow('Grey Mask', grey_mask2)
if cv2.waitKey(25) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
Original Image When drawContours() is Set to, 0
但如果我将轮廓数设置为show = -1(所有轮廓),它似乎会得到一些轮廓
When drawContours() is Set to, -1
我已经尽力解决这个问题,任何建议都会受到高度赞赏
答案 0 :(得分:2)
cv2.drawContours(image, contours, contourIdx, color, thickness)
绘制图像中的所有轮廓:contourIdx = -1 要在列表中绘制特定轮廓,例如第3轮廓,则设置contourIdx = 2
所以如果你想要具有赛道的轮廓,那么找到它的索引并绘制它。另外,假设赛道的轮廓是面积最大的。您可以简单地执行以下操作:
_, contours, heir = cv2.findContours(grey_mask2, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
c = max(contours, key = cv2.contourArea)
cv2.drawContours(grey_mask2,[c],0,(0, 255, 0),3)