OpenCV-Based Shape Detection and Labeling

  • Share this:

Code introduction


This function reads an image and uses OpenCV library features such as thresholding, morphological operations, and contour detection to identify shapes in the image, such as triangles, rectangles, squares, and circles. It then draws the shape names on the original image.


Technology Stack : OpenCV, NumPy

Code Type : Image processing

Code Difficulty : Intermediate


                
                    
import cv2
import numpy as np

def detect_shapes(image_path):
    # Load image
    image = cv2.imread(image_path)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    blurred = cv2.GaussianBlur(gray, (5, 5), 0)
    thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]

    # Find contours
    contours, _ = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # Loop through contours and find shapes
    shapes = []
    for contour in contours:
        perimeter = cv2.arcLength(contour, True)
        approx = cv2.approxPolyDP(contour, 0.04 * perimeter, True)

        # Classify shapes based on number of vertices
        if len(approx) == 3:
            shape = "Triangle"
        elif len(approx) == 4:
            (x, y, w, h) = cv2.boundingRect(approx)
            aspect_ratio = w / float(h)
            shape = "Rectangle" if 0.95 <= aspect_ratio <= 1.05 else "Square"
        elif len(approx) > 4:
            shape = "Circle"
        else:
            shape = "Unknown"

        # Draw shape name on the image
        cv2.drawContours(image, [contour], -1, (0, 255, 0), 2)
        cv2.putText(image, shape, (contour[0][0][0], contour[0][0][1]), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)

    # Display the image
    cv2.imshow("Shapes", image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

# Usage
detect_shapes("path_to_image.jpg")                
              
Tags: