前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【人工智能】Transformers之Pipeline(十):视频分类(video-classification)

【人工智能】Transformers之Pipeline(十):视频分类(video-classification)

作者头像
LDG_AGI
发布2024-08-20 11:04:24
1490
发布2024-08-20 11:04:24
举报
文章被收录于专栏:人工智能极简应用

一、引言

pipeline(管道)是huggingface transformers库中一种极简方式使用大模型推理的抽象,将所有大模型分为音频(Audio)、计算机视觉(Computer vision)、自然语言处理(NLP)、多模态(Multimodal)等4大类,28小类任务(tasks)。共计覆盖32万个模型

今天介绍CV计算机视觉的第六篇:视频分类(video-classification),在huggingface库内有1100个视频分类模型。

二、视频分类(video-classification)

2.1 概述

视频分类是为整个视频分配标签或类别的任务。每个视频预计只有一个类别。视频分类模型将视频作为输入,并返回关于该视频属于哪个类别的预测。

2.2 技术原理

视频分类(video-classification)最典型的模型莫过于微软的xclip系列,xclip为clip模型的拓展,采用(视频-文本)进行对比学习训练。微软提供了包括microsoft/xclip-base-patch32、microsoft/xclip-base-patch16等不同块分辨率训练的模型。比如microsoft/xclip-base-patch32,块分辨率大小为32,使用每段视频 8 帧进行训练,分辨率为 224x224。详细论文可参考《Expanding Language-Image Pretrained Models for General Video Recognition》

2.3 应用场景

  • 内容审查与过滤:自动识别视频内容,过滤非法、暴力、成人内容,确保平台合规。
  • 视频检索:用户可以通过分类标签快速找到感兴趣的视频,提高检索效率。
  • 教育与培训:将教育视频按科目、难度等分类,便于学习者系统学习。
  • 娱乐与直播:分类管理直播内容,如游戏、音乐、生活等,便于观众选择观看。
  • 体育赛事分析:通过分类快速定位到特定比赛类型或运动员表现分析。

2.4 pipeline参数

2.4.1 pipeline对象实例化参数

  • modelPreTrainedModelTFPreTrainedModel)— 管道将使用其进行预测的模型。 对于 PyTorch,这需要从PreTrainedModel继承;对于 TensorFlow,这需要从TFPreTrainedModel继承。
  • image_processor ( BaseImageProcessor ) — 管道将使用的图像处理器来为模型编码数据。此对象继承自 BaseImageProcessor
  • modelcardstrModelCard可选) — 属于此管道模型的模型卡。
  • frameworkstr可选)— 要使用的框架,"pt"适用于 PyTorch 或"tf"TensorFlow。必须安装指定的框架。
  • taskstr,默认为"")— 管道的任务标识符。
  • num_workersint可选,默认为 8)— 当管道将使用DataLoader(传递数据集时,在 Pytorch 模型的 GPU 上)时,要使用的工作者数量。
  • batch_sizeint可选,默认为 1)— 当管道将使用DataLoader(传递数据集时,在 Pytorch 模型的 GPU 上)时,要使用的批次的大小,对于推理来说,这并不总是有益的,请阅读使用管道进行批处理
  • args_parserArgumentHandler可选) - 引用负责解析提供的管道参数的对象。
  • deviceint可选,默认为 -1)— CPU/GPU 支持的设备序号。将其设置为 -1 将利用 CPU,设置为正数将在关联的 CUDA 设备 ID 上运行模型。您可以传递本机torch.devicestr
  • torch_dtypestrtorch.dtype可选) - 直接发送model_kwargs(只是一种更简单的快捷方式)以使用此模型的可用精度(torch.float16,,torch.bfloat16...或"auto"
  • binary_outputbool可选,默认为False)——标志指示管道的输出是否应以序列化格式(即 pickle)或原始输出数据(例如文本)进行。
2.4.2 pipeline对象使用参数

  • videostrList[str])——管道处理三种类型的视频:
    • 包含指向视频的 http 链接的字符串
    • 包含视频本地路径的字符串

    管道可以接受单个视频或一批视频,然后必须将其作为字符串传递。一批视频必须全部采用相同的格式:全部为 http 链接或全部为本地路径。

  • top_kint可选,默认为 5)— 管道将返回的顶部标签数。如果提供的数字高于模型配置中可用的标签数,则将默认为标签数。
  • num_framesint可选,默认为self.model.config.num_frames)— 从视频中采样的用于运行分类的帧数。如果未提供,则默认为模型配置中指定的帧数。
  • frame_sampling_rate ( int可选,默认为 1) — 用于从视频中选择帧的采样率。如果未提供,则默认为 1,即将使用每一帧。

2.4 pipeline实战

使用hf_hub_download下载或使用本地视频:

亲测pipeline不能用,于是使用Auto模型方法,与使用Autotokenizer处理文本不同,对于图片的处理使用AutoImageProcessor(处理视频的本质就是先将视频拆帧成图片,再对图片进行处理)

代码语言:javascript
复制
import os
os.environ["HF_ENDPOINT"] = "https://hf-mirror.com"
os.environ["CUDA_VISIBLE_DEVICES"] = "2"

import av
import torch
import numpy as np

from transformers import AutoImageProcessor, VideoMAEForVideoClassification,TimesformerForVideoClassification
from huggingface_hub import hf_hub_download

np.random.seed(0)

def read_video_pyav(container, indices):
    '''
    通过PyAV库解码视频中的特定帧。
    Decode the video with PyAV decoder.
    Args:
        container (`av.container.input.InputContainer`): PyAV container.
        indices (`List[int]`): List of frame indices to decode.
    Returns:
        result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
    '''
    frames = []
    container.seek(0)
    start_index = indices[0]
    end_index = indices[-1]
    for i, frame in enumerate(container.decode(video=0)):
        if i > end_index:
            break
        if i >= start_index and i in indices:
            frames.append(frame)
    return np.stack([x.to_ndarray(format="rgb24") for x in frames])


def sample_frame_indices(clip_len, frame_sample_rate, seg_len):
    '''
    从视频中按照特定规则采样帧的索引.
    Sample a given number of frame indices from the video.
    Args:
        clip_len (`int`): Total number of frames to sample.
        frame_sample_rate (`int`): Sample every n-th frame.
        seg_len (`int`): Maximum allowed index of sample's last frame.
    Returns:
        indices (`List[int]`): List of sampled frame indices
    '''
    converted_len = int(clip_len * frame_sample_rate)
    end_idx = np.random.randint(converted_len, seg_len)
    start_idx = end_idx - converted_len
    indices = np.linspace(start_idx, end_idx, num=clip_len)
    indices = np.clip(indices, start_idx, end_idx - 1).astype(np.int64)
    return indices


# video clip consists of 300 frames (10 seconds at 30 FPS)
file_path = "./transformers_basketball.avi"
"""
file_path = hf_hub_download(
    repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
)
"""
container = av.open(file_path)

# sample 16 frames
indices = sample_frame_indices(clip_len=16, frame_sample_rate=1, seg_len=container.streams.video[0].frames)
video = read_video_pyav(container, indices)

image_processor = AutoImageProcessor.from_pretrained("MCG-NJU/videomae-base-finetuned-kinetics")
#model = VideoMAEForVideoClassification.from_pretrained("MCG-NJU/videomae-base-finetuned-kinetics")
model = TimesformerForVideoClassification.from_pretrained("facebook/timesformer-base-finetuned-k400")

inputs = image_processor(list(video), return_tensors="pt")

with torch.no_grad():
    outputs = model(**inputs)
    logits = outputs.logits

# model predicts one of the 400 Kinetics-400 classes
predicted_label = logits.argmax(-1).item()
print(model.config.id2label[predicted_label])

执行后,自动下载模型文件,构建索引,拆帧,视频分类预测:​

2.5 模型排名

在huggingface上,我们将视频分类(video-classification)模型按下载量从高到低排序,排在前10的模型主要由微软的xclip、南京大学的videomae、facebook的timesformer、google的vivit等四类模型构成。

三、总结

本文对transformers之pipeline的视频分类(video-classification)从概述、技术原理、pipeline参数、pipeline实战、模型排名等方面进行介绍,读者可以基于pipeline使用代码极简的代码部署计算机视觉中的视频分类(video-classification)模型,应用于视频判别场景。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-08-15,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、引言
  • 二、视频分类(video-classification)
    • 2.1 概述
      • 2.2 技术原理
        • 2.3 应用场景
          • 2.4 pipeline参数
            • 2.4.1 pipeline对象实例化参数
            • 2.4.2 pipeline对象使用参数
          • 2.4 pipeline实战
            • 2.5 模型排名
            • 三、总结
            相关产品与服务
            云直播
            云直播(Cloud Streaming Services,CSS)为您提供极速、稳定、专业的云端直播处理服务,根据业务的不同直播场景需求,云直播提供了标准直播、快直播、云导播台三种服务,分别针对大规模实时观看、超低延时直播、便捷云端导播的场景,配合腾讯云视立方·直播 SDK,为您提供一站式的音视频直播解决方案。
            领券
            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档