DrawContours() not working opencv python

心已入冬 提交于 2019-12-23 03:30:29

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/31475634/drawcontours-not-working-opencv-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!