


Even if there are methods available on the web to do this work for you, it's worth implementing a few basic techniques yourself before you go googling. First image shows points I got with cv.CHAIN_APPROX_NONE (734 points) and second image shows the one with cv.CHAIN_APPROX_SIMPLE (only 4 points).The definition of "local maximum" can be tricky to pin down, but if you start with a simple method you'll develop an intuition to look further. Just draw a circle on all the coordinates in the contour array (drawn in blue color). It removes all redundant points and compresses the contour, thereby saving memory.īelow image of a rectangle demonstrate this technique. This is what cv.CHAIN_APPROX_SIMPLE does. Do you need all the points on the line to represent that line? No, we need just two end points of that line. But actually do we need all the points? For eg, you found the contour of a straight line. If you pass cv.CHAIN_APPROX_NONE, all the boundary points are stored. But does it store all the coordinates ? That is specified by this contour approximation method. It stores the (x,y) coordinates of the boundary of a shape. What does it denote actually?Ībove, we told that contours are the boundaries of a shape with same intensity. This is the third argument in cv.findContours function. Note Last two methods are same, but when you go forward, you will see last one is more useful. To draw all contours, pass -1) and remaining arguments are color, thickness etc.Ĭv.drawContours(img,, 0, (0,255,0), 3) Its first argument is source image, second argument is the contours which should be passed as a Python list, third argument is index of contours (useful when drawing individual contour. It can also be used to draw any shape provided you have its boundary points. To draw the contours, cv.drawContours function is used.
Easy contour python code#
Until then, the values given to them in code sample will work fine for all images. Note We will discuss second and third arguments and about hierarchy in details later. Each individual contour is a Numpy array of (x,y) coordinates of boundary points of the object. Contours is a Python list of all the contours in the image. And it outputs the contours and hierarchy.

See, there are three arguments in cv.findContours() function, first one is source image, second is contour retrieval mode, third is contour approximation method. Contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
