我有以下代码,它使用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(cv2.CAP_PROP_FRAME_COUNT)
这里 7 是 prop-Id。您可以在这里找到更多信息http://docs.opencv.org/2.4/modules/highgui/doc/reading_and_writing_images_and_video.html
之后就可以设置帧数了,假设我要提取第100帧
cap.set(cv2.CAP_PROP_FRAME_COUNT, 100)
ret, frame = cap.read()
cv2.imwrite("path_where_to_save_image", frame)
这是我的第一篇文章,所以如果我没有完全遵循协议,请不要攻击我。我只是想回复 June Wang,以防万一她不知道如何设置要提取的帧数,或者万一其他人偶然发现这个线程并提出这个问题:
解决方案是好的 ol' for 循环:
vid = cv2.VideoCapture(video_path)
for i in range(start_frame, start_frame+how_many_frames_you_want):
vid.set(1, i)
ret, still = vid.read()
cv2.imwrite(f'{video_path}_frame{i}.jpg', still)