如果您愿意升级到 OpenCV 3.0,以下 2 个用例可能会对您有所帮助。这可能适用于早期版本,但我没有尝试过。 如果您希望它捕获帧 a 和帧 b 之间的所有帧,请参考第二个用例并将“desired_frames”替换为:
desired_frames = range(a,b)
首先,导入一些包
import cv2
import math
import numpy as np
每 n 秒捕获一次(这里,n = 5)
#################### Setting up the file ################
videoFile = "Jumanji.mp4"
vidcap = cv2.VideoCapture(videoFile)
success,image = vidcap.read()
#################### Setting up parameters ################
seconds = 5
fps = vidcap.get(cv2.CAP_PROP_FPS) # Gets the frames per second
multiplier = fps * seconds
#################### Initiate Process ################
while success:
frameId = int(round(vidcap.get(1))) #current frame number, rounded b/c sometimes you get frame intervals which aren't integers...this adds a little imprecision but is likely good enough
success, image = vidcap.read()
if frameId % multiplier == 0:
cv2.imwrite("FolderSeconds/frame%d.jpg" % frameId, image)
vidcap.release()
print "Complete"
或者,每 n 帧捕获一次(这里,n = 10)
#################### Setting up the file ################
videoFile = "Jumanji.mp4"
vidcap = cv2.VideoCapture(videoFile)
success,image = vidcap.read()
#################### Setting up parameters ################
#OpenCV is notorious for not being able to good to
# predict how many frames are in a video. The point here is just to
# populate the "desired_frames" list for all the individual frames
# you'd like to capture.
fps = vidcap.get(cv2.CAP_PROP_FPS)
est_video_length_minutes = 3 # Round up if not sure.
est_tot_frames = est_video_length_minutes * 60 * fps # Sets an upper bound # of frames in video clip
n = 5 # Desired interval of frames to include
desired_frames = n * np.arange(est_tot_frames)
#################### Initiate Process ################
for i in desired_frames:
vidcap.set(1,i-1)
success,image = vidcap.read(1) # image is an array of array of [R,G,B] values
frameId = vidcap.get(1) # The 0th frame is often a throw-away
cv2.imwrite("FolderFrames/frame%d.jpg" % frameId, image)
vidcap.release()
print "Complete"
差不多就是这样。
一些不幸的警告...根据您的 opencv 版本(这是为 opencv V3 构建的),您可能需要以不同的方式设置 fps 变量。有关详细信息,请参阅
here。要找出您的版本,您可以执行以下操作:
(major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.')
major_ver