Jordan Yeomans
Jordan Yeomans

Reputation: 23

Problems drawing a specific contour using cv2.drawContours() Python 3

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

Here is the Code:

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

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

When drawContours() is Set to, -1

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

Upvotes: 2

Views: 5318

Answers (1)

janu777
janu777

Reputation: 1978

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

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)

Upvotes: 3

Related Questions