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:
cv2. findContours (thes, cv2.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
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:
import numpy as np import cv2 as cv im = cv.imread(r'C:\Users\DEVANSH SHARMA\binary.png') imgray = cv.cvtColor(im, cv.COLOR_BGR2GRAY) ret, thresh = cv.threshold(imgray, 127, 255, 0) contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
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:
cv2.drawCounter(img, contours,-1, (0,255,0),3)
To draw an individual contour, suppose 3rd counter
cnt = contours cv2.drawCounter(img,[cnt],0,(0,255,0),3)
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.
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.