Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Display movie file with support for browsing forward and backward through frames with a slider or arrow keys.
#!/usr/bin/env python3
"""
Display movie file with support for browsing forward and backward through frames
with a slider or arrow keys.
"""
import argparse
import datetime
import os
import imageio as im
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
parser = argparse.ArgumentParser(description='Browse frames in movie file')
parser.add_argument('file_name', help='input movie file')
args = parser.parse_args()
file_name = args.file_name
vid = im.get_reader(file_name, 'ffmpeg')
metadata = vid.get_meta_data()
st = os.stat(file_name)
start_time = datetime.datetime.fromtimestamp(st.st_mtime)-\
pd.to_timedelta(metadata['nframes']/metadata['fps'], unit='s')
# Set up figure:
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111)
ax.axis('off')
ax.autoscale(True)
plt.subplots_adjust(left=0.25, bottom=0.25)
# Render first frame:
frame = 0
axim = ax.imshow(vid.get_data(0))
# Create the slider:
axframe = plt.axes([0.25, 0.1, 0.65, 0.04])
sframe = Slider(axframe, 'Frame', 0, metadata['nframes'], valinit=0, valfmt='%d')
# Update rendered frame:
def update(val):
frame = int(np.floor(sframe.val))
axim.set_data(vid.get_data(frame))
ax.set_title(str(start_time+pd.to_timedelta(frame/metadata['fps'], unit='s')))
fig.canvas.draw()
# Move forward or backward in movie:
def arrow_key_image_ctrl(event):
if event.key == 'left':
if round(sframe.val) <= sframe.valmin:
pass
else:
sframe.set_val(sframe.val-1)
update(sframe.val)
elif event.key == 'right':
if round(sframe.val) >= sframe.valmax-1:
pass
else:
sframe.set_val(sframe.val+1)
update(sframe.val)
else:
print('unrecognized event')
fig.canvas.mpl_connect('key_release_event', arrow_key_image_ctrl)
# Connect callback to slider:
sframe.on_changed(update)
# Set title:
update(0)
# Display:
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.