gpt4 book ai didi

python - 从python中的VideoCapture opencv获取特定帧

转载 作者:太空狗 更新时间:2023-10-29 21:22:00 25 4
gpt4 key购买 nike

我有以下代码,它通过在 python 中使用 opencv 中的 VideoCapture 库从视频中连续获取所有帧:

import cv2

def frame_capture:
cap = cv2.VideoCapture("video.mp4")
while not cap.isOpened():
cap = cv2.VideoCapture("video.mp4")
cv2.waitKey(1000)
print "Wait for the header"

pos_frame = cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES)
while True:
flag, frame = cap.read()
if flag:
# The frame is ready and already captured
cv2.imshow('video', frame)
pos_frame = cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES)
print str(pos_frame)+" frames"
else:
# The next frame is not ready, so we try to read it again
cap.set(cv2.cv.CV_CAP_PROP_POS_FRAMES, pos_frame-1)
print "frame is not ready"
# It is better to wait for a while for the next frame to be ready
cv2.waitKey(1000)

if cv2.waitKey(10) == 27:
break
if cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES) == cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT):
# If the number of captured frames is equal to the total number of frames,
# we stop
break

但我想抓取视频中特定时间戳中的特定帧。

我怎样才能做到这一点?

最佳答案

您可以使用 VideoCapture 的 set() 函数。

您可以计算总帧数:

cap = cv2.VideoCapture("video.mp4")
total_frames = cap.get(7)

这里的 7 是 prop-Id。您可以在这里找到更多信息 http://docs.opencv.org/2.4/modules/highgui/doc/reading_and_writing_images_and_video.html

然后你可以设置帧数,假设我想提取第100帧

cap.set(1, 100)
ret, frame = cap.read()
cv2.imwrite("path_where_to_save_image", frame)

关于python - 从python中的VideoCapture opencv获取特定帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33523751/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com