Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating your own contour in opencv using python

Tags:

I have a set of boundary points of an object.

I want to draw it using opencv as contour.

I have no idea that how to convert my points to contour representation.

To the same contour representation which is obtained by following call

contours,_ = cv2.findContours(image,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) 

Any ideas?

Thanks

like image 896
Shan Avatar asked Jan 04 '13 16:01

Shan


People also ask

How do you show contours in Python?

findContours() function. First one is source image, second is contour retrieval mode, third is contour approximation method and it outputs the image, contours, and hierarchy. 'contours' is a Python list of all the contours in the image.

What is contour in Python?

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. Note. We will discuss second and third arguments and about hierarchy in details later.


2 Answers

By looking at the format of the contours I would think something like this should be sufficient:

contours = [numpy.array([[1,1],[10,50],[50,50]], dtype=numpy.int32) , numpy.array([[99,99],[99,60],[60,99]], dtype=numpy.int32)] 

This small program gives an running example:

import numpy import cv2  contours = [numpy.array([[1,1],[10,50],[50,50]], dtype=numpy.int32) , numpy.array([[99,99],[99,60],[60,99]], dtype=numpy.int32)]  drawing = numpy.zeros([100, 100],numpy.uint8) for cnt in contours:     cv2.drawContours(drawing,[cnt],0,(255,255,255),2)  cv2.imshow('output',drawing) cv2.waitKey(0) 
like image 118
sietschie Avatar answered Oct 01 '22 23:10

sietschie


To create your own contour from a python list of points L

L=[[x1,y1],[x2,y2],[x3,y3],[x4,y4],[x5,y5],[x6,y6],[x7,y7],[x8,y8],[x9,y9],...[xn,yn]] 

Create a numpy array ctr from L, reshape it and force its type

ctr = numpy.array(L).reshape((-1,1,2)).astype(numpy.int32) 

ctr is our new countour, let's draw it on an existing image

cv2.drawContours(image,[ctr],0,(255,255,255),1) 
like image 27
Cherif KAOUA Avatar answered Oct 02 '22 01:10

Cherif KAOUA