SoFunction
Updated on 2025-03-10

Python OpenCV implements image shape detection

Image shape detection is a key technology in the field of computer vision, and is widely used in many fields such as industrial automation, robot vision, and medical image processing. This article will introduce in detail how to use Python and OpenCV libraries to achieve image shape detection. Through concise and clear steps and code examples, you can quickly master this skill.

1. Environmental preparation

Before you begin, make sure that your computer has Python and OpenCV libraries installed. You can install the OpenCV library by:

pip install opencv-python

At the same time, make sure you are able to write and run Python code and be familiar with basic image processing concepts.

2. Read and preprocess images

Read the image

Use OpenCV's() function to read the image file. For example, read an image with different shapes:

import cv2
 
# Read the imageimg = ('')

Grayscale

Convert color images to grayscale images to simplify subsequent processing. Use the() function:

# Convert to grayscale imagegray_img = (img, cv2.COLOR_BGR2GRAY)

Filtering and denoising

Use Gaussian blur to remove noise in the image. Gaussian blur is a commonly used image processing technology that can smooth the image and reduce noise interference. Use the() function:

# Gaussian blurblurred_img = (gray_img, (5, 5), 0)

3. Edge detection

Edge detection is an important step in shape detection, which can help us find the outline in the image. Using the Canny edge detection algorithm, this algorithm is a commonly used edge detection algorithm with good edge detection effect. Use the() function:

# Canny edge detectionedges = (blurred_img, 50, 150)

4. Find out the outline

Use the() function to find outlines in the image. This function returns an approximation method of the contour point set, hierarchy, and contour. We mainly focus on the contour point set:

# Find out the outlinecontours, hierarchy = (edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

5. Draw the outline

To visualize the detected outline, we can use the() function to draw the outline on the original image:

# Draw outlinescontour_img = ()
(contour_img, contours, -1, (0, 255, 0), 2)

6. Shape classification

According to the number of vertices, area, perimeter and other characteristics of the outline, we can classify the detected shapes. Here is a simple example of shape classification:

for contour in contours:
    # Calculate the contour area    area = (contour)
    
    # Calculate the perimeter of the outline    perimeter = (contour, True)
    
    # Approximate contours are polygons    epsilon = 0.02 * perimeter
    approx = (contour, epsilon, True)
    
    # Get the number of outline vertices    num_vertices = len(approx)
    
    #Judge shape based on the number of vertices    shape = 'Unknown'
    if num_vertices == 3:
        shape = 'Triangle'
    elif num_vertices == 4:
        # Determine whether it is a square or rectangle        x, y, w, h = (approx)
        aspect_ratio = w / float(h)
        if 0.95 < aspect_ratio < 1.05:
            shape = 'Square'
        else:
            shape = 'Rectangle'
    elif num_vertices == 5:
        shape = 'Pentagon'
    elif num_vertices == 6:
        shape = 'Hexagon'
    else:
        # For shapes with a number of vertices greater than 6, they can be further classified according to characteristics such as perimeter and area ratio.        # For example, a circle can be judged by its perimeter and area ratio being close to a certain threshold.        if 4 * 3.14 * (area / 3.14) ** 0.5 / perimeter > 0.8 and 4 * 3.14 * (area / 3.14) ** 0.5 / perimeter < 1.2:
            shape = 'Circle'
        else:
            shape = 'Other Polygon'
    
    # Mark the shape name and number of vertices on the image    M = (contour)
    if M['m00'] != 0:
        cX = int(M['m10'] / M['m00'])
        cY = int(M['m01'] / M['m00'])
    else:
        cX, cY = 0, 0
    
    (contour_img, f'{shape} ({num_vertices} vertices)', (cX - 50, cY - 50), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
    (contour_img, [approx], -1, (0, 0, 255), 2)

7. Display the results

Finally, use the() function to display the processed image:

# Show result image('Shape Detection', contour_img)
(0)
()

8. Complete code example

Here is a complete code example that brings the above steps together:

import cv2
 
# Read the imageimg = ('')
 
# Convert to grayscale imagegray_img = (img, cv2.COLOR_BGR2GRAY)
 
# Gaussian blurblurred_img = (gray_img, (5, 5), 0)
 
# Canny edge detectionedges = (blurred_img, 50, 150)
 
# Find out the outlinecontours, hierarchy = (edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
 
# Draw outlines and classify shapes 
 
contour_img = ()
for contour in contours:
    # Calculate the contour area    area = (contour)
    
    # Calculate the perimeter of the outline    perimeter = (contour, True)
    
    # Approximate contours are polygons    epsilon = 0.02 * perimeter
    approx = (contour, epsilon, True)
    
    # Get the number of outline vertices    num_vertices = len(approx)
    
    #Judge shape based on the number of vertices    shape = 'Unknown'
    if num_vertices == 3:
        shape = 'Triangle'
    elif num_vertices == 4:
        # Determine whether it is a square or rectangle        x, y, w, h = (approx)
        aspect_ratio = w / float(h)
        if 0.95 < aspect_ratio < 1.05:
            shape = 'Square'
        else:
            shape = 'Rectangle'
    elif num_vertices == 5:
        shape = 'Pentagon'
    elif num_vertices == 6:
        shape = 'Hexagon'
    else:
        # For shapes with a number of vertices greater than 6, they can be further classified according to characteristics such as perimeter and area ratio.        # For example, a circle can be judged by its perimeter and area ratio being close to a certain threshold.        if 4 * 3.14 * (area / 3.14) ** 0.5 / perimeter > 0.8 and 4 * 3.14 * (area / 3.14) ** 0.5 / perimeter < 1.2:
            shape = 'Circle'
        else:
            shape = 'Other Polygon'
    
    # Mark the shape name and number of vertices on the image    M = (contour)
    if M['m00'] != 0:
        cX = int(M['m10'] / M['m00'])
        cY = int(M['m01'] / M['m00'])
    else:
        cX, cY = 0, 0
    
    # Draw the shape name and number of vertices    (contour_img, f'{shape} ({num_vertices} vertices)', (cX - 50, cY - 50), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
    
    # Draw outlines (approximate polygons)    (contour_img, [approx], -1, (0, 0, 255), 2)
 
# Show result image('Shape Detection', contour_img)
(0)
()

9. Summary

This article describes how to use Python and OpenCV libraries to implement image shape detection. Through environmental preparation, image preprocessing, edge detection, contour search, outline drawing and shape classification, the complete image shape detection process is demonstrated. Using Gaussian blur, Canny edge detection and contour approximation technologies, effective detection and classification of different shapes in the image are achieved. Through sample code, readers can quickly master the basic methods and techniques of image shape detection, providing strong support for practical applications in the fields of industrial automation, robot vision, etc.

This is the article about Python OpenCV implementing image shape detection. For more related Python OpenCV shape detection content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!