简体   繁体   English

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

[英]Python: Extract 'n' frames in different length of video

I want to extract constant number of frames 'n' from multiple length of video using Python and opencv.我想使用 Python 和 opencv 从多个长度的视频中提取恒定数量的帧“n”。 How to do that using opencv with Python?如何使用 opencv 和 Python 做到这一点?

eg in a 5second video, I want to extract 10 frames from this video evenly.例如,在一个 5 秒的视频中,我想从这个视频中均匀地提取 10 帧。

Code adopted from: How to turn a video into numpy array?代码来自: 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)

You can get the total number of frames, divide it by n to have the number of frames you'll skip at each step and then read the frames您可以获得总帧数,将其除以 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()

you can try this function:你可以试试这个功能:

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)

Output : This will return 45 frames as constant output.输出:这将返回 45 帧作为恒定输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM