准备把视频交给图片识别模型时,可以先抽取代表帧,并为每张图保留它在视频中的位置。这样模型说到某个场景时,可以回到视频核对。本文做约一秒一帧的入门抽取,识别模型调用需要另行接入。
先确认抽帧会遗漏什么
连续动作、闪过的字幕和短暂小目标可能落在两张抽取帧之间。先明确你想找的是长时间场景还是瞬间事件;后一类不能依赖稀疏抽帧做完整判定。

python -m pip install opencv-python-headless
准备 clip.mp4,保存代码为 sample_frames.py,运行 python sample_frames.py。本地用自行生成的恒定 12 FPS、48 帧测试视频运行了该代码,保存 4 张代表帧;未把这些帧交给 AI 模型识别。
保存帧文件与位置清单
from pathlib import Path
import csv
import math
import cv2
capture = cv2.VideoCapture("clip.mp4")
if not capture.isOpened():
raise ValueError("clip.mp4 cannot be opened")
fps = capture.get(cv2.CAP_PROP_FPS)
if not math.isfinite(fps) or fps <= 0:
capture.release()
raise ValueError("usable FPS metadata is missing")
step = max(1, round(fps)) # about one second for constant-frame-rate video
output = Path("frames")
output.mkdir(exist_ok=True)
index = 0
saved = 0
try:
with (output / "index.csv").open("w", newline="", encoding="utf-8-sig") as f:
writer = csv.writer(f)
writer.writerow(["frame_index", "time_seconds", "time_source", "file"])
while True:
ok, frame = capture.read()
if not ok:
break
if index % step == 0:
ms = capture.get(cv2.CAP_PROP_POS_MSEC)
reliable_value = math.isfinite(ms) and (ms > 0 or index == 0)
seconds = ms / 1000 if reliable_value else index / fps
source = "decoder" if reliable_value else "fps_estimate"
name = f"frame_{index:06d}.jpg"
if not cv2.imwrite(str(output / name), frame):
raise OSError("frame file was not written")
writer.writerow([index, round(seconds, 3), source, name])
saved += 1
index += 1
finally:
capture.release()
print("decoded_frames", index, "saved_frames", saved, "fps", fps)
代码每次解码一帧,按约一秒的帧步长选图。解码器提供的时间值写作 decoder;取不到正时间值时才按 FPS 估算,并标记 fps_estimate,不把估算当成精确时间。
如何检查输入到输出的对应
index.csv 的数据行数应与 saved_frames 和本批生成的图片数量一致。抽查开头、中间、结尾的图,回到播放器附近时间确认画面相符。
若视频帧率可变,按固定帧步长抽取不能保证精确一秒间隔;若帧解码中断,也不能把循环结束当成整段视频无损读取。对照播放器的完整时长和结尾,必要时换能读取实际时间戳的处理路线。
交给识别模型时保留哪些字段
保留原视频编号、frame_index、time_seconds、time_source 和图片路径。模型回答中的事件只对应它实际看到的帧,不概括成整个视频必然没有其他事件。
重复运行前选择新的 frames 输出目录或保存上一批清单,否则旧图片可能留在目录中干扰数量核对。需要覆盖短事件时减小步长并检查成本与信息遗漏,不能只增加模型提示词。
资料与适用范围
本文依据 2026 年 10 月 1 日读取的项目资料编写。安装后请记录实际依赖版本;版本升级时先用小样本核对接口和输出。
Ai菜鸟网。发布者:AI小管家,转载请注明出处:https://www.alyyhw.com/30842.html