In computer vision, contours are curves that join all continuous points along the boundary of objects with the same color or intensity. OpenCV provides functions to detect and draw contours, which are widely used in object detection, shape analysis, and recognition.
The function cv2.findContours() is used to retrieve contours from a binary image.
Contours should always be detected on thresholded or edge-detected images.
import cv2
# Read image in grayscale
img = cv2.imread("shapes.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Thresholding
_, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
# Find contours
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
print("Number of contours found:", len(contours))
Use cv2.drawContours() to draw contours on an image.
You can draw all contours or specific ones.
# Draw all contours in green
cv2.drawContours(img, contours, -1, (0, 255, 0), 2)
cv2.imshow("Contours", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.RETR_TREE, cv2.RETR_EXTERNAL): Defines contour retrieval.cv2.CHAIN_APPROX_SIMPLE, cv2.CHAIN_APPROX_NONE): Defines contour approximation.
✅ In this lesson, you learned how to detect and draw contours in OpenCV using
cv2.findContours() and cv2.drawContours().
Contours are powerful tools for shape analysis, object detection, and recognition.
👉 Next, we will explore shape detection using contours.
