📌 總體流程概覽
視頻文件 (.mp4)↓
關鍵幀抽取(FFmpeg / SceneDetect)↓
幀圖像(.jpg)↓
圖像模型提取特征(CLIP / CNN / ViT)↓
多幀聚合成視頻向量(均值池化等)↓
向量庫 / 推薦系統模型
🎯 特征提取推薦:使用 OpenAI 的 CLIP 模型
CLIP(Contrastive Language-Image Pretraining)適合推薦系統做跨模態建模,對視頻封面幀或場景幀提取效果非常好。
? 1. 安裝依賴
pip install torch torchvision ftfy regex tqdm
pip install git+https://github.com/openai/CLIP.git
? 2. 提取單幀圖像的特征向量
import torch
import clip
from PIL import Imagedevice = "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()
? 3. 批量處理目錄下的圖像幀
import os
import numpy as npdef 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"
}