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