为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

红颜莎娜 2021-11-09 18:31:38
我想使用 Python 和 opencv 从多个长度的视频中提取恒定数量的帧“n”。如何使用 opencv 和 Python 做到这一点?例如,在一个 5 秒的视频中,我想从这个视频中均匀地提取 10 帧。
查看完整描述

3 回答

?
慕容708150

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)


查看完整回答
反对 回复 2021-11-09
?
眼眸繁星

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()


查看完整回答
反对 回复 2021-11-09
?
萧十郎

TA贡献1815条经验 获得超12个赞

你可以试试这个功能:


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 帧作为恒定输出。


查看完整回答
反对 回复 2021-11-09
  • 3 回答
  • 0 关注
  • 234 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信