You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用OpenCV直接提取视频指定帧而非遍历整个视频?

直接跳转到目标帧的解决方案

你可以使用OpenCV的cv2.VideoCapture.set()方法,通过指定cv2.CAP_PROP_POS_FRAMES参数直接定位到目标帧,无需逐帧遍历,大幅减少长视频的处理时间。

修改后的代码

import cv2
import os

video = cv2.VideoCapture(str(input_files[0]))
fps = video.get(cv2.CAP_PROP_FPS)

print("FPS: " + str(fps))

minutes, seconds = indexImageTimeStamp.split(':')
targetFrame = int(minutes) * 60 * int(fps) + int(seconds) * int(fps)
print('targetframe ', str(targetFrame))

# 直接设置到目标帧位置
video.set(cv2.CAP_PROP_POS_FRAMES, targetFrame)
success, frame = video.read()

if success:
    cv2.imwrite(os.path.join('path', 'indexframe.jpg'), frame)
else:
    print("无法读取目标帧")

# 释放视频资源
video.release()

注意事项

  • 部分视频编码格式(如流媒体类编码)不支持精确帧定位,调用set()后可能跳转到最近的关键帧而非目标帧。这种情况下,可在设置位置后微调帧位置:
    # 修正帧位置偏差
    actual_frame = video.get(cv2.CAP_PROP_POS_FRAMES)
    while actual_frame < targetFrame and success:
        success, frame = video.read()
        actual_frame += 1
    
  • 确保fps取值准确,避免因视频实际帧率与读取值存在误差导致定位偏差。

内容的提问来源于stack exchange,提问作者Chud37

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 07:40:26