General Image Multi-Label Classification Pipeline Tutorial¶
1. Introduction to the General Image Multi-Label Classification Pipeline¶
Image multi-label classification is a technique that assigns multiple relevant categories to a single image simultaneously, widely used in image annotation, content recommendation, and social media analysis. It can identify multiple objects or features present in an image, for example, an image containing both "dog" and "outdoor" labels. By leveraging deep learning models, image multi-label classification automatically extracts image features and performs accurate classification, providing users with more comprehensive information. This technology is of great significance in applications such as intelligent search engines and automatic content generation.This pipeline also offers a flexible service-oriented deployment approach, supporting the use of multiple programming languages on various hardware platforms. Moreover, this pipeline provides the capability for secondary development. You can train and optimize models on your own dataset based on this pipeline, and the trained models can be seamlessly integrated.
The General Image Multi-Label Classification Pipeline includes a module for image multi-label classification. If you prioritize model accuracy, choose a model with higher accuracy. If you prioritize inference speed, choose a model with faster inference. If you prioritize model storage size, choose a model with a smaller storage size.
Model Name | Model Download Link | mAP (%) | Model Storage Size (M) |
---|---|---|---|
CLIP_vit_base_patch16_448_ML | Inference Model/Trained Model | 89.15 | - |
PP-HGNetV2-B0_ML | Inference Model/Trained Model | 80.98 | 39.6 |
PP-HGNetV2-B4_ML | Inference Model/Trained Model | 87.96 | 88.5 |
PP-HGNetV2-B6_ML | Inference Model/Trained Model | 91.25 | 286.5 |
PP-LCNet_x1_0_ML | Inference Model/Trained Model | 77.96 | 29.4 |
ResNet50_ML | Inference Model/Trained Model | 83.50 | 108.9 |
Test Environment Description:
- Performance Test Environment
- Test Dataset: multi-label classification task on COCO2017.
-
Hardware Configuration:
- GPU: NVIDIA Tesla T4
- CPU: Intel Xeon Gold 6271C @ 2.60GHz
- Other Environments: Ubuntu 20.04 / cuDNN 8.6 / TensorRT 8.5.2.2
-
Inference Mode Description
Mode | GPU Configuration | CPU Configuration | Acceleration Technology Combination |
---|---|---|---|
Regular Mode | FP32 Precision / No TRT Acceleration | FP32 Precision / 8 Threads | PaddleInference |
High-Performance Mode | Optimal combination of pre-selected precision types and acceleration strategies | FP32 Precision / 8 Threads | Pre-selected optimal backend (Paddle/OpenVINO/TRT, etc.) |
2. Quick Start¶
All model pipelines provided by PaddleX can be quickly experienced. You can experience the effect of the image multi-label classification pipeline on the community platform, or you can use the command line or Python locally to experience the effect of the image multi-label classification pipeline.
2.1 Online Experience¶
You can experience the image multi-label classification pipeline online by recognizing the demo images provided by the official platform, for example:
If you are satisfied with the performance of the pipeline, you can directly integrate and deploy it. You can choose to download the deployment package from the cloud, or refer to the methods in Section 2.2 Local Experience for local deployment. If you are not satisfied with the effect, you can fine-tune the models in the pipeline using your private data. If you have local hardware resources for training, you can start training directly on your local machine; if not, the Star River Zero-Code platform provides a one-click training service. You don't need to write any code—just upload your data and start the training task with one click.
2.2 Local Experience¶
❗ Before using the image multi-label classification pipeline locally, please ensure that you have completed the installation of the PaddleX wheel package according to the PaddleX Installation Guide.
2.2.1 Command Line Experience¶
You can quickly experience the image multi-label classification pipeline effect with a single command. Use the test file, and replace --input
with the local path for prediction.
paddlex --pipeline image_multilabel_classification --input general_image_classification_001.jpg --device gpu:0
The relevant parameter descriptions can be referred to in the parameter explanations in 2.2.2 Python Script Integration.
After running, the result will be printed to the terminal as follows:
{'res': {'input_path': 'test_imgs/general_image_classification_001.jpg', 'page_index': None, 'class_ids': array([21]), 'scores': array([0.99962]), 'label_names': ['bear']}}
The explanation of the result parameters can be referred to in 2.2.2 Python Script Integration.
The visualization results are saved under save_path
, and the visualization result is as follows:
2.2.2 Python Script Integration¶
- The above command line is for quickly experiencing and viewing the effect. Generally, in a project, it is often necessary to integrate through code. You can complete the quick inference of the pipeline with just a few lines of code. The inference code is as follows:
from paddlex import create_pipeline
pipeline = create_pipeline(pipeline="image_multilabel_classification")
output = pipeline.predict("general_image_classification_001.jpg")
for res in output:
res.print()
res.save_to_img("./output/")
res.save_to_json("./output/")
The result obtained is the same as the command line method.
In the above Python script, the following steps are performed:
(1) Instantiate the general image multi-label classification pipeline object through create_pipeline()
, with specific parameter descriptions as follows:
Parameter | Description | Type | Default |
---|---|---|---|
pipeline |
Pipeline name or pipeline configuration file path. If it is a pipeline name, it must be a pipeline supported by PaddleX. | str |
None |
config |
Specific configuration information for the pipeline (if set simultaneously with pipeline , it has higher priority than pipeline , and the pipeline name must be consistent with pipeline ). |
dict[str, Any] |
None |
device |
Pipeline inference device. Supports specifying the specific GPU card number, such as "gpu:0", other hardware specific card numbers, such as "npu:0", CPU such as "cpu". | str |
gpu:0 |
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 general image multi-label classification pipeline object for inference prediction. This method will return a generator
. The parameters of the predict()
method and their descriptions are as follows:
Parameter | Description | Type | Options | Default |
---|---|---|---|---|
input |
Data to be predicted, supports multiple input types, required | Python Var|str|list |
|
None |
device |
Pipeline inference device | str|None |
|
None |
threshold |
Multi-label classification threshold | float | dict | list | None |
|
0.5 |
3) Process the prediction results. The prediction result for each sample is of type dict
and supports operations such as printing, saving as an image, and saving as a json
file:
Method | Description | Parameter | Type | Parameter Description | Default Value |
---|---|---|---|---|---|
print() |
Print the result to the terminal | format_json |
bool |
Whether to format the output content using JSON indentation |
True |
indent |
int |
Specify the indentation level to beautify the output JSON data, making it more readable. Effective only when format_json is True |
4 | ||
ensure_ascii |
bool |
Control whether non-ASCII characters are escaped to Unicode . When set to True , all non-ASCII characters will be escaped; False retains the original characters. Effective only when format_json is True |
False |
||
save_to_json() |
Save the result as a json file | save_path |
str |
Path to save the file. If it is a directory, the saved file name will be consistent with the input file type | None |
indent |
int |
Specify the indentation level to beautify the output JSON data, making it more readable. Effective only when format_json is True |
4 | ||
ensure_ascii |
bool |
Control whether non-ASCII characters are escaped to Unicode . When set to True , all non-ASCII characters will be escaped; False retains the original characters. Effective only when format_json is True |
False |
||
save_to_img() |
Save the result as an image file | save_path |
str |
Path to save the file. Supports directory or file path | None |
-
Calling the
print()
method will print the result to the terminal. The content printed to the terminal is explained as follows:input_path
:(str)
Input path of the image to be predicted.page_index
:(Union[int, None])
If the input is a PDF file, it indicates the current page number of the PDF; otherwise, it isNone
.class_ids
:(List[numpy.ndarray])
Indicates the class IDs of the prediction results.scores
:(List[numpy.ndarray])
Indicates the confidence scores of the prediction results.label_names
:(List[str])
Indicates the class names of the prediction results.
-
Calling the
save_to_json()
method will save the above content to the specifiedsave_path
. If specified as a directory, the saved path will besave_path/{your_img_basename}.json
. If specified as a file, it will be saved directly to that file. Since json files do not support saving numpy arrays,numpy.array
types will be converted to lists. -
Calling the
save_to_img()
method will save the visualization result to the specifiedsave_path
. If specified as a directory, the saved path will besave_path/{your_img_basename}_res.{your_img_extension}
. If specified as a file, it will be saved directly to that file. (The pipeline usually contains many result images, it is not recommended to specify a specific file path directly, otherwise multiple images will be overwritten, leaving only the last image) -
In addition, you can also obtain the visualized image and prediction results through attributes, as follows:
Attribute | Description |
---|---|
json |
Get the prediction result in json format |
img |
Get the visualized image in dict format |
- The prediction result obtained by the
json
attribute is a dictionary type, and the content is consistent with the content saved by calling thesave_to_json()
method. - The prediction result returned by the
img
attribute is a dictionary type. The key isres
and the corresponding value is anImage.Image
object: an object used to display the visualized image of the attribute recognition result.
In addition, you can obtain the general image multi-label classification pipeline configuration file and load the configuration file for prediction. You can execute the following command to save the result in my_path
:
If you have obtained the configuration file, you can customize the settings for the image multi-label classification pipeline by simply modifying the pipeline
parameter value in the create_pipeline
method to the path of the configuration file. An example is as follows:
from paddlex import create_pipeline
pipeline = create_pipeline(pipeline="./my_path/image_multilabel_classification.yaml")
output = pipeline.predict(
input="./general_image_classification_001.jpg",
)
for res in output:
res.print()
res.save_to_img("./output/")
res.save_to_json("./output/")
Note: The parameters in the configuration file are the initialization parameters of the pipeline. If you want to change the initialization parameters of the general image multi-label classification pipeline, you can directly modify the parameters in the configuration file and load the configuration file for prediction. At the same time, CLI prediction also supports passing in the configuration file, and you can specify the path of the configuration file with --pipeline
.
3. Development Integration/Deployment¶
If the pipeline meets your requirements for inference speed and accuracy, you can proceed with development integration/deployment directly.
If you need to apply the pipeline directly in your Python project, you can refer to the example code in 2.2 Python Script Integration.
In addition, PaddleX also 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. Therefore, PaddleX provides a high-performance inference plugin, aiming to deeply optimize the performance of model inference and pre/post-processing, achieving significant acceleration of the end-to-end process. For detailed high-performance inference processes, please refer to PaddleX High-Performance Inference Guide.
☁️ Service Deployment: Service deployment is a common form of deployment in actual production environments. By encapsulating inference functions as services, clients can access these services through network requests to obtain inference results. PaddleX supports multiple pipeline service deployment solutions. For detailed pipeline service deployment processes, please refer to PaddleX Service Deployment Guide.
Below is the API reference for basic service deployment and multi-language service call examples:
API Reference
For the main operations provided by the service:
- The HTTP request method is POST.
- Both the request body and response body are JSON data (JSON objects).
- When the request is processed successfully, the response status code is
200
, and the response body has the following properties:
Name | Type | Description |
---|---|---|
logId |
string |
The UUID of the request. |
errorCode |
integer |
Error code. Fixed at 0 . |
errorMsg |
string |
Error description. Fixed at "Success" . |
result |
object |
Operation result. |
- When the request is not processed successfully, the response body has the following properties:
Name | Type | Description |
---|---|---|
logId |
string |
The UUID of the request. |
errorCode |
integer |
Error code. Same as the response status code. |
errorMsg |
string |
Error description. |
The main operations provided by the service are as follows:
infer
Perform image classification.
POST /multilabel-image-classification
- The properties of the request body are as follows:
Name | Type | Description | Required |
---|---|---|---|
image |
string |
The URL of an image file accessible by the server or the Base64-encoded content of the image file. | Yes |
threshold |
number | array | object | null |
Refer to the threshold parameter description in the pipeline predict method. |
No |
- When the request is processed successfully, the
result
in the response body has the following properties:
Name | Type | Description |
---|---|---|
categories |
array |
Image category information. |
image |
string | null |
The image classification result. The image is in JPEG format and is encoded in Base64. |
Each element in categories
is an object
with the following properties:
Name | Type | Description |
---|---|---|
id |
integer |
Category ID. |
name |
string |
Category name. |
score |
number |
Category score. |
An example of result
is as follows:
{
"categories": [
{
"id": 5,
"name": "Rabbit",
"score": 0.93
}
],
"image": "xxxxxx"
}
Multi-Language Service Call Examples
Python
import base64
import requests
API_URL = "http://localhost:8080/multilabel-image-classification" # Service URL
image_path = "./demo.jpg"
output_image_path = "./out.jpg"
# Encode the local image in Base64
with open(image_path, "rb") as file:
image_bytes = file.read()
image_data = base64.b64encode(image_bytes).decode("ascii")
payload = {"image": image_data} # Base64-encoded file content or image URL
# Call the API
response = requests.post(API_URL, json=payload)
# Process the returned data
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("\nCategories:")
print(result["categories"])
C++
#include <iostream>
#include "cpp-httplib/httplib.h" // https://github.com/Huiyicc/cpp-httplib
#include "nlohmann/json.hpp" // https://github.com/nlohmann/json
#include "base64.hpp" // https://github.com/tobiaslocker/base64
int main() {
httplib::Client client("localhost:8080");
const std::string imagePath = "./demo.jpg";
const std::string outputImagePath = "./out.jpg";
httplib::Headers headers = {
{"Content-Type", "application/json"}
};
// Encode the local image in Base64
std::ifstream file(imagePath, std::ios::binary | std::ios::ate);
std::streamsize size = file.tellg();
file.seekg(0, std::ios::beg);
std::vector<char> buffer(size);
if (!file.read(buffer.data(), size)) {
std::cerr << "Error reading file." << std::endl;
return 1;
}
std::string bufferStr(reinterpret_cast<const char*>(buffer.data()), buffer.size());
std::string encodedImage = base64::to_base64(bufferStr);
nlohmann::json jsonObj;
jsonObj["image"] = encodedImage;
std::string body = jsonObj.dump();
// Call the API
auto response = client.Post("/multilabel-image-classification", headers, body, "application/json");
// Process the returned data
if (response && response->status == 200) {
nlohmann::json jsonResponse = nlohmann::json::parse(response->body);
auto result = jsonResponse["result"];
encodedImage = result["image"];
std::string decodedString = base64::from_base64(encodedImage);
std::vector<unsigned char> decodedImage(decodedString.begin(), decodedString.end());
std::ofstream outputImage(outputImagePath, std::ios::binary | std::ios::out);
if (outputImage.is_open()) {
outputImage.write(reinterpret_cast<char*>(decodedImage.data()), decodedImage.size());
outputImage.close();
std::cout << "Output image saved at " << outputImagePath << std::endl;
} else {
std::cerr << "Unable to open file for writing: " << outputImagePath << std::endl;
}
auto categories = result["categories"];
std::cout << "\nCategories:" << std::endl;
for (const auto& category : categories) {
std::cout << category << std::endl;
}
} else {
std::cout << "Failed to send HTTP request." << std::endl;
return 1;
}
return 0;
}
Java
import okhttp3.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;
public class Main {
public static void main(String[] args) throws IOException {
String API_URL = "http://localhost:8080/multilabel-image-classification"; // Service URL
String imagePath = "./demo.jpg"; // Local image
String outputImagePath = "./out.jpg"; // Output image
// Encode the local image using Base64
File file = new File(imagePath);
byte[] fileContent = java.nio.file.Files.readAllBytes(file.toPath());
String imageData = Base64.getEncoder().encodeToString(fileContent);
ObjectMapper objectMapper = new ObjectMapper();
ObjectNode params = objectMapper.createObjectNode();
params.put("image", imageData); // Base64-encoded file content or image URL
// Create OkHttpClient instance
OkHttpClient client = new OkHttpClient();
MediaType JSON = MediaType.Companion.get("application/json; charset=utf-8");
RequestBody body = RequestBody.Companion.create(params.toString(), JSON);
Request request = new Request.Builder()
.url(API_URL)
.post(body)
.build();
// Call the API and process the response data
try (Response response = client.newCall(request).execute()) {
if (response.isSuccessful()) {
String responseBody = response.body().string();
JsonNode resultNode = objectMapper.readTree(responseBody);
JsonNode result = resultNode.get("result");
String base64Image = result.get("image").asText();
JsonNode categories = result.get("categories");
byte[] imageBytes = Base64.getDecoder().decode(base64Image);
try (FileOutputStream fos = new FileOutputStream(outputImagePath)) {
fos.write(imageBytes);
}
System.out.println("Output image saved at " + outputImagePath);
System.out.println("\nCategories: " + categories.toString());
} else {
System.err.println("Request failed with code: " + response.code());
}
}
}
}
Go
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
func main() {
API_URL := "http://localhost:8080/multilabel-image-classification"
imagePath := "./demo.jpg"
outputImagePath := "./out.jpg"
// Encode the local image using Base64
imageBytes, err := ioutil.ReadFile(imagePath)
if err != nil {
fmt.Println("Error reading image file:", err)
return
}
imageData := base64.StdEncoding.EncodeToString(imageBytes)
payload := map[string]string{"image": imageData} // Base64-encoded file content or image URL
payloadBytes, err := json.Marshal(payload)
if err != nil {
fmt.Println("Error marshaling payload:", err)
return
}
// Call the API
client := &http.Client{}
req, err := http.NewRequest("POST", API_URL, bytes.NewBuffer(payloadBytes))
if err != nil {
fmt.Println("Error creating request:", err)
return
}
res, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return
}
defer res.Body.Close()
// Process the response data
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println("Error reading response body:", err)
return
}
type Response struct {
Result struct {
Image string `json:"image"`
Categories []map[string]interface{} `json:"categories"`
} `json:"result"`
}
var respData Response
err = json.Unmarshal([]byte(string(body)), &respData)
if err != nil {
fmt.Println("Error unmarshaling response body:", err)
return
}
outputImageData, err := base64.StdEncoding.DecodeString(respData.Result.Image)
if err != nil {
fmt.Println("Error decoding base64 image data:", err)
return
}
err = ioutil.WriteFile(outputImagePath, outputImageData, 0644)
if err != nil {
fmt.Println("Error writing image to file:", err)
return
}
fmt.Printf("Image saved at %s.jpg\n", outputImagePath)
fmt.Println("\nCategories:")
for _, category := range respData.Result.Categories {
fmt.Println(category)
}
}
C#
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
class Program
{
static readonly string API_URL = "http://localhost:8080/multilabel-image-classification";
static readonly string imagePath = "./demo.jpg";
static readonly string outputImagePath = "./out.jpg";
static async Task Main(string[] args)
{
var httpClient = new HttpClient();
// Encode the local image to Base64
byte[] imageBytes = File.ReadAllBytes(imagePath);
string image_data = Convert.ToBase64String(imageBytes);
var payload = new JObject{ { "image", image_data } }; // Base64-encoded file content or image URL
var content = new StringContent(payload.ToString(), Encoding.UTF8, "application/json");
// Call the API
HttpResponseMessage response = await httpClient.PostAsync(API_URL, content);
response.EnsureSuccessStatusCode();
// Process the response data
string responseBody = await response.Content.ReadAsStringAsync();
JObject jsonResponse = JObject.Parse(responseBody);
string base64Image = jsonResponse["result"]["image"].ToString();
byte[] outputImageBytes = Convert.FromBase64String(base64Image);
File.WriteAllBytes(outputImagePath, outputImageBytes);
Console.WriteLine($"Output image saved at {outputImagePath}");
Console.WriteLine("\nCategories:");
Console.WriteLine(jsonResponse["result"]["categories"].ToString());
}
}
Node.js
const axios = require('axios');
const fs = require('fs');
const API_URL = 'http://localhost:8080/multilabel-image-classification'
const imagePath = './demo.jpg'
const outputImagePath = "./out.jpg";
let config = {
method: 'POST',
maxBodyLength: Infinity,
url: API_URL,
data: JSON.stringify({
'image': encodeImageToBase64(imagePath) // Base64-encoded file content or image URL
})
};
// Encode the local image in Base64
function encodeImageToBase64(filePath) {
const bitmap = fs.readFileSync(filePath);
return Buffer.from(bitmap).toString('base64');
}
// Call the API
axios.request(config)
.then((response) => {
// Process the returned data
const result = response.data["result"];
const imageBuffer = Buffer.from(result["image"], 'base64');
fs.writeFile(outputImagePath, imageBuffer, (err) => {
if (err) throw err;
console.log(`Output image saved at ${outputImagePath}`);
});
console.log("\nCategories:");
console.log(result["categories"]);
})
.catch((error) => {
console.log(error);
});
PHP
<?php
$API_URL = "http://localhost:8080/multilabel-image-classification"; // Service URL
$image_path = "./demo.jpg";
$output_image_path = "./out.jpg";
// Encode the local image in Base64
$image_data = base64_encode(file_get_contents($image_path));
$payload = array("image" => $image_data); // Base64-encoded file content or image URL
// Call the API
$ch = curl_init($API_URL);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
// Process the returned data
$result = json_decode($response, true)["result"];
file_put_contents($output_image_path, base64_decode($result["image"]));
echo "Output image saved at " . $output_image_path . "\n";
echo "\nCategories:\n";
print_r($result["categories"]);
?>
📱 Edge Deployment: Edge deployment is a method where computation 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 processes, please refer to the PaddleX Edge Deployment Guide. You can choose the appropriate method to deploy the model pipeline based on your needs for subsequent AI application integration.
4. Secondary Development¶
If the default model weights provided by the general image multi-label classification pipeline do not meet your accuracy or speed requirements in your scenario, you can try further fine-tuning the existing model using your own specific domain or application scenario data to improve the recognition performance of the general image multi-label classification pipeline in your scenario.
4.1 Model Fine-Tuning¶
Since the general image multi-label classification pipeline includes an image multi-label classification module, if the performance of the model pipeline is not as expected, you need to refer to the fine-tuning tutorial link in the table below to fine-tune the model.
Situation | Fine-Tuning Module | Fine-Tuning Reference Link |
---|---|---|
Multi-label classification is inaccurate | Multi-label classification module | Link |
4.2 Model Application¶
After completing the fine-tuning training with your private dataset, you will obtain a local model weight file.
If you need to use the fine-tuned model weights, simply modify the pipeline configuration file by replacing the local path of the fine-tuned model weights in the corresponding position in the configuration file:
pipeline_name: image_multilabel_classification
SubModules:
ImageMultiLabelClassification:
module_name: image_multilabel_classification
model_name: PP-HGNetV2-B6_ML
model_dir: null # Modify this path to the local fine-tuned model weight file
batch_size: 4
Subsequently, refer to the command line method or Python script method in the local experience section to load the modified pipeline configuration file.
5. Multi-Hardware Support¶
PaddleX supports various mainstream hardware devices such as NVIDIA GPU, Kunlunxin XPU, Ascend NPU, and Cambricon MLU. You only need to modify the --device
parameter to achieve seamless switching between different hardware.
For example, if you use Ascend NPU for inference of the general image multi-label classification pipeline, the Python command used is:
paddlex --pipeline image_multilabel_classification \
--input general_image_classification_001.jpg \
--device npu:0
If you want to use the general image multi-label classification pipeline on more types of hardware, please refer to the PaddleX Multi-Hardware Usage Guide.