Home  >  Article  >  Backend Development  >  How to use Python to trace shapes on pictures

How to use Python to trace shapes on pictures

PHPz
PHPzOriginal
2023-08-18 19:57:23932browse

How to use Python to trace shapes on pictures

How to use Python to track shapes in pictures

Introduction:
Image processing is an important part of the field of computer vision, and tracking specific shapes in images Tracking is one of the common tasks. This article will introduce how to use Python and the OpenCV library to track shapes in pictures, and provide corresponding code examples.

1. Preparation:
Before starting to write code, we need to install the Python and OpenCV libraries, and prepare a picture containing the target shape as input. First, make sure you have Python installed. You can download and install the version suitable for your operating system from the official Python website. Next, we need to install the OpenCV library using the pip command. Open the terminal (or command line) and enter the following command to install OpenCV:

pip install opencv-python

2. Import the library and read the image:
Before formally writing the code, we First you need to import the corresponding library. Python provides the import statement to import the libraries you need to use. In this task, we need to import the cv2 library (which is the Python interface to the OpenCV library). In addition, we also need to import the numpy library to support array operations. Here is the code to import the required libraries:

import cv2
import numpy as np

Next, we need to read the image and convert it to a grayscale image. Grayscale images are easier to process and can reduce the amount of calculations. Considering that future work may modify the original image, we can use a copy to save the grayscale image. Here is the code to read the image and convert it to grayscale:

image = cv2.imread("input.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

3. Shape detection and tracking:
Before performing shape tracking, we need to perform shape detection first. OpenCV provides a function cv2.findContours() for finding contours in images. This function accepts a binarized image as input and returns a list of all contours in the image. Here is a code example for shape detection:

ret, thresh = cv2.threshold(gray, 127, 255, 0)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2. CHAIN_APPROX_SIMPLE)

Next, we can use the cv2.approxPolyDP() function to approximate the contour and make it smoother. The degree of approximation can be changed by adjusting the value of epsilon, the second parameter of this function. Small epsilon values ​​will produce more accurate approximations, while large epsilon values ​​will produce rougher approximations. Here is a code example for shape approximation:

epsilon = 0.04 * cv2.arcLength(contour, True)
approx = cv2.approxPolyDP(contour, epsilon, True)

Finally, We can use the cv2.drawContours() function to draw the detected shapes onto the original image. The following is a code example for drawing contours:

cv2.drawContours(image, [approx], 0, (0, 255, 0), 2)

Code explanation:
Above code , ret is a Boolean value used to indicate whether the thresholding operation was successful. thresh is a thresholded image used for contour detection. contours is a list containing all detected contours. hierarchy is the hierarchical information of the outline. epsilon is a parameter used to approximate the contour. approx is the approximated contour. Finally, the cv2.drawContours() function is used to draw contours.

4. Display and results:
After completing the shape tracking, we can display the result image and save it as a new file. The following is a code example for displaying and saving results:

cv2.imshow("Result", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

cv2 .imwrite("output.jpg", image)

Code explanation:
In the above code, the cv2.imshow() function is used to display the result image. cv2.waitKey(0) is used to wait for the user to press any key before closing the image window. The cv2.destroyAllWindows() function is used to close all open windows. Finally, the cv2.imwrite() function is used to save the resulting image.

Summary:
This article introduces how to use Python and the OpenCV library to track shapes in pictures. We first learned about the preparation, then imported the required libraries and read the images. Next, we performed shape detection and tracking to track the target shape by approximating contours and drawing contours. Finally, we display the resulting image and save the tracking results.

Here is the complete code example:

import cv2
import numpy as np

image = cv2.imread("input.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

ret, thresh = cv2.threshold(gray, 127, 255, 0)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

for contour in contours:
    epsilon = 0.04 * cv2.arcLength(contour, True)
    approx = cv2.approxPolyDP(contour, epsilon, True)
    cv2.drawContours(image, [approx], 0, (0, 255, 0), 2)

cv2.imshow("Result", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

cv2.imwrite("output.jpg", image)

I hope this article can help readers understand how to use Python and the OpenCV library to track shapes in pictures. By learning and applying the code examples provided in this article, readers can easily perform shape tracking tasks and play a role in image processing applications.

The above is the detailed content of How to use Python to trace shapes 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