问题描述
我有以下代码,该代码通过在python的opencv中使用VideoCapture库连续从视频中获取所有帧:
I have the following code, which continuously fetches all the frames from a video by using VideoCapture library in opencv in python:
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
但是我想在视频的特定时间戳中获取特定的帧.
But I want to grab a specific frame in a specific timestamp in the video.
我该如何实现?
推荐答案
您可以使用VideoCapture的set()函数.
You can use set() function of VideoCapture.
您可以计算总帧数:
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
Here 7 is the prop-Id. You can find more here http://docs.opencv.org/2.4/modules/highgui/doc/reading_and_writing_images_and_video.html
之后您可以设置帧号,假设我要提取第100帧
After that you can set the frame number, suppose i want to extract 100th frame
cap.set(1, 100)
ret, frame = cap.read()
cv2.imwrite("path_where_to_save_image", frame)
这篇关于在Python中从VideoCapture opencv获取特定帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!