使用cv2.drawContours()Python 3绘制特定轮廓时出现问题 [英] Problems drawing a specific contour using cv2.drawContours() Python 3

查看:51
本文介绍了使用cv2.drawContours()Python 3绘制特定轮廓时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用python的cv2.drawContours()遇到问题

I am having a problem with cv2.drawContours() using python

问题:我无法显示单个轮廓.我只想听一听

Problem: I can't show single contour. I would like to get just the track

以下是代码:

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

原始图像将drawContours()设置为0时,

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

but it seems to get a few contours if I set the number of contours to show = -1 (all of them)

将drawContours()设置为-1

我已经尽力解决了这个问题,我们将不胜感激

I've tried my best to fix this one, any advice would be highly appreciated

推荐答案

cv2.drawContours(image, contours, contourIdx, color, thickness)

绘制图像中的所有轮廓:contourIdx = -1要绘制特定轮廓,请在列表中说出第三轮廓,然后设置轮廓IDx = 2

Draw all the contours in the image : contourIdx = -1 To draw a specific contour say 3 rd contour in the list, then set contourIdx = 2

因此,如果您想要具有赛车轨迹的轮廓,请找到其索引并进行绘制.否则,假设跑道的轮廓是该区域中最大的.您可以简单地执行以下操作:

So If you want the contour which has the race track, then find its index and draw it. Else, assuming the racetrack's contour is the largest in area. You can simply do the following:

_, 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)

这篇关于使用cv2.drawContours()Python 3绘制特定轮廓时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆