Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Extract 'n' frames in different length of video

Tags:

python

opencv

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.

like image 726
lai hang Avatar asked May 03 '26 12:05

lai hang


1 Answers

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)
like image 74
keineahnung2345 Avatar answered May 06 '26 02:05

keineahnung2345



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!