Skip to content

Mainbody detection Module Development Tutorial

I. Overview

Mainbody detection is a fundamental task in object detection, aiming to identify and extract the location and size of specific target objects, people, or entities from images and videos. By constructing deep neural network models, mainbody detection learns the feature representations of image subjects to achieve efficient and accurate detection.

II. Supported Model List

ModelModel Download Link mAP(0.5:0.95) mAP(0.5) CPU Inference Time (ms)
[Normal Mode / High-Performance Mode]
CPU Inference Time (ms)
[Normal Mode / High-Performance Mode]
Model Size (M) Description
PP-ShiTuV2_detInference Model/Trained Model 41.5 62.0 12.79 / 4.51 44.14 / 44.14 27.54 A mainbody detection model based on PicoDet_LCNet_x2_5, which may detect multiple common subjects simultaneously.

Test Environment Description:

  • Performance Test Environment
  • Test Dataset: PaddleClas mainbody detection dataset.
  • 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
Normal 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.)

III. Quick Integration

❗ Before quick integration, please install the PaddleX wheel package. For detailed instructions, refer to PaddleX Local Installation Guide

After installing the wheel package, you can perform mainbody detection inference with just a few lines of code. You can easily switch between models under this module, and integrate the mainbody detection model inference into your project. Before running the following code, please download the demo image to your local machine.

from paddlex import create_model
model_name = "PP-ShiTuV2_det"
model = create_model(model_name)
output = model.predict("general_object_detection_002.png", batch_size=1)
for res in output:
    res.print()
    res.save_to_img("./output/")
    res.save_to_json("./output/res.json")

After running, the result obtained is:

{'res': "{'input_path': 'general_object_detection_002.png', 'page_index': None, 'boxes': [{'cls_id': 0, 'label': 'mainbody', 'score': 0.8161919713020325, 'coordinate': [76.07117, 272.83017, 329.5627, 519.48236]}, {'cls_id': 0, 'label': 'mainbody', 'score': 0.8071584701538086, 'coordinate': [662.7539, 92.804276, 874.7139, 308.21216]}, {'cls_id': 0, 'label': 'mainbody', 'score': 0.754974365234375, 'coordinate': [284.4833, 93.76895, 476.6789, 297.27588]}, {'cls_id': 0, 'label': 'mainbody', 'score': 0.6657832860946655, 'coordinate': [732.1591, 0, 1035.9547, 168.45923]}, {'cls_id': 0, 'label': 'mainbody', 'score': 0.614763081073761, 'coordinate': [763.9127, 280.74258, 925.48065, 439.444]}, ... ]}"}

The meanings of the running results parameters are as follows: - input_path: Indicates the path of the input image to be predicted. - page_index: If the input is a PDF file, it represents the current page number of the PDF; otherwise, it is None. - boxes: Information of each detected object. - cls_id: Class ID. - label: Class name. - score: Prediction score. - coordinate: Coordinates of the bounding box, in the format [xmin, ymin, xmax, ymax].

The visualization image is as follows:

Note: Due to network issues, the above URL may not be accessible. If you need to access this link, please check the validity of the URL and try again. If the problem persists, it may be related to the link itself or the network connection.

Related methods, parameters, and explanations are as follows:

  • create_model instantiates a main body detection model (here, PP-ShiTuV2_det is used as an example), and the specific explanations are as follows:
Parameter Parameter Description Parameter Type Options Default Value
model_name Name of the model str None None
model_dir Path to store the model str None None
threshold Threshold for filtering low-confidence objects float/None/dict None None
  • The model_name must be specified. After specifying model_name, the default model parameters built into PaddleX are used. If model_dir is specified, the user-defined model is used.
  • threshold is the threshold for filtering low-confidence objects. The default is None, which means using the settings from the lower priority. The priority of parameter settings from highest to lowest is: predict parameter > create_model initialization > yaml configuration file. Currently, two types of threshold settings are supported:
  • float, using the same threshold for all classes.
  • dict, where the key is the class ID and the value is the threshold, allowing different thresholds for different classes. Since main body detection is a single-class detection, this setting is not required.

  • The predict() method of the main body detection model is called for inference prediction. The predict() method has parameters input, batch_size, and threshold, which are explained as follows:

Parameter Parameter Description Parameter Type Options Default Value
input Data to be predicted, supporting multiple input types Python Var/str/list
  • Python variable, such as image data represented by numpy.ndarray
  • File path, such as the local path of an image file: /root/data/img.jpg
  • URL link, such as the network URL of an image file: Example
  • Local directory, the directory should contain data files to be predicted, such as the local path: /root/data/
  • List, elements of the list must be of the above types of data, such as [numpy.ndarray, numpy.ndarray], ["/root/data/img1.jpg", "/root/data/img2.jpg"], ["/root/data1", "/root/data2"]
None
batch_size Batch size int Any integer 1
threshold Threshold for filtering low-confidence objects float/dict/None
  • None, indicating the use of settings from the lower priority. The priority of parameter settings from highest to lowest is: predict parameter > create_model initialization > yaml configuration file
  • float, such as 0.5, indicating the use of 0.5 as the threshold for filtering low-confidence objects during inference
  • dict, such as {0: 0.5, 1: 0.35}, indicating the use of 0.5 as the threshold for class 0 and 0.35 for class 1 during inference. Since main body detection is a single-class detection, this setting is not required.
None
  • The prediction results are processed, and the prediction result for each sample is of type dict. It supports operations such as printing, saving as an image, and saving as a json file:
Method Method Description Parameter Parameter Type Parameter Description Default Value
print() Print the results 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, only effective when format_json is True 4
ensure_ascii bool Control whether to escape non-ASCII characters to Unicode. If set to True, all non-ASCII characters will be escaped; False retains the original characters, only effective when format_json is True False
save_to_json() Save the results as a JSON file save_path str The path to save the file. If it is a directory, the saved file name will be consistent with the input file name None
indent int Specify the indentation level to beautify the output JSON data, making it more readable, only effective when format_json is True 4
ensure_ascii bool Control whether to escape non-ASCII characters to Unicode. If set to True, all non-ASCII characters will be escaped; False retains the original characters, only effective when format_json is True False
save_to_img() Save the results as an image file save_path str The path to save the file. If it is a directory, the saved file name will be consistent with the input file name None
  • Additionally, it supports obtaining the visualization image with results and the prediction results through attributes, as follows:
Attribute Attribute Description
json Get the prediction result in json format
img Get the visualization image in dict format

For more information on using PaddleX's single-model inference APIs, refer to PaddleX Single Model Python Script Usage Instructions.

IV. Custom Development

If you seek higher accuracy from existing models, you can leverage PaddleX's custom development capabilities to develop better mainbody detection models. Before developing mainbody detection models with PaddleX, ensure you have installed the PaddleDetection plugin for PaddleX. The installation process can be found in PaddleX Local Installation Guide.

4.1 Data Preparation

Before model training, you need to prepare a dataset for the specific task module. PaddleX provides a data validation function for each module, and only data that passes validation can be used for model training. Additionally, PaddleX provides demo datasets for each module, which you can use to complete subsequent development. If you wish to use a private dataset for model training, refer to PaddleX Object Detection Task Module Data Annotation Tutorial.

4.1.1 Demo Data Download

You can download the demo dataset to a specified folder using the following commands:

cd /path/to/paddlex
wget https://paddle-model-ecology.bj.bcebos.com/paddlex/data/mainbody_det_examples.tar -P ./dataset
tar -xf ./dataset/mainbody_det_examples.tar -C ./dataset/

4.1.2 Data Validation

You can complete data validation with a single command:

python main.py -c paddlex/configs/modules/mainbody_detection/PP-ShiTuV2_det.yaml \
    -o Global.mode=check_dataset \
    -o Global.dataset_dir=./dataset/mainbody_det_examples
After executing the above command, PaddleX will validate the dataset and collect its basic information. Upon successful execution, the log will print the message Check dataset passed !. The validation result file will be saved in ./output/check_dataset_result.json, and related outputs will be saved in the ./output/check_dataset directory of the current directory. The output directory includes visualized example images and histograms of sample distributions.

👉 Details of validation results (click to expand)

The specific content of the validation result file is:

{
  "done_flag": true,
  "check_pass": true,
  "attributes": {
    "num_classes": 1,
    "train_samples": 701,
    "train_sample_paths": [
      "check_dataset/demo_img/road839.png",
      "check_dataset/demo_img/road363.png",
      "check_dataset/demo_img/road148.png"
    ],
    "val_samples": 176,
    "val_sample_paths": [
      "check_dataset/demo_img/road218.png",
      "check_dataset/demo_img/road681.png",
      "check_dataset/demo_img/road138.png"
    ]
  },
  "analysis": {
    "histogram": "check_dataset/histogram.png"
  },
  "dataset_path": "mainbody_det_examples",
  "show_type": "image",
  "dataset_type": "COCODetDataset"
}

In the above validation results, check_pass being True indicates that the dataset format meets the requirements. The explanations for other indicators are as follows:

  • attributes.num_classes:The number of classes in this dataset is 1.
  • attributes.train_samples:The number of samples in the training set of this dataset is 701.
  • attributes.val_samples:The number of samples in the validation set of this dataset is 176.
  • attributes.train_sample_paths:A list of relative paths to the visualized images of samples in the training set of this dataset.
  • attributes.val_sample_paths: A list of relative paths to the visualized images of samples in the validation set of this dataset.

The dataset validation also analyzes the distribution of sample counts across all classes in the dataset and generates a histogram (histogram.png) to visualize this distribution.

4.1.3 Dataset Format Conversion / Dataset Splitting (Optional)

After completing the dataset verification, you can convert the dataset format or re-split the training/validation ratio by modifying the configuration file or appending hyperparameters.

👉 Details on Format Conversion / Dataset Splitting (Click to Expand)

(1) Dataset Format Conversion

Mainbody detection does not support data format conversion.

(2) Dataset Splitting

Dataset splitting parameters can be set by modifying the CheckDataset section in the configuration file. Some example parameters in the configuration file are explained below:

  • CheckDataset:
  • split:
  • enable: Whether to re-split the dataset. Set to True to enable dataset splitting, default is False;
  • train_percent: If re-splitting the dataset, set the percentage of the training set. The type is any integer between 0-100, ensuring the sum with val_percent is 100;

For example, if you want to re-split the dataset with a 90% training set and a 10% validation set, modify the configuration file as follows:

......
CheckDataset:
  ......
  split:
    enable: True
    train_percent: 90
    val_percent: 10
  ......

Then execute the command:

python main.py -c paddlex/configs/modules/mainbody_detection/PP-ShiTuV2_det.yaml \
    -o Global.mode=check_dataset \
    -o Global.dataset_dir=./dataset/mainbody_det_examples

After dataset splitting, the original annotation files will be renamed to xxx.bak in their original paths.

The above parameters can also be set by appending command-line arguments:

python main.py -c paddlex/configs/modules/mainbody_detection/PP-ShiTuV2_det.yaml  \
    -o Global.mode=check_dataset \
    -o Global.dataset_dir=./dataset/mainbody_det_examples \
    -o CheckDataset.split.enable=True \
    -o CheckDataset.split.train_percent=90 \
    -o CheckDataset.split.val_percent=10

4.2 Model Training

Model training can be completed with a single command, taking the training of PP-ShiTuV2_det as an example:

python main.py -c paddlex/configs/modules/mainbody_detection/PP-ShiTuV2_det.yaml \
    -o Global.mode=train \
    -o Global.dataset_dir=./dataset/mainbody_det_examples
The steps required are:

  • Specify the .yaml configuration file path for the model (here it is PP-ShiTuV2_det.yaml,When training other models, you need to specify the corresponding configuration files. The relationship between the model and configuration files can be found in the PaddleX Model List (CPU/GPU))
  • Specify the mode as model training: -o Global.mode=train
  • Specify the training dataset path: -o Global.dataset_dir Other related parameters can be set by modifying the Global and Train fields in the .yaml configuration file, or adjusted by appending parameters in the command line. For example, to specify training on the first two GPUs: -o Global.device=gpu:0,1; to set the number of training epochs to 10: -o Train.epochs_iters=10. For more modifiable parameters and their detailed explanations, refer to the PaddleX Common Configuration Parameters for Model Tasks.
👉 More Details (Click to Expand)
  • During model training, PaddleX automatically saves model weight files, defaulting to output. To specify a save path, use the -o Global.output field in the configuration file.
  • PaddleX shields you from the concepts of dynamic graph weights and static graph weights. During model training, both dynamic and static graph weights are produced, and static graph weights are selected by default for model inference.
  • After completing the model training, all outputs are saved in the specified output directory (default is ./output/), typically including:

  • train_result.json: Training result record file, recording whether the training task was completed normally, as well as the output weight metrics, related file paths, etc.;

  • train.log: Training log file, recording changes in model metrics and loss during training;
  • config.yaml: Training configuration file, recording the hyperparameter configuration for this training session;
  • .pdparams, .pdema, .pdopt.pdstate, .pdiparams, .pdmodel: Model weight-related files, including network parameters, optimizer, EMA, static graph network parameters, static graph network structure, etc.;

4.3 Model Evaluation

After completing model training, you can evaluate the specified model weight file on the validation set to verify the model's accuracy. Using PaddleX for model evaluation, you can complete the evaluation with a single command:

python main.py -c paddlex/configs/modules/mainbody_detection/PP-ShiTuV2_det.yaml \
    -o Global.mode=evaluate \
    -o Global.dataset_dir=./dataset/mainbody_det_examples
Similar to model training, the process involves the following steps:

  • Specify the path to the .yaml configuration file for the model(here it's PP-ShiTuV2_det.yaml
  • Set the mode to model evaluation: -o Global.mode=evaluate
  • Specify the path to the validation dataset: -o Global.dataset_dir Other related parameters can be configured by modifying the fields under Global and Evaluate in the .yaml configuration file. For detailed information, please refer to PaddleX Common Configuration Parameters for Models
👉 More Details (Click to Expand)

When evaluating the model, you need to specify the model weights file path. Each configuration file has a default weight save path built-in. If you need to change it, simply set it by appending a command line parameter, such as -o Evaluate.weight_path=./output/best_model/best_model/model.pdparams.

After completing the model evaluation, an evaluate_result.json file will be generated, which records the evaluation results, specifically whether the evaluation task was completed successfully, and the model's evaluation metrics, including AP.

4.4 Model Inference

After completing model training and evaluation, you can use the trained model weights for inference predictions. In PaddleX, model inference predictions can be achieved through two methods: command line and wheel package.

4.4.1 Model Inference

  • To perform inference predictions through the command line, simply use the following command. Before running the following code, please download the demo image to your local machine.

    python main.py -c paddlex/configs/modules/mainbody_detection/PP-ShiTuV2_det.yaml \
        -o Global.mode=predict \
        -o Predict.model_dir="./output/best_model/inference" \
        -o Predict.input="general_object_detection_002.png"
    
    Similar to model training and evaluation, the following steps are required:

  • Specify the .yaml configuration file path of the model (here it is PP-ShiTuV2_det.yaml)

  • Set the mode to model inference prediction: -o Global.mode=predict
  • Specify the model weights path: -o Predict.model_dir="./output/best_model/inference"
  • Specify the input data path: -o Predict.input="..." Other related parameters can be set by modifying the fields under Global and Predict in the .yaml configuration file. For details, please refer to PaddleX Common Model Configuration File Parameter Description.

4.4.2 Model Integration

The model can be directly integrated into the PaddleX pipeline or directly into your own project.

  1. Pipeline Integration

The main body detection module can be integrated into PaddleX pipelines such as General Object Detection (comming soon). Simply replace the model path to update the main body detection module of the relevant pipeline. In pipeline integration, you can use high-performance inference and service-oriented deployment to deploy your trained model.

  1. Module Integration

The weights you produce can be directly integrated into the main body detection module. You can refer to the Python example code in Quick Integration, simply replace the model with the path to your trained model.

You can also use the PaddleX high-performance inference plugin to optimize the inference process of your model and further improve efficiency. For detailed procedures, please refer to the PaddleX High-Performance Inference Guide.

Comments