King Long Tse
King Long Tse

Reputation: 305

Python opencv drawContours does not show anything

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.

Upvotes: 15

Views: 33660

Answers (4)

Shivam Sahil
Shivam Sahil

Reputation: 4921

I guess your original image is in gray bit plane. Since your bit plane is Gray instead of BGR and so the contour is not showing up. Because it's slightly black and grey which you cannot distinguish. Here's the simple solution [By converting the bit plane]:

im=cv2.cvtColor(im,cv2.COLOR_GRAY2BGR)
cv2.drawContours(im,contours,-1,(0,255,0),3)

Upvotes: 2

Derek Janni
Derek Janni

Reputation: 2507

You have to do something to the effect of:

cv2.drawContours(im,contours,-1,(255,255,0),3)
cv2.imshow("Keypoints", im)
cv2.waitKey(0)

Upvotes: 7

Daniel Andersen
Daniel Andersen

Reputation: 225

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)).

Upvotes: 17

patel deven
patel deven

Reputation: 750

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)

Upvotes: 8

Related Questions