Table of contents
1.
Introduction
2.
A brief about OpenCV
3.
Contours in OpenCV
3.1.
How does OpenCV do it?
4.
Finding Contours
4.1.
What are the Requirements? 
4.2.
Syntax
4.3.
Return Value 
5.
Drawing Contours 
5.1.
Syntax
5.2.
Return Value 
6.
Time for an Example 
7.
Frequently Asked Questions
7.1.
What are the basic operations that are provided by OpenCV on Images/Video Data?
7.2.
What are Contours, and can they be used in OpenCV?
7.3.
What is Blob Detection?
8.
Conclusion
Last Updated: Mar 27, 2024
Easy

Contours in OpenCV

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

How many balls are there in this picture? 

balls

5 right? We can easily guess it by looking and counting how many objects there are. 

Imagine if we could teach computers to "see" and recognize those objects as we do. Well, that's where computer vision comes into play, and OpenCV (Open Source Computer Vision Library) is one of the most popular tools used for such tasks. Among the many powerful features it offers, "contours" stand out as a fundamental concept in understanding and analyzing shapes within images.

Contours in OpenCV

The scope of this article to give you a better understanding of finding and drawing Contours in Images using OpenCV Library. The contours are a useful tool for Shape analysisObject detection and Recognition.

Let us get started: 

A brief about OpenCV

OpenCV stands for open-source computer vision library. OpenCV provides the necessary libraries that are helpful in performing computer vision tasks. The libraries implemented in OpenCV are written in C++ and are very fast in processing.

openCV

Using the OpenCV Python library, we can extract image information like the text in the image, an object in the image, etc. Various programming languages like C++, Java, and Python support OpenCV.

Let us now understand what are Contours in OpenCV. 

Contours in OpenCV

Contours in OpenCV are like the outlines or borders of objects you can find in images. Imagine you have a picture with some shapes or objects, and you want to know their boundaries so you can recognize and analyze them better. Contours help you do just that!

In simple words, Contours are the curves that connect all the continuous points along the boundary of an object in an image. It's like drawing the outline of a shape without any gaps.

How does OpenCV do it?

OpenCV uses a technique called Edge detection to find the points where there are sudden changes in color or intensity in the image. These points are often the edges of the objects you want to find. 

connected dots

Once OpenCV detects the edge points, it connects them together to form the contour lines. Think of it as joining the dots to get the full outline of the object.

Now a question may arise, how do we find the contours in an image? 

Finding Contours

OpenCV provides a method known as findContours(), which is used to find the contour in the binary image. 

What are the Requirements? 

Before we start, it is important to note that to maintain the accuracy we use the binary images. Because, In OpenCV, finding the contour in the binary image is the same as finding white object from a black background. 

black and white demo

Converting an image to binary format is known as Thresholding

Let us see the syntax of findContours(): 

Syntax

cv2. findContours (thes(image), cv2.RETR_TREE (mode) , cv.CHAIN_APPROX_SIMPLE(method))  
You can also try this code with Online Python Compiler
Run Code


Let us breakdown the syntax: 

  • thes: The first argument is the input image thes from which we want to find contours. This image should be in a binary format as we have discussed above
     
  • cv2.RETR_TREE (mode): There might be a case where your objects have hierarchical relationships. 

For example, a circle might contain a small circle within.

The second argument specifies the contour retrieval mode. In this case, we use cv2.RETR_TREE, which means the function will retrieve all of the contours present in the image and reconstruct a full hierarchy of nested contours

Note: There are other retrieval modes as well which you can use based on your requirements. Examples: cv2.RETR_EXTERNAL, cv2.RETR_LIST and cv2.RETR_CCOMP
 

  • cv2.CHAIN_APPROX_SIMPLE (method): The third argument is the contour approximation method. 

In this case, cv2.CHAIN_APPROX_SIMPLE is used, which approximates and compresses the contour, reducing the number of points needed to represent the contour. 

It saves memory by retaining only the endpoints of horizontal, vertical, and diagonal segments of the contour. This approximation method is suitable when we don't need a very precise contour representation and want to work with simplified contours.

There are other methods as well: cv2.CHAIN_APPROX_NONE, cv2.CHAIN_APPROX_TC89_L1 and cv2.CHAIN_APPROX_TC89_KCOS based on your requirements

Return Value 

Below are the return values: 

  • contours: It is a Python list containing the detected contours
     
  • hierarchy: It is a numpy array containing the hierarchical relationships between contours (only applicable for certain retrieval modes)
     

Let us now see how we can draw the contours on the image. 

Drawing Contours 

To draw anything, you must know what to draw and where to draw. All you can think about drawing anything is the same as drawing the contours in OpenCV. You require some parameters that decide your outcome. 

There is an amazing method: drawContours() in OpenCV that helps in drawing the Contours in an image. 

Let us start with knowing its syntax: 

Syntax

output_image = cv2.drawContours(image, contours, contourIndex , color, thickness)
You can also try this code with Online Python Compiler
Run Code

Where, 

  • image : The input image on which you want to draw the contours. This should be a 3-channel (BGR) image, and the contours will be drawn on this image directly
     
  • contours: A Python list containing the contours to be drawn. You can manually decide the contours or you may use the findContours() method that will return the contours
     
  • contourIndex: The index of the contour within the contours list that you want to draw. Use -1 to draw all contours in the list
     
  • color: The color of the contours. It is a tuple of three integers representing the BGR color values, e.g., (0, 255, 0) for green
     
  • thickness: The thickness of the contour lines. Use a negative value or cv2.FILLED to fill the interior of the contours

Return Value 

The drawContours() returns a single value as the output_image that has Contours drawn on the detected objects. 

Let us now look at an example that utilizes both finding and drawing the contours using OpenCV: 

Time for an Example 

Code in Python

import cv2
import numpy as np
from google.colab import files
from IPython.display import Image, display

# Step 2: Upload the binary image
uploaded = files.upload()
image_path = next(iter(uploaded))

# Step 3: Read the binary image
binary_image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)

# Step 4: Find contours
contours, _ = cv2.findContours(binary_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# Step 5: Draw contours on a separate image (optional)
contour_image = np.copy(binary_image)
contour_image = cv2.cvtColor(contour_image, cv2.COLOR_GRAY2BGR)  # Convert to a 3-channel image
cv2.drawContours(contour_image, contours, -1, (0, 255, 0), 2)    # -1 means draw all contours in green color with 2px thickness

# Print the number of objects found
num_objects = len(contours)
print("Number of objects found:", num_objects)

# Display the original binary and contour images
display(Image(image_path))
display(Image(cv2.imencode('.png', contour_image)[1].tobytes()))
You can also try this code with Online Python Compiler
Run Code


Output 

Number of Objects found: 28

The sample Image used: 

The sample Image used:

Output:

Output

Frequently Asked Questions

What are the basic operations that are provided by OpenCV on Images/Video Data?

The OpenCV Python library provides various operations that can be performed on image/video data. 

The basic and widely used operations that are often used in OpenCV are:

  • Read and Save Images 
  • Resize Images 
  • Rotate Images 
  • Edge Detection of Images 
  • Image Smoothing

What are Contours, and can they be used in OpenCV?

A contour is a curve that joins the point in an image having the same intensity or color. Yes, OpenCV provides in-built methods for drawing the contours of an image. The methods used in OpenCV for contours are findCountours() and drawCountours().

What is Blob Detection?

It is the computer vision technique for clustering and locating a group of pixels with some common properties. The blob refers to this group of pixels having some common properties. Blob detection helps to find the image pixels different from the surroundings.

Conclusion

In this article, we learned about the concept of Contours in OpenCV. We looked at finding and drawing Contours on the Images for object detection. We have also discussed some frequently asked questions about the same. 

If you’re interested in learning more about OpenCv, here are some more related articles:


Check out The Interview Guide for Product Based Companies and some famous Interview Problems from Top Companies, like AmazonAdobeGoogle, etc., on CodeStudio.

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test SeriesInterview Bundles, and some Interview Experiences curated by top Industry Experts only on CodeStudio.

We hope you liked this article.

"Have fun coding!”

Live masterclass