3 回答

TA贡献1831条经验 获得超4个赞
代码来自: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)

TA贡献1873条经验 获得超9个赞
您可以获得总帧数,将其除以 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()

TA贡献1815条经验 获得超13个赞
你可以试试这个功能:
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 帧作为恒定输出。
添加回答
举报