Home  >  Article  >  Backend Development  >  How to use Python to perform shape recognition on pictures

How to use Python to perform shape recognition on pictures

王林
王林Original
2023-08-19 09:53:072772browse

How to use Python to perform shape recognition on pictures

How to use Python to perform shape recognition on pictures

With the rapid development of computer vision, people are paying more and more attention to using computer programs to automatically analyze and process images. Among them, the recognition of the shape of objects in images is an important technology. This article will introduce how to use the Python programming language and the OpenCV library to recognize shapes in images, with sample code.

Python is an easy-to-learn and easy-to-use programming language, while OpenCV is an open source library widely used in the field of computer vision. It provides a series of image processing and image recognition functions.

First, you need to install the Python and OpenCV libraries. You can install them in the Windows environment through the following command:

pip install opencv-python

Next, we divide the sample code into four steps: loading the image, Image processing, shape detection and shape recognition.

Step 1: Load the image

Before starting processing, we need to load an image to be processed. You can use OpenCV's imread() function to read the image file:

import cv2

# 加载图像
image = cv2.imread('image.jpg')

Step 2: Image processing

In order to better detect the shape in the image, We need to do some image processing operations. First, we will convert the color image into a grayscale image:

# 转换为灰度图像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

Then, we binarize the grayscale image and convert it into a black and white image:

# 二值化处理
ret, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

Step 3 :Shape detection

Next, we can use OpenCV’s findContours() function to detect all contours in the image. A contour is a curve formed by a series of consecutive points that describes the edge of an object.

# 查找图像中的轮廓
contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

Step 4: Shape Recognition

Finally, we can identify the shapes in the image through the detected contours. In this example, we match the detected contours with predefined shapes and determine the shape type.

for contour in contours:
    # 计算轮廓的周长
    perimeter = cv2.arcLength(contour, True)
    # 仅检测周长大于一定阈值的形状
    if perimeter > 50:
        # 进行多边形拟合
        approx = cv2.approxPolyDP(contour, 0.04 * perimeter, True)
        # 根据拟合出的多边形边数判断形状类型
        sides = len(approx)
        
        if sides == 3:
            shape = "三角形"
        elif sides == 4:
            shape = "四边形"
        elif sides == 5:
            shape = "五边形"
        else:
            shape = "其他"
            
        # 在图像上标记出形状
        cv2.drawContours(image, [approx], -1, (0, 255, 0), 2)
        cv2.putText(image, shape, (approx.ravel()[0], approx.ravel()[1]), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 2)

Finally, we can display the result image through the imshow() function, and the waitKey() function to wait for keyboard input to keep the window displayed:

# 显示结果图像
cv2.imshow("Shapes", image)
cv2.waitKey(0)

Summary

This article introduces how to use Python and the OpenCV library to perform shape recognition on images. Through the four steps of loading images, image processing, shape detection and shape recognition, we can realize the recognition of shapes in images by writing simple code. This method is very useful for developers engaged in computer vision and image processing, and can be applied in various scenarios, such as industrial automation, robot vision, intelligent monitoring and other fields.

Code example:

import cv2

# 加载图像
image = cv2.imread('image.jpg')

# 转换为灰度图像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# 二值化处理
ret, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

# 查找图像中的轮廓
contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

for contour in contours:
    perimeter = cv2.arcLength(contour, True)
    if perimeter > 50:
        approx = cv2.approxPolyDP(contour, 0.04 * perimeter, True)
        sides = len(approx)
        
        if sides == 3:
            shape = "三角形"
        elif sides == 4:
            shape = "四边形"
        elif sides == 5:
            shape = "五边形"
        else:
            shape = "其他"
            
        cv2.drawContours(image, [approx], -1, (0, 255, 0), 2)
        cv2.putText(image, shape, (approx.ravel()[0], approx.ravel()[1]), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 2)

cv2.imshow("Shapes", image)
cv2.waitKey(0)

I hope this article can help you further understand how to use Python and OpenCV for image shape recognition. By learning and exploring these technologies in depth, you can apply them in your own projects to achieve more features and applications.

The above is the detailed content of How to use Python to perform shape recognition on pictures. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn