Javatpoint Logo
Javatpoint Logo

OpenCV Contours

Contours are defined as a curve joining all the continuous points (along the boundary), having the same color or intensity. In the other, we find counter in a binary image, we focus to find the boundary in the binary image. The official definition is following:

The Contours are the useful tool for shape analysis and object detection and recognition.

To maintain accuracy, we should use the binary images. First, we apply the threshold or canny edge detection.

In OpenCV, finding the contour in the binary image is the same as finding white object from a black background.

OpenCV provides findContours(), which is used to find the contour in the binary image. The syntax is following:

The findContours () accepts the three argument first argument is source image, second is contour retrieval mode, and the third is contours approximation.

Let's consider the following example:

How to draw the Contours?

OpenCV provides the cv2.drawContours() function, which is used to draw the contours. It is also used to draw any shape by providing its boundary points. Syntax of cv2.drawContours() function is given below:

To draw all the contours in an image:

To draw an individual contour, suppose 3rd counter

The first argument represents the image source, second argument represents the contours which should be passed as a Python list, the third argument is used as index of Contours, and other arguments are used for color thickness.

Contour Approximation Method

It is the third argument in the cv2.findCounter(). Above, we have described it to draw the boundary of the shape with same intensity. It stores the (x,y) coordinates of the boundary of a shape. But here the question arise does it store all the coordinates? That is specified by the contour approximation method.

If we pass the cv.CHAIN_APPROX_NONE, it will store all the boundary points. Sometimes it does not need to store all the points coordinate, suppose we found the contours of a straight line where it does not require to store all the contour points, it requires only two endpoints to store. So for such case, we use cv.CHAIN_APPROX_NONE, it removes all redundant points and compresses the contours, thereby saving memory.


OpenCV Contours

In the above image of rectangle, the first image shows points using with cv.CHAIN_APPROX_NONE(734) and the second image shows the one with cv2.CHAIN_APPROX_SIMPLE(only 4 points). We can see the difference between both the images.

Next TopicOpenCV Mouse Event

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA