Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python opencv drawContours does not show anything

Tags:

python

opencv

I followed the tutorial at this page but nothing seems to happen when the line cv2.drawContours(im,contours,-1,(0,255,0),3) is executed. I was expecting to see star.jpg with a green outline, as shown in the tutorial. Here is my code:

import numpy as np
import cv2

im = cv2.imread('C:\Temp\ip\star.jpg')
print im.shape #check if the image is loaded correctly
imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,127,255,0)
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(im,contours,-1,(0,255,0),3)
pass

There are no error messages. star.jpg is the star from the above mentioned webpage. I am using opencv version 2.4.8 and Python 2.7.

Is drawContours supposed to show an image on my screen? If so, what did I do wrong? If not, how do I show the image?

Thanks

Edit:

Adding the following lines will show the image:

cv2.imshow("window title", im)
cv2.waitKey()

waitKey() is needed otherwise the window will just show a gray background. According to this post, that's because waitKey() tells it to start handling the WM_PAINT event.

like image 659
King Long Tse Avatar asked Mar 03 '14 02:03

King Long Tse


People also ask

What is cv2 drawContours?

To draw the contours, cv. drawContours function is used. It can also be used to draw any shape provided you have its boundary points. Its first argument is source image, second argument is the contours which should be passed as a Python list, third argument is index of contours (useful when drawing individual contour.

What is cv2 approxPolyDP?

The process of approximating the shape of a contour of a given polygon to the shape of the original polygon to the specified precision is called approximation of a shape of the contour. We make use of a function in OpenCV called approxPolyDP() function to perform an approximation of a shape of a contour.

What does .read do OpenCV?

. read() in OpenCV returns 2 things, boolean and data. If there are not 2 variables, a tuple will be assigned to one variable. The boolean is mostly used for error catching.


2 Answers

I had the same issue. I believe the issue is that the underlying image is 1-channel rather than 3-channel. Therefore, you need to set the color so it's nonzero in the first element (e.g. (255,0,0)).

like image 121
Daniel Andersen Avatar answered Oct 05 '22 06:10

Daniel Andersen


i too had the same problem. The thing is it shows, but too dark for our eyes to see. Solution: change the colour from (0,255,0) (for some weird reason, i too had give exactly the same color!) to (128,255,0) (or some better brighter colour)

like image 31
patel deven Avatar answered Oct 05 '22 06:10

patel deven