Edge and contour detection with OpenCV

BeginnerImage processingImage processing

Goal: Converting an image to grayscale, detecting edges and counting shapes.

Python — example.py
import cv2, numpy as np

img = np.zeros((200, 300, 3), dtype=np.uint8)
cv2.rectangle(img, (20, 20), (90, 90), (255, 255, 255), -1)
cv2.circle(img, (160, 100), 40, (0, 255, 0), -1)
cv2.ellipse(img, (250, 150), (30, 20), 0, 0, 360, (0, 0, 255), -1)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 50, 150)
contours, _ = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
print("Edge pixels:", int((edges > 0).sum()))
print("Number of shapes:", len(contours))
print("Areas:", sorted(int(cv2.contourArea(c)) for c in contours))

Code explanation

We draw three shapes on a black image, then apply the Canny filter to detect edges and findContours to extract and count the outer contours. Remember that OpenCV stores channels in BGR order.

Requirements

Shell
pip install opencv-python-headless numpy

How to run

Save the code in a file example.py then run it:

Shell
python example.py

Output recorded during testing

Edge pixels: 712
Number of shapes: 3
Areas: [1884, 4900, 4912]

This example was actually run and tested on 21 November 2026 on a CPU — opencv-python-headless 5.1.0.95, numpy 2.5.5, python 3.13.18

Libraries used

Related examples