Contour detection OpenCV

Contour detection is a fundamental task in image processing and computer vision. It involves identifying the boundaries of objects within an image, which is useful for various applications such as object recognition, shape analysis, and image segmentation. OpenCV provides efficient algorithms and functions to perform contour detection and analysis.

Here are the steps to detect contours in your image:

Installing OpenCV

First of all, we need to install OpenCV. We can install it using the following command:

pip install opencv-python

Importing libraries

After installing OpenCV, we will start by importing the necessary libraries:

import cv2
import numpy as np

We import the cv2 for image processing and manipulation and numpy for array operations.

Preprocessing the image

Next, we need to load the image and preprocess it for better detection. We will convert the image to grayscale and apply Gaussian Blur to reduce noise in the image. Here is a sample code:

image = cv2.imread('image.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5, 5), 0)

We load an image using the cv2.imread() and convert it to grayscale using the cv2.cvtColor(). Then we apply Gaussian blur using cv2.GaussianBlur().

Detecting edges

In this step, we will use the Canny edge detection algorithm to detect the edges within the grayscale image. Edge detection highlights the significant transitions in pixel intensity, which often correspond to object boundaries. Here is the syntax of the Canny edge detection function:

edges = cv2.Canny(blur, threshold1, threshold2)

We can adjust threshold1 and threshold2 parameters to control the sensitivity of edge detection.

Finding contours

Contour detection involves identifying the boundaries of distinct objects within an image. Apply the cv2.findContours() function to identify contours in the edge-detected image. The function returns a list of contours and hierarchy information. Here is the syntax:

contours, _ = cv2.findContours(edges.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

We use the _ variable to discard hierarchy data. You can also adjust the second argument (cv2.RETR_EXTERNAL) to specify the contour retrieval mode.

Drawing contours

Create an empty image using the np.zeros_like() and draw detected contours using the cv2.drawContours().

contour_image = np.zeros_like(image)
cv2.drawContours(contour_image, contours, -1, (0, 255, 0), 2)

The third argument (-1) instructs the function to draw all contours. The (0, 255, 0) is RGB color code for drawing contours and 2 is the thickness of the contour we want to be drawn. You can adjust these parameters according to your preference.

Displaying results

Use the cv2.imshow() to display the original image and the contour image.

cv2.imshow('Original Image', image)
cv2.imshow('Contour Image', contour_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

The cv2.waitKey(0) function waits for a key press before closing windows, and cv2.destroyAllWindows() closes all windows.

Putting together

By following these steps, the complete code will turn out like this:

import cv2
import numpy as np
# Load an Image
image = cv2.imread('image.png')
# Preprocess the Image
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5, 5), 0)
# Edge Detection
edges = cv2.Canny(blur, 30, 150) # Adjust threshold values as needed
# Find Contours
contours, _ = cv2.findContours(edges.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Draw Contours
contour_image = np.zeros_like(image)
cv2.drawContours(contour_image, contours, -1, (0, 255, 0), 2)
# Saving Contours
cv2.imwrite('output/ContourImage.png', contour_image)
cv2.imwrite('output/Image.png', image)

Conclusion

Contour detection is a fundamental technique in computer vision that plays a crucial role in various image analysis tasks. OpenCV simplifies the process by offering efficient tools for contour detection and manipulation. Furthermore, you can explore more advanced techniques and combine contour detection with other computer vision algorithms to achieve even more sophisticated results in your projects.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved