Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DrawContours() not working opencv python

I was working on the example of finding and drawing contours in opencv python. But when I run the code, I see just a dark window with no contours drawn. I don't know where I am going wrong. The code is:

import numpy as np
import cv2
im = cv2.imread('test.png')
imgray=cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,127,255,0)
image, contours, hierarchy =     cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
img=cv2.drawContours(image,contours,0,(0,255,0),3)
cv2.imshow('draw contours',img)
cv2.waitKey(0)

test.png is just a white rectangle in black background.

Any help would be appreciated.

Edit: I am using Opencv 3.0.0 and Python 2.7

like image 503
Nil Avatar asked Jul 17 '15 12:07

Nil


People also ask

How to detect contours in OpenCV?

Use the findContours() function to detect the contours in the image. Draw Contours on the Original RGB Image.

What is contourIdx?

contourIdx. parameter indicating a contour to draw. If it is negative, all the contours are drawn. color.

What is image contour?

Image contouring is process of identifying structural outlines of objects in an image which in turn can help us identify shape of the object.


2 Answers

I believe the problem is with the drawContours command. As currently written, the image destination is both image and img. You are also attempting to draw a colored box onto a single channel 8-bit image. In addition, it is worth noting that the findContours function actually modifies the input image in the process of finding the contours, so it is best not to use that image in later code.

I would also recommend creating a new image copy to set as your destination for the drawContours function if you intend on doing further analysis on your image so you don't write over the only copy to which your program currently has access.

import numpy as np
import cv2

im = cv2.imread('test.png')
imCopy = im.copy()
imgray=cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,127,255,0)
image, contours, hierarchy =  cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(imCopy,contours,-1,(0,255,0))
cv2.imshow('draw contours',imCopy)
cv2.waitKey(0)

These two quick fixes worked for me on a similar image of a black square with a white background.

like image 96
Andrew Avatar answered Oct 09 '22 03:10

Andrew


Just make sure that image is 3 channel here:

img = cv2.drawContours(image, contours, -1, (0, 255, 0), 3)

Check image shape:

print(image.shape)
# (400, 300)    -> Error
# (400, 300, 3) -> Works
like image 20
Scott Avatar answered Oct 09 '22 03:10

Scott