Reputation: 79
I want to extract constant number of frames 'n' from multiple length of video using Python and opencv. How to do that using opencv with Python?
e.g. in a 5second video, I want to extract 10 frames from this video evenly.
Upvotes: 3
Views: 2654
Reputation: 3086
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.
Upvotes: 0
Reputation: 363
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
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()
Upvotes: 0
Reputation: 2701
Code adopted from: 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)
Upvotes: 1