Open In App

How to Detect Shapes in Images in Python using OpenCV?

Last Updated : 19 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

OpenCV is an open source library used mainly for processing images and videos to identify shapes, objects, text etc. It is mostly used with python. In this article we are going to see how to detect shapes in image. For this we need cv2.findContours() function of OpenCV, and also we are going to use cv2.drawContours() function to draw edges on images. A contour is an outline or a boundary of shape.

Here's the step-by-step approach to detecting shapes:

  • Import module
  • Import image
  • Convert it to grayscale image
  • Apply thresholding on image and then find out contours.
  • Run a loop in the range of contours and iterate through it.
  • In this loop draw a outline of shapes Using drawContours() and find out center point of shape.
  • Classify the detected shape on the basis of a number of contour points it has and put the detected shape name at the center point of shape.

Function Used

1. cv2.findContours(): Basically this method find outs all the boundary points of shape in image. Syntax:

cv2.findContours(src, contour_retrieval, contours_approximation)

Parameters:

  • src: input image n-dimensional (but for in our example we are going to use 2 dimensional image which is mostly preferred.)
  • contour_retrieval:
    • cv.RETR_EXTERNAL retrieves only the extreme outer contours
    • cv.RETR_LIST retrieves all of the contours without establishing any hierarchical relationships.
    • cv.RETR_TREE retrieves all of the contours and reconstructs a full hierarchy of nested contours.
  • contours_approximation:
    • cv.CHAIN_APPROX_NONE It will store all the boundary points.
    • cv.CHAIN_APPROX_SIMPLE It will store number of end points (eg.In case of rectangle it will store 4)

Return value: list of contour points

2. cv2.drawContours(): This method draws a contour. It can also draw a shape if you provide boundary points. Syntax:

cv.DrawContours(src, contour, contourIndex, colour, thickness)

Parameters:

  • src: n dimensional image
  • contour: contour points it can be list.
  • contourIndex:
    • -1:draw all the contours
  • To draw individual contour we can pass here index value
    • color: color values
    • thickness: size of outline

Input:

Program:

Python
import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread('shapes.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, threshold = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

contours, _ = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

# Process each contour
for i, contour in enumerate(contours):
    if i == 0:
        continue

    # Approximate contour shape
    approx = cv2.approxPolyDP(contour, 0.01 * cv2.arcLength(contour, True), True)

    # Draw contour
    cv2.drawContours(img, [contour], 0, (0, 0, 255), 5)

    # Find center
    M = cv2.moments(contour)
    if M['m00'] != 0:
        x = int(M['m10'] / M['m00'])
        y = int(M['m01'] / M['m00'])

    # Detect shape
    sides = len(approx)
    if sides == 3:
        label = 'Triangle'
    elif sides == 4:
        label = 'Quadrilateral'
    elif sides == 5:
        label = 'Pentagon'
    elif sides == 6:
        label = 'Hexagon'
    else:
        label = 'Circle'

    # Label the shape
    cv2.putText(img, label, (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2)
cv2.imshow('shapes', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Output

Explanation:

  • Read the image, convert it to grayscale and apply binary thresholding to prepare for shape detection.
  • cv2.findContours() detect shape boundaries in the thresholded image.
  • Loop through contours and use cv2.approxPolyDP() to simplify each shape to its polygon form.
  • Outline each detected shape on the original image using cv2.drawContours().
  • Find the shape’s center using cv2.moments(), identify the shape by its sides, and label it with cv2.putText().
  • Show the final image with cv2.imshow(), wait for a key, and close using cv2.destroyAllWindows().

Next Article
Article Tags :
Practice Tags :

Similar Reads