Vehicle Attribute Recognition Pipeline Tutorial¶
1. Introduction to Vehicle Attribute Recognition Pipeline¶
Vehicle attribute recognition is a crucial component in computer vision systems. Its primary task is to locate and label specific attributes of vehicles in images or videos, such as vehicle type, color, and license plate number. This task not only requires accurately detecting vehicles but also identifying detailed attribute information for each vehicle. The vehicle attribute recognition pipeline is an end-to-end serial system for locating and recognizing vehicle attributes, widely used in traffic management, intelligent parking, security surveillance, autonomous driving, and other fields. It significantly enhances system efficiency and intelligence levels, driving the development and innovation of related industries.
The vehicle attribute recognition pipeline includes a vehicle detection module and a vehicle attribute recognition module, with several models in each module. Which models to use can be selected based on the benchmark data below. If you prioritize model accuracy, choose models with higher accuracy; if you prioritize inference speed, choose models with faster inference; if you prioritize model storage size, choose models with smaller storage.
Vehicle Detection Module:
Model | Model Download Link | mAP 0.5:0.95 | GPU Inference Time (ms) | CPU Inference Time (ms) | Model Size (M) | Description |
---|---|---|---|---|---|---|
PP-YOLOE-S_vehicle | Inference Model/Trained Model | 61.3 | 15.4 | 178.4 | 28.79 | Vehicle detection model based on PP-YOLOE |
PP-YOLOE-L_vehicle | Inference Model/Trained Model | 63.9 | 32.6 | 775.6 | 196.02 |
Note: The above accuracy metrics are mAP(0.5:0.95) on the PPVehicle validation set. All GPU inference times are based on an NVIDIA Tesla T4 machine with FP32 precision. CPU inference speeds are based on an Intel(R) Xeon(R) Gold 5117 CPU @ 2.00GHz with 8 threads and FP32 precision.
Vehicle Attribute Recognition Module:
Model | Model Download Link | mA (%) | GPU Inference Time (ms) | CPU Inference Time (ms) | Model Size (M) | Description |
---|---|---|---|---|---|---|
PP-LCNet_x1_0_vehicle_attribute | Inference Model/Trained Model | 91.7 | 3.84845 | 9.23735 | 6.7 M | PP-LCNet_x1_0_vehicle_attribute is a lightweight vehicle attribute recognition model based on PP-LCNet. |
Note: The above accuracy metrics are mA on the VeRi dataset. GPU inference times are based on an NVIDIA Tesla T4 machine with FP32 precision. CPU inference speeds are based on an Intel(R) Xeon(R) Gold 5117 CPU @ 2.00GHz with 8 threads and FP32 precision.
2. Quick Start¶
The pre-trained models provided by PaddleX can quickly demonstrate results. You can experience the effects of the vehicle attribute recognition pipeline online or locally using command line or Python.
2.1 Online Experience¶
Not supported yet.
2.2 Local Experience¶
Before using the vehicle attribute recognition pipeline locally, ensure you have installed the PaddleX wheel package according to the PaddleX Local Installation Tutorial.
2.2.1 Experience via Command Line¶
You can quickly experience the vehicle attribute recognition pipeline with a single command. Use the test file and replace --input
with the local path for prediction.
--pipeline: The name of the pipeline, here it is the vehicle attribute recognition pipeline.
--input: The local path or URL of the input image to be processed.
--device: The index of the GPU to use (e.g., gpu:0 means using the first GPU, gpu:1,2 means using the second and third GPUs). You can also choose to use the CPU (--device cpu).
When executing the above Python script, the default vehicle attribute recognition pipeline configuration file is loaded. If you need a custom configuration file, you can run the following command to obtain it:
👉Click to Expand
paddlex --get_pipeline_config vehicle_attribute_recognition
After execution, the vehicle attribute recognition pipeline configuration file will be saved in the current directory. If you wish to specify a custom save location, you can run the following command (assuming the custom save location is ./my_path
):
paddlex --get_pipeline_config vehicle_attribute_recognition --save_path ./my_path
After obtaining the pipeline configuration file, you can replace --pipeline
with the saved path of the configuration file to make it effective. For example, if the saved path of the configuration file is ./vehicle_attribute_recognition.yaml
, just execute:
paddlex --pipeline ./vehicle_attribute_recognition.yaml --input vehicle_attribute_002.jpg --device gpu:0
Among them, parameters such as --model
and --device
do not need to be specified, and the parameters in the configuration file will be used. If parameters are still specified, the specified parameters will take precedence.
2.2.2 Integrating via Python Script¶
A few lines of code suffice for rapid inference on the production line, taking the vehicle attribute recognition pipeline as an example:
from paddlex import create_pipeline
pipeline = create_pipeline(pipeline="vehicle_attribute_recognition")
output = pipeline.predict("vehicle_attribute_002.jpg")
for res in output:
res.print() ## Print the structured output of the prediction
res.save_to_img("./output/") ## Save the visualized result image
res.save_to_json("./output/") ## Save the structured output of the prediction
In the above Python script, the following steps are executed:
(1) Instantiate the create_pipeline
to create a pipeline object: Specific parameter descriptions are as follows:
Parameter | Description | Parameter Type | Default Value |
---|---|---|---|
pipeline |
The name of the pipeline or the path to the pipeline configuration file. If it is the name of the pipeline, it must be a pipeline supported by PaddleX. | str |
None |
device |
The device for pipeline model inference. Supports: "gpu", "cpu". | str |
"gpu" |
use_hpip |
Whether to enable high-performance inference, only available when the pipeline supports high-performance inference. | bool |
False |
(2) Call the predict
method of the vehicle attribute recognition pipeline object for inference prediction: The predict
method parameter is x
, which is used to input data to be predicted, supporting multiple input methods. Specific examples are as follows:
Parameter Type | Description |
---|---|
Python Var | Supports directly passing in Python variables, such as image data represented by numpy.ndarray. |
str |
Supports passing in the file path of the data to be predicted, such as the local path of an image file: /root/data/img.jpg . |
str |
Supports passing in the URL of the data file to be predicted, such as the network URL of an image file: Example. |
str |
Supports passing in a local directory, which should contain data files to be predicted, such as the local path: /root/data/ . |
dict |
Supports passing in a dictionary type, where the key needs to correspond to the specific task, such as "img" for the vehicle attribute recognition task, and the value of the dictionary supports the above data types, for example: {"img": "/root/data1"} . |
list |
Supports passing in a list, where the elements of the list need to be the above data types, such as [numpy.ndarray, numpy.ndarray], ["/root/data/img1.jpg", "/root/data/img2.jpg"], ["/root/data1", "/root/data2"], [{"img": "/root/data1"}, {"img": "/root/data2/img.jpg"}] . |
(3) Obtain the prediction results by calling the predict
method: The predict
method is a generator
, so prediction results need to be obtained through iteration. The predict
method predicts data in batches, so the prediction results are in the form of a list representing a set of prediction results.
(4) Processing the Prediction Results: The prediction result for each sample is in dict
format, which supports printing or saving to a file. The supported file types for saving depend on the specific pipeline, such as:
Method | Description | Method Parameters |
---|---|---|
Print results to the terminal | - format_json : bool, whether to format the output content with json indentation, default is True;- indent : int, json formatting setting, only effective when format_json is True, default is 4;- ensure_ascii : bool, json formatting setting, only effective when format_json is True, default is False; |
|
save_to_json | Save results as a json file | - save_path : str, the path to save the file, when it is a directory, the saved file name is consistent with the input file type;- indent : int, json formatting setting, default is 4;- ensure_ascii : bool, json formatting setting, default is False; |
save_to_img | Save results as an image file | - save_path : str, the path to save the file, when it is a directory, the saved file name is consistent with the input file type; |
If you have obtained the configuration file, you can customize the configurations for the vehicle attribute recognition pipeline by simply modifying the pipeline
parameter in the create_pipeline
method to the path of your pipeline configuration file.
For example, if your configuration file is saved at ./my_path/vehicle_attribute_recognition.yaml
, you only need to execute:
from paddlex import create_pipeline
pipeline = create_pipeline(pipeline="./my_path/vehicle_attribute_recognition.yaml")
output = pipeline.predict("vehicle_attribute_002.jpg")
for res in output:
res.print() # Print the structured output of the prediction
res.save_to_img("./output/") # Save the visualized result image
res.save_to_json("./output/") # Save the structured output of the prediction
3. Development Integration/Deployment¶
If the vehicle attribute recognition pipeline meets your requirements for inference speed and accuracy, you can proceed directly with development integration/deployment.
If you need to directly apply the vehicle attribute recognition pipeline in your Python project, you can refer to the example code in 2.2.2 Python Script Integration.
Additionally, PaddleX provides three other deployment methods, detailed as follows:
🚀 High-Performance Inference: In actual production environments, many applications have stringent standards for the performance metrics of deployment strategies (especially response speed) to ensure efficient system operation and smooth user experience. To this end, PaddleX provides high-performance inference plugins aimed at deeply optimizing model inference and pre/post-processing to significantly speed up the end-to-end process. For detailed high-performance inference procedures, please refer to the PaddleX High-Performance Inference Guide.
☁️ Service-Oriented Deployment: Service-oriented deployment is a common deployment form in actual production environments. By encapsulating inference functionality as services, clients can access these services through network requests to obtain inference results. PaddleX supports users in achieving service-oriented deployment of pipelines at low cost. For detailed service-oriented deployment procedures, please refer to the PaddleX Service-Oriented Deployment Guide.
Below are the API reference and multi-language service invocation examples:
API Reference
For main operations provided by the service:
- The HTTP request method is POST.
- The request body and the response body are both JSON data (JSON objects).
- When the request is processed successfully, the response status code is
200
, and the response body properties are as follows:
Name | Type | Description |
---|---|---|
errorCode |
integer |
Error code. Fixed as 0 . |
errorMsg |
string |
Error description. Fixed as "Success" . |
The response body may also have a result
property of type object
, which stores the operation result information.
- When the request is not processed successfully, the response body properties are as follows:
Name | Type | Description |
---|---|---|
errorCode |
integer |
Error code. Same as the response status code. |
errorMsg |
string |
Error description. |
Main operations provided by the service are as follows:
infer
Get vehicle attribute recognition results.
POST /vehicle-attribute-recognition
- The request body properties are as follows:
Name | Type | Description | Required |
---|---|---|---|
image |
string |
The URL of an image file accessible by the service or the Base64 encoded result of the image file content. | Yes |
- When the request is processed successfully, the
result
of the response body has the following properties:
Name | Type | Description |
---|---|---|
vehicles |
array |
Information about the vehicle's location and attributes. |
image |
string |
The vehicle attribute recognition result image. The image is in JPEG format and encoded using Base64. |
Each element in vehicles
is an object
with the following properties:
Name | Type | Description |
---|---|---|
bbox |
array |
The location of the vehicle. The elements in the array are the x-coordinate of the top-left corner, the y-coordinate of the top-left corner, the x-coordinate of the bottom-right corner, and the y-coordinate of the bottom-right corner of the bounding box, respectively. |
attributes |
array |
The vehicle attributes. |
score |
number |
The detection score. |
Each element in attributes
is an object
with the following properties:
Name | Type | Description |
---|---|---|
label |
string |
The label of the attribute. |
score |
number |
The classification score. |
Multi-Language Service Invocation Examples
Python
import base64
import requests
API_URL = "http://localhost:8080/vehicle-attribute-recognition"
image_path = "./demo.jpg"
output_image_path = "./out.jpg"
with open(image_path, "rb") as file:
image_bytes = file.read()
image_data = base64.b64encode(image_bytes).decode("ascii")
payload = {"image": image_data}
response = requests.post(API_URL, json=payload)
assert response.status_code == 200
result = response.json()["result"]
with open(output_image_path, "wb") as file:
file.write(base64.b64decode(result["image"]))
print(f"Output image saved at {output_image_path}")
print("\nDetected vehicles:")
print(result["vehicles"])
📱 Edge Deployment: Edge deployment is a method where computing and data processing functions are placed on the user's device itself, allowing the device to process data directly without relying on remote servers. PaddleX supports deploying models on edge devices such as Android. For detailed edge deployment procedures, please refer to the PaddleX Edge Deployment Guide. You can choose an appropriate method to deploy your model pipeline based on your needs, and proceed with subsequent AI application integration.
4. Custom Development¶
If the default model weights provided by the vehicle attribute recognition pipeline do not meet your expectations in terms of accuracy or speed for your specific scenario, you can try to further fine-tune the existing models using your own data from specific domains or application scenarios to enhance the recognition performance of the vehicle attribute recognition pipeline in your context.
4.1 Model Fine-tuning¶
Since the vehicle attribute recognition pipeline includes both a vehicle attribute recognition module and a vehicle detection module, the suboptimal performance of the pipeline may stem from either module. You can analyze images with poor recognition results. If during the analysis, you find that many main targets are not detected, it may indicate deficiencies in the vehicle detection model. In this case, you need to refer to the Custom Development section in the Vehicle Detection Module Development Tutorial and use your private dataset to fine-tune the vehicle detection model. If the detected main attributes are incorrectly recognized, you need to refer to the Custom Development section in the Vehicle Attribute Recognition Module Development Tutorial and use your private dataset to fine-tune the vehicle attribute recognition model.
4.2 Model Application¶
After fine-tuning with your private dataset, you will obtain local model weight files.
To use the fine-tuned model weights, you only need to modify the pipeline configuration file by replacing the path to the default model weights with the local path to the fine-tuned model weights:
......
Pipeline:
det_model: PP-YOLOE-L_vehicle
cls_model: PP-LCNet_x1_0_vehicle_attribute # Can be modified to the local path of the fine-tuned model
device: "gpu"
batch_size: 1
......
5. Multi-hardware Support¶
PaddleX supports various mainstream hardware devices such as NVIDIA GPUs, Kunlun XPU, Ascend NPU, and Cambricon MLU. Simply modifying the --device
parameter allows seamless switching between different hardware.
For example, if you use an NVIDIA GPU for inference with the vehicle attribute recognition pipeline, the command is:
At this point, if you want to switch the hardware to Ascend NPU, you only need to change--device
to npu:0:
If you want to use the vehicle attribute recognition pipeline on more types of hardware, please refer to the PaddleX Multi-device Usage Guide.