I am trying to draw contours around my test image. I am using canny edge detection in the background.
The findContours
method works fine for my image but when I try to do drawContours
method on that image. It does not show anything.
Here is what I have tried
import cv2
import numpy as np
image = cv2.imread('/path/to/image.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (11, 11), 0)
cv2.imshow("blurred", blurred)
canny = cv2.Canny(blurred, 30, 150)
(_, cnts, _) = cv2.findContours(canny.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
print "Contours in the image, %d" % (len(cnts))
shape = image.copy()
cv2.drawContours(shape.copy(), cnts, -1, (0, 255, 0), 2)
cv2.imshow("Edges", shape)
From what I gather from the docs, the fourth argument to the method drawContours
would be used to specify the colour of the edge to be drawn over. But it does not show anything for instead of the green edge that I am expecting.
len(cnts)
returns 2 for me
Here is the image I am trying it out with
I am using opencv version 3.0.0
Relevant SO question
EDIT: After changing the 3rd argument for cv2.findContours()
to cv2.CHAIN_APPROX_NONE
, it is still not showing the final green edges(or any colour for that matter) on the final cv2.imshow("Edges", shape)
image. Here is what I get from the canny edge image
You have to modify the last to lines of your code to:
You are already storing a copy of image
in shape
shape = image.copy()
So why do you use shape.copy()
in cv2.drawContours()
again?
Replace it as follows:
cv2.drawContours(shape, cnts, -1, (0, 255, 0), 2)
cv2.imshow("Edges", shape)
NOTE: You already have copied the image once, so use it to draw the contours. You don't have to use a copied version of the copied image.
This is what you get as a result: