Python:在不同长度的视频中提取“n”帧

我想使用 Python 和 opencv 从多个长度的视频中提取恒定数量的帧“n”。如何使用 opencv 和 Python 做到这一点?

例如,在一个 5 秒的视频中,我想从这个视频中均匀地提取 10 帧。


红颜莎娜
浏览 273回答 3
3回答

慕容708150

代码来自:How to turn a video into numpy array?import numpy as npimport cv2cap = cv2.VideoCapture('sample.mp4')frameCount = 10frameWidth = 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 = 0ret = Truewhile (fc < frameCount&nbsp; and ret):&nbsp; &nbsp; ret, buf[fc] = cap.read()&nbsp; &nbsp; fc += 1cap.release()print(buf.shape) # (10, 540, 960, 3)

眼眸繁星

您可以获得总帧数,将其除以 n 以获得您在每一步跳过的帧数,然后读取帧数&nbsp; &nbsp; vidcap = cv2.VideoCapture(video_path)&nbsp; &nbsp; total_frames = vidcap.get(cv2.CAP_PROP_FRAME_COUNT)&nbsp; &nbsp; frames_step = total_frames//n&nbsp; &nbsp; for i in range(n):&nbsp; &nbsp; &nbsp; &nbsp; #here, we set the parameter 1 which is the frame number to the frame (i*frames_step)&nbsp; &nbsp; &nbsp; &nbsp; vidcap.set(1,i*frames_step)&nbsp; &nbsp; &nbsp; &nbsp; success,image = vidcap.read()&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; #save your image&nbsp; &nbsp; &nbsp; &nbsp; cv2.imwrite(path,image)&nbsp; &nbsp; vidcap.release()

萧十郎

你可以试试这个功能:def rescaleFrame(inputBatch, scaleFactor = 50):&nbsp; &nbsp; ''' returns constant frames for any length video&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; scaleFactor: number of constant frames to get.&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; inputBatch : frames present in the video.&nbsp;&nbsp; &nbsp; '''&nbsp; &nbsp; if len(inputBatch) < 1:&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; """ This is to rescale the frames to specific length considering almost all the data in the batch&nbsp; """&nbsp;&nbsp; &nbsp; skipFactor = len(inputBatch)//scaleFactor&nbsp; &nbsp; 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:&nbsp; &nbsp;if not ret:&nbsp; &nbsp; &nbsp; &nbsp;print('no frames')&nbsp; &nbsp; &nbsp; &nbsp;break&nbsp; &nbsp;&nbsp; &nbsp;ret, frame = cap.read()&nbsp; &nbsp;frames.append(frame)''' to get the constant frames from varying number of frames, call the rescaleFrame() function '''outputFrames = rescaleFrames(inputBatch=frames, scaleFactor = 45)输出:这将返回 45 帧作为恒定输出。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python