video_classification.en.md 33 KB


comments: true

General Video Classification Pipeline Tutorial

1. Introduction to the General Video Classification Pipeline

Video Classification is a technique that assigns video clips to predefined categories. It is widely applied in fields such as action recognition, event detection, and content recommendation. Video classification can recognize various dynamic events and scenes, such as sports activities, natural phenomena, traffic conditions, and categorize them based on their characteristics. By utilizing deep learning models, especially the combination of Convolutional Neural Networks (CNN) and Recurrent Neural Networks (RNN), video classification can automatically extract spatio-temporal features from videos and perform accurate classification. This technology holds significant applications in video surveillance, media retrieval, and personalized recommendation systems.

The General Video Classification Pipeline includes an video classification module. If you prioritize model accuracy, choose a model with higher accuracy. If you prioritize inference speed, select a model with faster inference. If you prioritize model storage size, choose a model with a smaller storage size.

👉Details of Model List
ModelModel Download Link Top1 Acc(%) Model Storage Size (M) Description
PPTSM_ResNet50_k400_8frames_uniformInference Model/Trained Model 74.36 93.4 M PP-TSM is a video classification model developed by Baidu PaddlePaddle's Vision Team. This model is optimized based on the ResNet-50 backbone network and undergoes model tuning in six aspects: data augmentation, network structure fine-tuning, training strategies, Batch Normalization (BN) layer optimization, pre-trained model selection, and model distillation. Under the center crop evaluation method, its accuracy on Kinetics-400 is improved by 3.95 points compared to the original paper's implementation.
PPTSMv2_LCNet_k400_8frames_uniformInference Model/Trained Model 71.71 22.5 M PP-TSMv2 is a lightweight video classification model optimized based on the CPU-oriented model PP-LCNetV2. It undergoes model tuning in seven aspects: backbone network and pre-trained model selection, data augmentation, TSM module tuning, input frame number optimization, decoding speed optimization, DML distillation, and LTA module. Under the center crop evaluation method, it achieves an accuracy of 75.16%, with an inference speed of only 456ms on the CPU for a 10-second video input.
PPTSMv2_LCNet_k400_16frames_uniformInference Model/Trained Model 73.11 22.5 M

Note: The above accuracy metrics refer to Top-1 Accuracy on the K400 validation set. All model GPU inference times are based on NVIDIA Tesla T4 machines, with precision type FP32. CPU inference speeds are based on Intel® Xeon® Gold 5117 CPU @ 2.00GHz, with 8 threads and precision type FP32.

2. Quick Start

PaddleX supports experiencing the effects of pipelines locally using the command line or Python.

Before using the general video classification pipeline locally, please ensure that you have completed the installation of the PaddleX wheel package according to the PaddleX local installation tutorial.

2.1 Command Line Experience

A single command is all you need to quickly experience the video classification pipeline, Use the test file, and replace --input with the local path to perform prediction.

paddlex --pipeline video_classification --input general_video_classification_001.mp4 --device gpu:0

Parameter Explanation:

--pipeline: The name of the pipeline, here it is the video classification pipeline.
--input: The local path or URL of the input video to be processed.
--device: The GPU index to use (e.g., gpu:0 for the first GPU, gpu:1,2 for the second and third GPUs). You can also choose to use CPU (--device cpu).

When executing the above command, the default video classification pipeline configuration file is loaded. If you need to customize the configuration file, you can execute the following command to obtain it:

👉Click to expand
paddlex --get_pipeline_config video_classification

After execution, the video classification pipeline configuration file will be saved in the current path. If you wish to customize the save location, you can execute the following command (assuming the custom save location is ./my_path):

paddlex --get_pipeline_config video_classification --save_path ./my_path

After obtaining the pipeline configuration file, replace --pipeline with the configuration file's save path to make the configuration file take effect. For example, if the configuration file's save path is ./video_classification.yaml, simply execute:

paddlex --pipeline ./video_classification.yaml --input general_video_classification_001.mp4  --device gpu:0

Here, parameters such as --model and --device do not need to be specified, as they will use the parameters in the configuration file. If you still specify parameters, the specified parameters will take precedence.

After running, the result will be:

{'input_path': 'general_video_classification_001.mp4', 'class_ids': [0], 'scores': array([0.91996]), 'label_names': ['abseiling']}

The visualized video not saved by default. You can customize the save path through --save_path, and then all results will be saved in the specified path.

2.2 Python Script Integration

A few lines of code can complete the quick inference of the pipeline. Taking the general video classification pipeline as an example:

from paddlex import create_pipeline

pipeline = create_pipeline(pipeline="video_classification")

output = pipeline.predict("general_video_classification_001.mp4")
for res in output:
    res.print() # Print the structured output of the prediction
    res.save_to_video("./output/")  # Save the result visualization video
    res.save_to_json("./output/") # Save the structured output of the prediction

The results obtained are the same as those obtained through the command line method.

In the above Python script, the following steps are executed:

(1) Instantiate the create_pipeline to create a pipeline object: The specific parameter descriptions are as follows:

Parameter Description Type Default
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, which is only available when the pipeline supports it. bool False
(2) Call the predict method of the video classification pipeline object for inference prediction: The predict method parameter is x, which is used to input data to be predicted, supporting multiple input methods, as shown in the following examples:

Parameter Type Description
Python Var Supports directly passing Python variables, such as numpy.ndarray representing video data.
str Supports passing the path of the file to be predicted, such as the local path of an video file: /root/data/video.mp4。.
str Supports passing the URL of the file to be predicted, such as the network URL of an video file: Example.
str Supports passing a local directory, which should contain files to be predicted, such as the local path: /root/data/.
dict Supports passing a dictionary type, where the key needs to correspond to the specific task, such as "video" for the video classification task, and the value of the dictionary supports the above data types, e.g., {"video": "/root/data1"}.
list Supports passing a list, where the list elements need to be the above data types, such as [numpy.ndarray, numpy.ndarray], ["/root/data/video1.mp4", "/root/data/video2.mp4"], ["/root/data1", "/root/data2"], [{"video": "/root/data1"}, {"video": "/root/data2/video.mp4"}].
3)Obtain 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.

(4)Process the prediction results: The prediction result for each sample is of dict type and supports printing or saving to files, with the supported file types depending on the specific pipeline. For example:

Method Description Method Parameters
print Prints 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 valid when format_json is True, default is 4;
- ensure_ascii: bool, json formatting setting, only valid when format_json is True, default is False;
save_to_json Saves results as a json file - save_path: str, the path to save the file, when it's 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_video Saves results as an video file - save_path: str, the path to save the file, when it's a directory, the saved file name is consistent with the input file type;
If you have a configuration file, you can customize the configurations of the video anomaly detection pipeline by simply modifying the pipeline parameter in the create_pipeline method to the path of the pipeline configuration file.

For example, if your configuration file is saved at ./my_path/video_classification.yaml, you only need to execute:

from paddlex import create_pipeline
pipeline = create_pipeline(pipeline="./my_path/video_classification.yaml")
output = pipeline.predict("general_video_classification_001.mp4 ")
for res in output:
    res.print()  # Print the structured output of prediction
    res.save_to_video("./output/")  # Save the visualization video of the result
    res.save_to_json("./output/")  # Save the structured output of prediction

3. Development Integration/Deployment

If the pipeline meets your requirements for inference speed and accuracy, you can proceed directly with development integration/deployment.

If you need to apply the pipeline directly in your Python project, refer to the example code in 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 for significant end-to-end speedups. For detailed high-performance inference procedures, 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 functions as services, clients can access these services through network requests to obtain inference results. PaddleX supports users in achieving low-cost service-oriented deployment of pipelines. For detailed service-oriented deployment procedures, refer to the PaddleX Service-Oriented Deployment Guide.

Below are the API references 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 message. 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 message.

Main operations provided by the service are as follows:

  • infer

Classify videos.

POST /video-classification

  • The request body properties are as follows:
Name Type Description Required
video string The URL of an video file accessible by the service or the Base64 encoded result of the video file content. Yes
inferenceParams object Inference parameters. No

The properties of inferenceParams are as follows:

Name Type Description Required
topK integer Only the top topK categories with the highest scores will be retained in the results. No
  • When the request is processed successfully, the result of the response body has the following properties:
Name Type Description
categories array video category information.
video string The video classification result video. The video is in JPEG format and encoded using 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
}
],
"video": "xxxxxx"
}
Multi-Language Service Invocation Examples
Python
import base64
import requests

API_URL = "http://localhost:8080/video-classification"
video_path = "./demo.mp4"
output_video_path = "./out.mp4"

with open(video_path, "rb") as file:
    video_bytes = file.read()
    video_data = base64.b64encode(video_bytes).decode("ascii")

payload = {"video": video_data}

response = requests.post(API_URL, json=payload)

assert response.status_code == 200
result = response.json()["result"]
with open(output_video_path, "wb") as file:
    file.write(base64.b64decode(result["video"]))
print(f"Output video saved at {output_video_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 videoPath = "./demo.mp4";
    const std::string outputvideoPath = "./out.mp4";

    httplib::Headers headers = {
        {"Content-Type", "application/json"}
    };

    std::ifstream file(videoPath, 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 encodedVideo = base64::to_base64(bufferStr);

    nlohmann::json jsonObj;
    jsonObj["video"] = encodedVideo;
    std::string body = jsonObj.dump();

    auto response = client.Post("/video-classification", headers, body, "application/json");
    if (response && response->status == 200) {
        nlohmann::json jsonResponse = nlohmann::json::parse(response->body);
        auto result = jsonResponse["result"];

        encodedVideo = result["video"];
        std::string decodedString = base64::from_base64(encodedVideo);
        std::vector<unsigned char> decodedImage(decodedString.begin(), decodedString.end());
        std::ofstream outputImage(outPutvideoPath, std::ios::binary | std::ios::out);
        if (outputImage.is_open()) {
            outputImage.write(reinterpret_cast<char*>(decodedImage.data()), decodedImage.size());
            outputImage.close();
            std::cout << "Output video saved at " << outPutvideoPath << std::endl;
        } else {
            std::cerr << "Unable to open file for writing: " << outPutvideoPath << 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/video-classification";
        String videoPath = "./demo.mp4";
        String outputvideoPath = "./out.mp4";

        File file = new File(videoPath);
        byte[] fileContent = java.nio.file.Files.readAllBytes(file.toPath());
        String videoData = Base64.getEncoder().encodeToString(fileContent);

        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode params = objectMapper.createObjectNode();
        params.put("video", videoData);

        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();

        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("video").asText();
                JsonNode categories = result.get("categories");

                byte[] videoBytes = Base64.getDecoder().decode(base64Image);
                try (FileOutputStream fos = new FileOutputStream(outputvideoPath)) {
                    fos.write(videoBytes);
                }
                System.out.println("Output video saved at " + outputvideoPath);
                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/video-classification"
    videoPath := "./demo.mp4"
    outputvideoPath := "./out.mp4"

    videoBytes, err := ioutil.ReadFile(videoPath)
    if err != nil {
        fmt.Println("Error reading video file:", err)
        return
    }
    videoData := base64.StdEncoding.EncodeToString(videoBytes)

    payload := map[string]string{"video": videoData}
    payloadBytes, err := json.Marshal(payload)
    if err != nil {
        fmt.Println("Error marshaling payload:", err)
        return
    }

    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()

    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:"video"`
            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 video data:", err)
        return
    }
    err = ioutil.WriteFile(outputvideoPath, outputImageData, 0644)
    if err != nil {
        fmt.Println("Error writing video to file:", err)
        return
    }
    fmt.Printf("Image saved at %s.mp4\n", outputvideoPath)
    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/video-classification";
    static readonly string videoPath = "./demo.mp4";
    static readonly string outputvideoPath = "./out.mp4";

    static async Task Main(string[] args)
    {
        var httpClient = new HttpClient();

        byte[] videoBytes = File.ReadAllBytes(videoPath);
        string video_data = Convert.ToBase64String(videoBytes);

        var payload = new JObject{ { "video", video_data } };
        var content = new StringContent(payload.ToString(), Encoding.UTF8, "application/json");

        HttpResponseMessage response = await httpClient.PostAsync(API_URL, content);
        response.EnsureSuccessStatusCode();

        string responseBody = await response.Content.ReadAsStringAsync();
        JObject jsonResponse = JObject.Parse(responseBody);

        string base64Image = jsonResponse["result"]["video"].ToString();
        byte[] outputImageBytes = Convert.FromBase64String(base64Image);

        File.WriteAllBytes(outputvideoPath, outputImageBytes);
        Console.WriteLine($"Output video saved at {outputvideoPath}");
        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/video-classification'
const videoPath = './demo.mp4'
const outputvideoPath = "./out.mp4";

let config = {
   method: 'POST',
   maxBodyLength: Infinity,
   url: API_URL,
   data: JSON.stringify({
    'video': encodeImageToBase64(videoPath)
  })
};

function encodeImageToBase64(filePath) {
  const bitmap = fs.readFileSync(filePath);
  return Buffer.from(bitmap).toString('base64');
}

axios.request(config)
.then((response) => {
    const result = response.data["result"];
    const videoBuffer = Buffer.from(result["video"], 'base64');
    fs.writeFile(outputvideoPath, videoBuffer, (err) => {
      if (err) throw err;
      console.log(`Output video saved at ${outputvideoPath}`);
    });
    console.log("\nCategories:");
    console.log(result["categories"]);
})
.catch((error) => {
  console.log(error);
});
PHP
<?php

$API_URL = "http://localhost:8080/video-classification";
$video_path = "./demo.mp4";
$output_video_path = "./out.mp4";

$video_data = base64_encode(file_get_contents($video_path));
$payload = array("video" => $video_data);

$ch = curl_init($API_URL);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

$result = json_decode($response, true)["result"];
file_put_contents($output_video_path, base64_decode($result["video"]));
echo "Output video saved at " . $output_video_path . "\n";
echo "\nCategories:\n";
print_r($result["categories"]);
?>


📱 Edge Deployment: Edge deployment is a method that places computing and data processing functions on user devices themselves, allowing devices to process data directly without relying on remote servers. PaddleX supports deploying models on edge devices such as Android. For detailed edge deployment procedures, refer to the PaddleX Edge Deployment Guide. You can choose the appropriate deployment method for 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 general video classification pipeline do not meet your requirements for accuracy or speed in your specific scenario, you can try to further fine-tune the existing model using data from your specific domain or application scenario to improve the recognition performance of the general video classification pipeline in your scenario.

4.1 Model Fine-tuning

Since the general video classification pipeline includes an video classification module, if the performance of the pipeline does not meet expectations, you need to refer to the Customization section in the Video Classification Module Development Tutorial and use your private dataset to fine-tune the video classification model.

4.2 Model Application

After you have completed fine-tuning training using your private dataset, you will obtain local model weight files.

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 to the corresponding location in the pipeline configuration file:

......
Pipeline:
  model: PPTSMv2_LCNet_k400_8frames_uniform  # Can be modified to the local path of the fine-tuned model
  device: "gpu"
  batch_size: 1
......

Then, 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 GPUs, Kunlun XPU, Ascend NPU, and Cambricon MLU. Simply modify the --device parameter to seamlessly switch between different hardware.

For example, if you use an NVIDIA GPU for inference in the video classification pipeline, the Python command is:

paddlex --pipeline video_classification --input general_video_classification_001.mp4  --device gpu:0
``````
At this point, if you wish to switch the hardware to Ascend NPU, simply modify the `--device` in the Python command to `npu:0`:

bash paddlex --pipeline video_classification --input general_video_classification_001.mp4 --device npu:0 ``` If you want to use the General Video Classification Pipeline on more types of hardware, please refer to the PaddleX Multi-Device Usage Guide.