【发布时间】:2020-07-02 13:49:30
【问题描述】:
我想使用 Python 和 opencv 从多个长度的视频中提取恒定数量的帧“n”。如何在 Python 中使用 opencv?
例如在一个 5 秒的视频中,我想从这个视频中平均提取 10 帧。
【问题讨论】:
-
将视频中的所有帧读入一个数组,然后切片。
-
如何执行切片操作
我想使用 Python 和 opencv 从多个长度的视频中提取恒定数量的帧“n”。如何在 Python 中使用 opencv?
例如在一个 5 秒的视频中,我想从这个视频中平均提取 10 帧。
【问题讨论】:
代码来自:How to turn a video into numpy array?
import numpy as np
import cv2
cap = cv2.VideoCapture('sample.mp4')
frameCount = 10
frameWidth = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frameHeight = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
buf = np.empty((frameCount, frameHeight, frameWidth, 3), np.dtype('uint8'))
fc = 0
ret = True
while (fc < frameCount and ret):
ret, buf[fc] = cap.read()
fc += 1
cap.release()
print(buf.shape) # (10, 540, 960, 3)
【讨论】:
您可以获得总帧数,将其除以 n 得到您将在每一步跳过的帧数,然后读取帧数
vidcap = cv2.VideoCapture(video_path)
total_frames = vidcap.get(cv2.CAP_PROP_FRAME_COUNT)
frames_step = total_frames//n
for i in range(n):
#here, we set the parameter 1 which is the frame number to the frame (i*frames_step)
vidcap.set(1,i*frames_step)
success,image = vidcap.read()
#save your image
cv2.imwrite(path,image)
vidcap.release()
【讨论】:
你可以试试这个功能:
def rescaleFrame(inputBatch, scaleFactor = 50):
''' returns constant frames for any length video
scaleFactor: number of constant frames to get.
inputBatch : frames present in the video.
'''
if len(inputBatch) < 1:
return
""" This is to rescale the frames to specific length considering almost all the data in the batch """
skipFactor = len(inputBatch)//scaleFactor
return [inputBatch[i] for i in range(0, len(inputBatch), skipFactor)][:scaleFactor]
''' read the frames from the video '''
frames = []
cap = cv2.VideoCapture('sample.mp4')
ret, frame = cap.read()
while True:
if not ret:
print('no frames')
break
ret, frame = cap.read()
frames.append(frame)
''' to get the constant frames from varying number of frames, call the rescaleFrame() function '''
outputFrames = rescaleFrames(inputBatch=frames, scaleFactor = 45)
输出: 这将返回 45 帧作为恒定输出。
【讨论】: