---
comments: true
---
# 通用视频分类产线使用教程
## 1. 通用视频分类产线介绍
视频分类是一种将视频片段分配到预定义类别的技术。它广泛应用于动作识别、事件检测和内容推荐等领域。视频分类可以识别各种动态事件和场景,如体育活动、自然现象、交通状况等,并根据其特征将其归类。通过使用深度学习模型,尤其是卷积神经网络(CNN)和循环神经网络(RNN)的结合,视频分类能够自动提取视频中的时空特征并进行准确分类。这种技术在视频监控、媒体检索和个性化推荐系统中具有重要应用.
通用视频分类产线中包含了视频分类模块,如您更考虑模型精度,请选择精度较高的模型,如您更考虑模型推理速度,请选择推理速度较快的模型,如您更考虑模型存储大小,请选择存储大小较小的模型。
👉模型列表详情
| 模型 | 模型下载链接 |
Top1 Acc(%) |
模型存储大小 (M) |
介绍 |
| PPTSM_ResNet50_k400_8frames_uniform | 推理模型/训练模型 |
74.36 |
93.4 M |
PP-TSM是一种百度飞桨视觉团队自研的视频分类模型。该模型基于ResNet-50骨干网络进行优化,从数据增强、网络结构微调、训练策略、BN层优化、预训练模型选择、模型蒸馏等6个方面进行模型调优,在中心采样评估方式下,Kinetics-400上精度较原论文实现提升3.95个点
|
| PPTSMv2_LCNet_k400_8frames_uniform | 推理模型/训练模型 |
71.71 |
22.5 M |
PP-TSMv2是轻量化的视频分类模型,基于CPU端模型PP-LCNetV2进行优化,从骨干网络与预训练模型选择、数据增强、tsm模块调优、输入帧数优化、解码速度优化、DML蒸馏、LTA模块等7个方面进行模型调优,在中心采样评估方式下,精度达到75.16%,输入10s视频在CPU端的推理速度仅需456ms。 |
| PPTSMv2_LCNet_k400_16frames_uniform | 推理模型/训练模型 |
73.11 |
22.5 M |
注:以上精度指标为 K400 验证集 Top1 Acc。所有模型 GPU 推理耗时基于 NVIDIA Tesla T4 机器,精度类型为 FP32, CPU 推理速度基于 Intel(R) Xeon(R) Gold 5117 CPU @ 2.00GHz,线程数为8,精度类型为 FP32。
## 2. 快速开始
PaddleX 支持在本地使用命令行或 Python 体验产线的效果。
在本地使用通用视频分类产线前,请确保您已经按照PaddleX本地安装教程完成了PaddleX的wheel包安装。
#### 2.1 命令行方式体验
一行命令即可快速体验视频分类产线效果,使用 [测试文件](https://paddle-model-ecology.bj.bcebos.com/paddlex/videos/demo_video/general_video_classification_001.mp4),并将 `--input` 替换为本地路径,进行预测
```bash
paddlex --pipeline video_classification --input general_video_classification_001.mp4 --device gpu:0
```
参数说明:
```
--pipeline:产线名称,此处为视频分类产线
--input:待处理的输入视频的本地路径或URL
--device 使用的GPU序号(例如gpu:0表示使用第0块GPU,gpu:1,2表示使用第1、2块GPU),也可选择使用CPU(--device cpu)
```
在执行上述 Python 脚本时,加载的是默认的视频分类产线配置文件,若您需要自定义配置文件,可执行如下命令获取:
👉点击展开
paddlex --get_pipeline_config video_classification
执行后,视频分类产线配置文件将被保存在当前路径。若您希望自定义保存位置,可执行如下命令(假设自定义保存位置为 ./my_path ):
paddlex --get_pipeline_config video_classification --save_path ./my_path
获取产线配置文件后,可将 --pipeline 替换为配置文件保存路径,即可使配置文件生效。例如,若配置文件保存路径为 ./video_classification.yaml,只需执行:
paddlex --pipeline ./video_classification.yaml --input general_video_classification_001.mp4 --device gpu:0
其中,--model、--device 等参数无需指定,将使用配置文件中的参数。若依然指定了参数,将以指定的参数为准。
运行后,得到的结果为:
```
{'input_path': 'general_video_classification_001.mp4', 'class_ids': [0], 'scores': array([0.91996]), 'label_names': ['abseiling']}
```
可视化视频默认不进行保存,您可以通过 `--save_path` 自定义保存路径,随后所有结果将被保存在指定路径下。
#### 2.2 Python脚本方式集成
几行代码即可完成产线的快速推理,以通用视频分类产线为例:
```
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() ## 打印预测的结构化输出
res.save_to_video("./output/") ## 保存结果可视化视频
res.save_to_json("./output/") ## 保存预测的结构化输出
```
得到的结果与命令行方式相同。
在上述 Python 脚本中,执行了如下几个步骤:
(1)实例化 `create_pipeline` 实例化产线对象:具体参数说明如下:
API参考
对于服务提供的主要操作:
- HTTP请求方法为POST。
- 请求体和响应体均为JSON数据(JSON对象)。
- 当请求处理成功时,响应状态码为
200,响应体的属性如下:
| 名称 |
类型 |
含义 |
errorCode |
integer |
错误码。固定为0。 |
errorMsg |
string |
错误说明。固定为"Success"。 |
响应体还可能有result属性,类型为object,其中存储操作结果信息。
| 名称 |
类型 |
含义 |
errorCode |
integer |
错误码。与响应状态码相同。 |
errorMsg |
string |
错误说明。 |
服务提供的主要操作如下:
对视频进行分类。
POST /video-classification
| 名称 |
类型 |
含义 |
是否必填 |
video |
string |
服务可访问的视频文件的URL或视频文件内容的Base64编码结果。 |
是 |
inferenceParams |
object |
推理参数。 |
否 |
inferenceParams的属性如下:
| 名称 |
类型 |
含义 |
是否必填 |
topK |
integer |
结果中将只保留得分最高的topK个类别。 |
否 |
- 请求处理成功时,响应体的
result具有如下属性:
| 名称 |
类型 |
含义 |
categories |
array |
视频类别信息。 |
video |
string |
视频分类结果图。视频为JPEG格式,使用Base64编码。 |
categories中的每个元素为一个object,具有如下属性:
| 名称 |
类型 |
含义 |
id |
integer |
类别ID。 |
name |
string |
类别名称。 |
score |
number |
类别得分。 |
result示例如下:
{
"categories": [
{
"id": 5,
"name": "兔子",
"score": 0.93
}
],
"video": "xxxxxx"
}
多语言调用服务示例
Python
import base64
import requests
API_URL = "http://localhost:8080/video-classification" # 服务URL
video_path = "./demo.mp4"
output_video_path = "./out.mp4"
# 对本地视频进行Base64编码
with open(video_path, "rb") as file:
video_bytes = file.read()
video_data = base64.b64encode(video_bytes).decode("ascii")
payload = {"video": video_data} # Base64编码的文件内容或者视频URL
# 调用API
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 outputImagePath = "./out.mp4";
httplib::Headers headers = {
{"Content-Type", "application/json"}
};
// 对本地视频进行Base64编码
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 encodedImage = base64::to_base64(bufferStr);
nlohmann::json jsonObj;
jsonObj["video"] = encodedImage;
std::string body = jsonObj.dump();
// 调用API
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"];
encodedImage = result["video"];
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 video 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/video-classification"; // 服务URL
String videoPath = "./demo.mp4"; // 本地视频
String outputImagePath = "./out.mp4"; // 输出视频
// 对本地视频进行Base64编码
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); // Base64编码的文件内容或者视频URL
// 创建 OkHttpClient 实例
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();
// 调用API并处理接口返回数据
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(outputImagePath)) {
fos.write(videoBytes);
}
System.out.println("Output video 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/video-classification"
videoPath := "./demo.mp4"
outputImagePath := "./out.mp4"
// 对本地视频进行Base64编码
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} // Base64编码的文件内容或者视频URL
payloadBytes, err := json.Marshal(payload)
if err != nil {
fmt.Println("Error marshaling payload:", err)
return
}
// 调用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()
// 处理接口返回数据
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(outputImagePath, outputImageData, 0644)
if err != nil {
fmt.Println("Error writing video to file:", err)
return
}
fmt.Printf("Image saved at %s.mp4\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/video-classification";
static readonly string videoPath = "./demo.mp4";
static readonly string outputImagePath = "./out.mp4";
static async Task Main(string[] args)
{
var httpClient = new HttpClient();
// 对本地视频进行Base64编码
byte[] videoBytes = File.ReadAllBytes(videoPath);
string video_data = Convert.ToBase64String(videoBytes);
var payload = new JObject{ { "video", video_data } }; // Base64编码的文件内容或者视频URL
var content = new StringContent(payload.ToString(), Encoding.UTF8, "application/json");
// 调用API
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(outputImagePath, outputImageBytes);
Console.WriteLine($"Output video 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/video-classification'
const videoPath = './demo.mp4'
const outputImagePath = "./out.mp4";
let config = {
method: 'POST',
maxBodyLength: Infinity,
url: API_URL,
data: JSON.stringify({
'video': encodeImageToBase64(videoPath) // Base64编码的文件内容或者视频URL
})
};
// 对本地视频进行Base64编码
function encodeImageToBase64(filePath) {
const bitmap = fs.readFileSync(filePath);
return Buffer.from(bitmap).toString('base64');
}
// 调用API
axios.request(config)
.then((response) => {
// 处理接口返回数据
const result = response.data["result"];
const videoBuffer = Buffer.from(result["video"], 'base64');
fs.writeFile(outputImagePath, videoBuffer, (err) => {
if (err) throw err;
console.log(`Output video saved at ${outputImagePath}`);
});
console.log("\nCategories:");
console.log(result["categories"]);
})
.catch((error) => {
console.log(error);
});
PHP
<?php
$API_URL = "http://localhost:8080/video-classification"; // 服务URL
$video_path = "./demo.mp4";
$output_video_path = "./out.mp4";
// 对本地视频进行Base64编码
$video_data = base64_encode(file_get_contents($video_path));
$payload = array("video" => $video_data); // Base64编码的文件内容或者视频URL
// 调用API
$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"]);
?>