I\'m trying to create a mask from a contour, but am getting a C++ error.
Using OS X Yosemite, Python 2.7.10, OpenCV 3.1.0.
def create_mask(img, cnt):
For me this worked. But I'm not sure why.
cv2.drawContours(mask, [cnt.astype(int)], 0, (0, 255, 0), -1)
When you get an array of rounded floats from findContours, drawContours doesn't complain. But when I construct a similar (4,2) array of floats myself, it complains.
I think you are adding extra []
around cnt
it should be
cv2.drawContours(mask, cnt, 0, (0, 255, 0), -1)
as cnt
is already array of array but [cnt]
is array of array of arrays which won't work
Update to the above code
you should convert your contour to numpy array first
ctr = numpy.array(cnt).reshape((-1,1,2)).astype(numpy.int32)
cv2.drawContours(mask, [ctr], 0, (0, 255, 0), -1)
check documentation here
contours is a Python list of all the contours in the image. Each individual contour is a Numpy array of (x,y) coordinates of boundary points of the object.
You might have commited mistake while finding the contours. Contour is the second value returned by findContours()
function as the docs say
im2, contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
So the following code will not work
cnt = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
This might solve your problem.
If you just use this, it will work...
ctr = np.array(cnt).reshape((-1,1,2)).astype(np.int32)
cv2.drawContours(mask, [ctr], -1, 255, -1)
its hierarchy, contours so:
contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)