Last Updated : 04 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:
The function gives us three outputs:
Lets implement it in python.
1. Importing Necessary LibrariesFirst, 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)
3. Converting Image to GrayScaleYou can download the image we used in the code from here.
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:
Canny Edges After Contouring 7. Printing Number of Contours Found Python
print("Number of Contours Found = " + str(len(contours)))
Output:
8. Drawing Contours on the Original ImageNumber of Contours Found = 3
Finally, we draw the contours on the original image to visualize the shapes we found. The contours are drawn in green, and we display the updated image.
Python
cv2.drawContours(image, contours, -1, (0, 255, 0), 3)
cv2.imshow('Contours', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Output:
Contours on the Original ImageWith the following steps we can find contours in a image that can be used for image segmentation and object detection.
Related articles:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4