我想使用Python和opencv从多个视频长度中提取恒定数量的帧'n'。如何在Python中使用opencv?
例如在5秒的视频中,我想从该视频中平均提取10帧。
答案 0 :(得分:0)
采用的代码来自: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)
答案 1 :(得分:0)
您可以获得帧的总数,将其除以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()
答案 2 :(得分:0)
您可以尝试使用此功能:
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帧作为恒定输出。