Last modified: Jan 15, 2025 By Alexander Williams

Python OpenCV cv2.drawContours() Guide

In this guide, we will explore how to use the cv2.drawContours() function in Python OpenCV. This function is essential for drawing contours on images, which is a common task in image processing and computer vision.

What is cv2.drawContours()?

The cv2.drawContours() function is used to draw contours on an image. Contours are the boundaries of objects in an image. They are often used in object detection, shape analysis, and image segmentation.

Before using cv2.drawContours(), you need to find contours using the cv2.findContours() function. This function returns a list of contours that can be passed to cv2.drawContours().

How to Use cv2.drawContours()

Here is a step-by-step guide on how to use cv2.drawContours():


import cv2
import numpy as np

# Load an image
image = cv2.imread('image.jpg')

# Convert the image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Apply Gaussian blur to reduce noise
blurred = cv2.GaussianBlur(gray, (5, 5), 0)

# Use Canny edge detection to find edges
edges = cv2.Canny(blurred, 50, 150)

# Find contours from the edges
contours, _ = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

# Draw contours on the original image
cv2.drawContours(image, contours, -1, (0, 255, 0), 2)

# Display the result
cv2.imshow('Contours', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

In this example, we first load an image and convert it to grayscale. We then apply Gaussian blur to reduce noise and use Canny edge detection to find edges. Finally, we find contours using cv2.findContours() and draw them on the original image using cv2.drawContours().

Parameters of cv2.drawContours()

The cv2.drawContours() function has several parameters:

  • image: The image on which to draw the contours.
  • contours: A list of contours obtained from cv2.findContours().
  • contourIdx: The index of the contour to draw. Use -1 to draw all contours.
  • color: The color of the contours (BGR format).
  • thickness: The thickness of the contour lines. Use -1 to fill the contour.

Example Output

Here is an example output of the above code:


# Output: An image with contours drawn around objects

The output will be an image with green contours drawn around the detected objects. The thickness of the contours is set to 2, and the color is green (0, 255, 0).

Conclusion

The cv2.drawContours() function is a powerful tool in OpenCV for drawing contours on images. It is often used in conjunction with cv2.findContours() to detect and highlight objects in an image. By understanding how to use this function, you can perform advanced image processing tasks such as object detection and shape analysis.

For more information on related functions, check out our guides on cv2.Canny() and cv2.GaussianBlur().