视频文件 (.mp4)
↓
关键帧抽取(FFmpeg / SceneDetect)
↓
帧图像(.jpg)
↓
图像模型提取特征(CLIP / CNN / ViT)
↓
多帧聚合成视频向量(均值池化等)
↓
向量库 / 推荐系统模型
CLIP(Contrastive Language-Image Pretraining)适合推荐系统做跨模态建模,对视频封面帧或场景帧提取效果非常好。
pip install torch torchvision ftfy regex tqdm
pip install git+https://github.com/openai/CLIP.git
import torch
import clip
from PIL import Image
device = "cuda" if torch.cuda.is_available() else "cpu"
model, preprocess = clip.load("ViT-B/32", device=device)
def extract_clip_feature(image_path):
image = preprocess(Image.open(image_path)).unsqueeze(0).to(device)
with torch.no_grad():
features = model.encode_image(image)
return features.cpu().numpy().flatten()
import os
import numpy as np
def extract_dir_features(frame_dir, max_frames=5):
frame_list = sorted([os.path.join(frame_dir, f) for f in os.listdir(frame_dir) if f.endswith('.jpg')])
frame_list = frame_list[:max_frames] # 可选:限制帧数
features = [extract_clip_feature(p) for p in frame_list]
return np.mean(features, axis=0) # 聚合为视频向量
方法 | 说明 |
---|---|
均值池化 | 简单平均(推荐,鲁棒) |
最大池化 | 每维取最大值 |
attention聚合 | 可加入权重建模(需模型支持) |
LSTM | 融合多帧序列,捕捉时间关系(高级) |
格式 | 说明 |
---|---|
.npy / .npz |
NumPy 向量存储(推荐) |
.pkl |
Python 对象存储 |
CSV / JSON | 可读性高,但体积大 |
Faiss / Milvus | 向量库,支持 ANN 检索 |
.npy
示例:np.save('video_001_vector.npy', video_vector)
使用 ViT-B/32
,每帧输出:
(512,)
(512,)
可直接用于用户-视频召回、相似度检索、排序模型等模块。
你可以配合视频标签、标题、评论等文本用 CLIP 提 text_features
:
text = clip.tokenize(["a man driving a car"]).to(device)
text_feat = model.encode_text(text)
再与图像特征 cosine_similarity
计算 图文相关性分数。
{
"video_id": "cars_001",
"clip_vector": [0.123, 0.345, ..., 0.890], // 长度512
"source": "scene_ffmpeg",
"timestamp": "2025-06-26T12:00:00Z"
}