Skip to content

Instantly share code, notes, and snippets.

@andrewgiessel
Created August 13, 2012 23:20
Show Gist options
  • Save andrewgiessel/3344758 to your computer and use it in GitHub Desktop.
Save andrewgiessel/3344758 to your computer and use it in GitHub Desktop.
Embedded playing of numpy arrays in an Ipython notebook
from IPython.display import HTML
import subprocess
import tempfile
from PIL import Image
def playNPArray(array, frameRate = 6):
# ffmpeg is fussy- images must be in the right format to encode right
uint8_array = np.uint8(array.astype('float').copy() / float(array.max()) * 2**8-1)
fileName = 'temp'
temp_dir = tempfile.mkdtemp()
# save the jpeg frames
for i in range(uint8_array.shape[2]):
im = Image.fromarray(uint8_array[:,:,i])
im.save(os.path.join(temp_dir, '%s_%06d.jpg' % (fileName, i)), format='jpeg')
# encode the video
command = 'ffmpeg -y -r %s -i %s' % (frameRate, fileName) + '_%06d.jpg ' + '%s.webm' % fileName
handle = subprocess.Popen(command, shell=True, cwd=temp_dir)
handle.wait()
# build the appropriate html from the video file
video = open(os.path.join(temp_dir, 'temp.webm'), 'rb').read()
video_encoded = video.encode('base64')
video_tag = '<video controls alt="test" src="data:video/webm;base64,{0}">'.format(video_encoded)
# kill the temp files
subprocess.Popen('rm -rf ' + temp_dir, shell=True)
return HTML(data=video_tag)
playNPArray(np.random.random((100,100,10)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment