The Wayback Machine - https://web.archive.org/web/20240712175353/https://www.geeksforgeeks.org/find-and-draw-contours-using-opencv-python/
Open In App

Find and Draw Contours using OpenCV | Python

Last Updated : 04 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Contours are defined as the line joining all the points along the boundary of an image that are having the same intensity. Contours come handy in shape analysis, finding the size of the object of interest, and object detection.

OpenCV has findContour() function that helps in extracting the contours from the image. It works best on binary images, so we should first apply thresholding techniques, Sobel edges, etc.

Below is the code for finding contours –




import cv2
import numpy as np
  
# Let's load a simple image with 3 black squares
image = cv2.imread('C://Users//gfg//shapes.jpg')
cv2.waitKey(0)
  
# Grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  
# Find Canny edges
edged = cv2.Canny(gray, 30, 200)
cv2.waitKey(0)
  
# Finding Contours
# Use a copy of the image e.g. edged.copy()
# since findContours alters the image
contours, hierarchy = cv2.findContours(edged, 
    cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
  
cv2.imshow('Canny Edges After Contouring', edged)
cv2.waitKey(0)
  
print("Number of Contours found = " + str(len(contours)))
  
# Draw all contours
# -1 signifies drawing all contours
cv2.drawContours(image, contours, -1, (0, 255, 0), 3)
  
cv2.imshow('Contours', image)
cv2.waitKey(0)
cv2.destroyAllWindows()


Output:

We see that there are three essential arguments in cv2.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. Each individual contour is a Numpy array of (x, y) coordinates of boundary points of the object.

Contours Approximation Method –
Above, we see that contours are the boundaries of a shape with the same intensity. It stores the (x, y) coordinates of the boundary of a shape. But does it store all the coordinates? That is specified by this contour approximation method.
If we pass cv2.CHAIN_APPROX_NONE, all the boundary points are stored. But actually, do we need all the points? For eg, if we have to find the contour of a straight line. We need just two endpoints of that line. This is what cv2.CHAIN_APPROX_SIMPLE does. It removes all redundant points and compresses the contour, thereby saving memory.


Previous Article
Next Article

Similar Reads

Find Co-ordinates of Contours using OpenCV | Python
In this article, we will learn how to find the co-ordinates of Contours with the help of OpenCV. Contours are defined as the line joining all the points along the boundary of an image that are having the same intensity. Contours come handy in shape analysis, finding the size of the object of interest, and object detection. We will be using OpenCV f
3 min read
Draw contours on an unstructured triangular grid in Python using Matplotlib
Matplotlib is a Python library which is an open-source drawing library which supports rich drawing types, it can be used to draw 2D and 3D graphics. Data can be understood easily by visualizing it with the help of matplotlib. You can also generate plots, pie charts, histograms, and many other charts as well. It provides a MATLAB-like plotting inter
5 min read
Ternary contours Plot using Plotly in Python
A Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. Ternary contours in Plotly In plotly, ternary
3 min read
Draw a rectangular shape and extract objects using Python's OpenCV
OpenCV is an open-source computer vision and machine learning software library. Various image processing operations such as manipulating images and applying tons of filters can be done with the help of it. It is broadly used in Object detection, Face Detection, and other Image processing tasks. Let's see how to draw rectangular shape on image and e
4 min read
Draw Multiple Rectangles in Image using Python-Opencv
In this article, we are going to see how to draw multiple rectangles in an image using Python and OpenCV. Function used:imread(): In the OpenCV, the cv2.imread() function is used to read an image in Python. Syntax: cv2.imread(path_of_image, flag) rectangle(): In the OpenCV, the cv2.rectangle function is used to draw a rectangle on the image in Pyth
2 min read
How to draw Filled rectangle to every frame of video by using Python-OpenCV?
In this article, we will discuss how to draw a filled rectangle on every frame of video through OpenCV in Python. Stepwise Implementation:Import the required libraries into the working space.Read the video on which you have to write. Syntax: cap = cv2.VideoCapture("path") Create an output file using cv2.VideoWriter_fourcc() method. Here you will ha
2 min read
Draw geometric shapes on images using OpenCV
OpenCV provides many drawing functions to draw geometric shapes and write text on images. Let's see some of the drawing functions and draw geometric shapes on images using OpenCV. Some of the drawing functions are : cv2.line() : Used to draw line on an image. cv2.rectangle() : Used to draw rectangle on an image. cv2.circle() : Used to draw circle o
3 min read
Draw a filled polygon using the OpenCV function fillPoly()
fillPoly() function of OpenCV is used to draw filled polygons like rectangle, triangle, pentagon over an image. This function takes inputs of an image and endpoints of Polygon and color. Syntax: cv2.fillpoly(Image,End_Points,Color) Parameter: Image: This is image on which we want draw filled polygonEnd_Points: Points of polygon(for triangle 3 end p
3 min read
Draw a triangle with centroid using OpenCV
Prerequisite: Geometric shapes using OpenCV Given three vertices of a triangle, write a Python program to find the centroid of the triangle and then draw the triangle with its centroid on a black window using OpenCV. Examples: Input: (100, 200) (50, 50) (300, 100) Output: (150, 116) Libraries Needed: OpenCV Numpy Approach: Create a black window wit
2 min read
Automatic Document Scanner using OpenCV (OpenCV Document Scanner)
An automatic document scanner using OpenCV is a computer vision application that automatically detects and extracts documents from images. This type of scanner can be useful in various scenarios, such as digitizing paper documents, processing scanned documents, or automating document recognition tasks. In this article, we will see how we can build
6 min read
Practice Tags :
three90RightbarBannerImg