从 python 中的视频中获取特定的帧序列

Getting a specific sequence of frames from video in python

我需要从视频中提取特定的帧序列,例如我想要

例如每 10 帧提取一次 (frame_1,frame_10,frame_20,...)。我

使用下面的代码但它提取了所有帧,知道如何做到这一点吗?

import cv2
vidcap = cv2.VideoCapture('big_buck_bunny_720p_5mb.mp4')
success,image = vidcap.read()
count = 0
success = True
while success:

   cv2.imwrite("frame%d.jpg" % count, image)     # save frame as JPEG file
   success,image = vidcap.read()

count += 1

使用帧数的modulo

import cv2
vidcap = cv2.VideoCapture('big_buck_bunny_720p_5mb.mp4')
success,image = vidcap.read()
count = 0
frame = 0 #after first frame read, so frame 0 will be saved, next every 10th
success = True
while success:

   if frame % 10 == 0:
       cv2.imwrite("frame%d.jpg" % count, image)     # save frame as JPEG file
       count += 1
   success,image = vidcap.read()
   frame += 1

只是为了添加另一个解决方案,您可以使用 set function and CAP_PROP_POS_FRAMES 属性 id 像这样在 10 帧之后获取帧:

import cv2
vidcap = cv2.VideoCapture('big_buck_bunny_720p_5mb.mp4')
success,image = vidcap.read()
count = 0
success = True
while success:
   cv2.imwrite("frame%d.jpg" % count, image)     # save frame as JPEG file
   success,image = vidcap.read()
   count += 1
   vidcap.set(cv2.CAP_PROP_POS_FRAMES, count * 10 )

与其他答案相比,这可能会给您带来性能优势,因为它不会读取每一帧,但如果它是来自摄像机的视频,我认为这个解决方案不会做任何事情,而另一个会。