Ask Your Question

Difference in drawn result between cv2.drawContours and drawing contours with a loop

asked 2020-06-18 04:10:18 -0500

read_a_book gravatar image

updated 2020-09-05 07:26:33 -0500


I am hoping someone could help me understand this strange result I stumbled upon today while drawing contours.

When I draw all the contours at once with cv2.drawContours(image, contours, -1, (255, 50, 255),1) I get a nice result:

image description

However, when I draw each contour individually by looping through the contours with a for loop:

for cnt in contours: cv2.drawContours(blank2, cnt, -1, (255, 50, 255), 1)

I get a very low quality result where the car shape is not even fully outlined anymore

image description

I have tried displaying the images with cv2.imShow, zooming in, increasing line thickness and I keep getting this weird result. Is there a difference I do not know about between drawing the contours in these two different ways?

I have copy pasted my code below. Thank you for your help!

image = cv2.imread(imagePath)
imageB,_,_ = cv2.split(image)

_, imageThresh = cv2.threshold(imageB,118,255,cv2.THRESH_BINARY_INV)

contours, hierarchy = cv2.findContours(imageThresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

blank = np.ones_like(image)
cv2.drawContours(blank, contours, -1, (255, 50, 255), 1)

blank2 = np.ones_like(image)
for index,cnt in enumerate(contours):
    cv2.drawContours(blank2, cnt, -1, (255, 50, 255), 1)

plt.title("Result 2")
edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2020-06-18 04:15:42 -0500

berak gravatar image

updated 2020-06-18 04:35:09 -0500

your code here:

for index,cnt in enumerate(contours):
    cv2.drawContours(blank2, cnt, -1, (255, 50, 255), 1)

is simply wrong.

cv2.drawContours expects an array of contours, if you give it a single one, it will still try to access it as an array of arrays, and yea, bad result.

blame python's non-existing type system for making such an error possible.

if you want to use a loop, it has to be like this (use all the contours and an index):

for index, _ in enumerate(contours):
    cv2.drawContours(blank2, contours, index, (255, 50, 255), 1)
edit flag offensive delete link more


Aaaaahhhh Thank you!!! Ive been copy pasting without checking my arguments. Glad I can blame python and not myself : )

read_a_book gravatar imageread_a_book ( 2020-06-18 04:34:38 -0500 )edit

Question Tools

1 follower


Asked: 2020-06-18 04:10:18 -0500

Seen: 383 times

Last updated: Jun 18 '20