Skip to content

Instantly share code, notes, and snippets.

@ngaloppo
Created March 23, 2016 18:28
Show Gist options
  • Save ngaloppo/73a77db7dd9a0dd06ec1 to your computer and use it in GitHub Desktop.
Save ngaloppo/73a77db7dd9a0dd06ec1 to your computer and use it in GitHub Desktop.
OpenCV video information extraction
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import logging
import cv2 as cv
import argparse
import os
log = logging.getLogger('test_video')
def open_video_stream(filename, return_props=False):
try:
with open(filename, 'rb') as f:
pass
except IOError as e:
raise RuntimeError(e)
cap = cv.VideoCapture(filename)
num_frames = int(cap.get(cv.CAP_PROP_FRAME_COUNT))
frame_rate = cap.get(cv.CAP_PROP_FPS)
if not cap.isOpened():
raise RuntimeError(
"Failed to open video file. Is ffmpeg properly configured?")
log.info("Loading {} [{} frames]...".format(filename, num_frames))
if return_props:
return cap, {'num_frames': num_frames, 'frame_rate': frame_rate}
else:
return cap
if __name__ == '__main__':
try:
import coloredlogs
coloredlogs.install(level=logging.INFO)
except:
logging.basicConfig(level=logging.INFO)
## Command-line arguments
parser = argparse.ArgumentParser(description='Video Info')
parser.add_argument('filename', metavar='video.mp4')
args = parser.parse_args()
try:
video_stream, props = open_video_stream(args.filename, return_props=True)
print("OpenCV version: {}".format(cv.__version__))
print("{}: {} fps, {} frames".format(args.filename, props['frame_rate'], props['num_frames']))
count = 0
while True:
ts = video_stream.get(cv.CAP_PROP_POS_MSEC)
fr = video_stream.get(cv.CAP_PROP_POS_FRAMES)
ret, frame = video_stream.read()
if not ret:
break
print("{} - {}/{} : {}".format(count, fr, props['num_frames'], ts))
count += 1
print("OpenCV version: {}".format(cv.__version__))
print("{}: {} fps, {} frames".format(args.filename, props['frame_rate'], props['num_frames']))
print("Number of frames returned by OpenCV: {}".format(count))
video_stream.release()
except Exception as e:
log.exception(e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment