4

I want to find the contours of an image to then draw its convex hull. What I am doing is loading the image, threshold it, find its contours and then draw the convex hull.

gray = cv2.imread(test_paths[i], 0)
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnt = contours[0]

The number of contours detected is equal to 1. The problem comes when I try to plot the contours, if I do

cv2.drawContours(cnt_dst, cnt, -1, (255, 0, 0), 3)
plt.imshow(cnt_dst)

enter image description here

If I change the code to the following:

cv2.drawContours(cnt_dst, contours, 0, (255, 0, 0), 3)
plt.imshow(cnt_dst)

The contours are different:

enter image description here

Note that I am getting the same (nice) result with this:

cv2.drawContours(cnt_dst, contours, -1, (255, 0, 0), 3)

Any ideas of why this is happening?

Jeru Luke
  • 13,413
  • 9
  • 57
  • 71
Manuel Lagunas
  • 2,026
  • 15
  • 30

1 Answers1

5

cv2.drawContours(cnt_dst, contours, 0, (255, 0, 0), 3) or cv2.drawContours(cnt_dst, contours, -1, (255, 0, 0), 3) are the same in that case

-1 tells opencv to draw all the contours of the contours array, and 0 tells it to draw the first contour of the contours array.

Since there's only one contour, the result is the same.

The other call cv2.drawContours(cnt_dst, cnt, -1, (255, 0, 0), 3) is probably bogus / should be better checked on the opencv side.

In this blog it indicates:

Now you want to draw "cnt" only. It can be done as follows:
cv2.drawContours(im,[cnt],0,(255,0,0),-1) Note the square bracket around "cnt". Third argument set to 0, means only that particular contour is drawn.

Jean-François Fabre
  • 126,787
  • 22
  • 103
  • 165