Find and Draw Contours using OpenCV - Python

Last Updated : 4 Jul, 2025

Contours are edges or outline of a objects in a image and is used in image processing to identify shapes, detect objects or measure their size. We use OpenCV's findContours() function that works best for binary images.

There are three important arguments of this function:

  • Source Image: This is the image from which we want to find the contours.
  • Contour Retrieval Mode: This determines how contours are retrieved.
  • Contour Approximation Method: This decides how much detail to keep when storing the contours.

The function gives us three outputs:

  • Image: The image with contours found in it.
  • Contours: A list of contours. Each contour is made up of the (x, y) coordinates that outline a shape in the image.
  • Hierarchy: This gives extra information about the contours like which ones are inside others.

Lets implement it in python.

1. Importing Necessary Libraries

First, we need to import libraries like numpy and OpenCV that help us process image.

Python
import cv2
import numpy as np

2. Reading Image

Now, we load the image we want to work with. We use cv2.imread() to read the image and cv2.waitKey(0) pauses the program until you press a key.

Python
image = cv2.imread('./image.png')
cv2.waitKey(0)

You can download the image we used in the code from here.

3. Converting Image to GrayScale

To make it easier to process the image, we convert it from color (BGR) to grayscale. Grayscale images are simpler to work with for tasks like detecting edges.

Python
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

4. Edge Detection Using Canny

Next, we apply Canny edge detection which highlights the edges of objects in the image. This helps us find boundaries of shapes and objects easily.

Python
edged = cv2.Canny(gray, 30, 200)
cv2.waitKey(0)

5. Finding Contours

We then find the contours, which are the boundaries of objects in the image. This helps us detect the shapes in the image. We focus on the external contours.

Python
contours, hierarchy = cv2.findContours(edged,
                      cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

6. Displaying Canny Edges After Contouring

Now, we show the edges that we found using Canny edge detection. This gives us a visual idea of where the edges of the objects are.

Python
cv2.imshow('Canny Edges After Contouring', edged)
cv2.waitKey(0)

Output: