使用cv2.drawContours()Python 3绘制特定轮廓时出现问题

使用cv2.drawContours()Python 3绘制特定轮廓时出现问题,python,opencv,cv2,Python,Opencv,Cv2,我在使用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 (

我在使用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

但是,如果我将显示的轮廓数设置为=-1(全部),似乎会得到一些轮廓

我已经尽了最大努力来解决这个问题,任何建议都将不胜感激

cv2.drawContours(image, contours, contourIdx, color, thickness)
绘制图像中的所有轮廓:contourIdx=-1 要绘制特定轮廓,请在列表中选择第三个轮廓,然后将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)