Created
September 6, 2023 07:21
-
-
Save realphongha/f8db807a9a0fc512ed146786e684cd43 to your computer and use it in GitHub Desktop.
Get FPS of a video using Python, OpenCV and Ffmpeg.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cv2 | |
import ffmpeg | |
def get_fps_fast(video_path): | |
# using only opencv-python package, fast but can be inaccurate | |
cap = cv2.VideoCapture(video_path) | |
if not cap.isOpened(): | |
raise Exception(f"Cannot open {video_path}") | |
fps = cap.get(cv2.CAP_PROP_FPS) | |
cap.release() | |
return fps | |
def get_fps_accurate(video_path): | |
# using opencv-python and ffmpeg-python packages, slow but more accurate | |
cap = cv2.VideoCapture(video_path) | |
if not cap.isOpened(): | |
raise Exception(f"Cannot open {video_path}") | |
metadata = ffmpeg.probe(video_path) | |
duration = metadata["format"]["duration"] | |
duration = float(duration) | |
if duration == 0: | |
raise ZeroDivisionError("Video duration is zero!") | |
frames = 0 | |
while True: | |
ret, _ = cap.read() | |
if not ret: | |
break | |
frames += 1 | |
cap.release() | |
return frames / duration | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment