Skip to content

Instantly share code, notes, and snippets.

@SuperDoxin
Created May 8, 2015 18:25
Show Gist options
  • Select an option

  • Save SuperDoxin/cf33daf602156c30b6f2 to your computer and use it in GitHub Desktop.

Select an option

Save SuperDoxin/cf33daf602156c30b6f2 to your computer and use it in GitHub Desktop.
from __future__ import division
import subprocess
from docopt import docopt
import os
import shutil
import tempfile
import json
from pprint import pprint
import time
import numpy
import Image
import ImageTk
import atexit
import Tkinter as tk
import itertools
def grouper(n, iterable):
it = iter(iterable)
while True:
chunk = tuple(itertools.islice(it, n))
if not chunk:
return
yield chunk
def video_get_size(fname):
p=subprocess.Popen(["avprobe","-of","json","-show_streams","-loglevel","warning",fname],stdout=subprocess.PIPE)
data=json.load(p.stdout)
width,height=None,None
for stream in data["streams"]:
if "width" in stream and "height" in stream:
width,height=stream["width"],stream["height"]
break
if width==None:
raise RuntimeError("no video stream found")
return width,height
def extract_frames(fname,skip):
width,height=video_get_size(fname)
#avconv -loglevel debug -i "/home/lieuwe/Downloads/Firefly/Episode 1 - Serenity.mkv" -f image2pipe -pix_fmt rgb24 -vcodec rawvideo -
p=subprocess.Popen(["avconv","-loglevel","warning","-i",fname,"-vf","select=expr=not(mod(n\\,{}))".format(skip),"-f","rawvideo","-pix_fmt","rgb24","-vcodec","rawvideo","-"],stdout=subprocess.PIPE,bufsize=width*height*3*2)
def atexit_callback():
if p.poll():
p.terminate()
p.wait()
atexit.register(atexit_callback)
while p.poll:
left=3*width*height
frame=""
while left>0:
p.stdout.flush()
d=p.stdout.read(left)#single frame :D
left-=len(d)
frame+=d
arr=numpy.fromstring(frame,dtype="uint8")
arr=arr.reshape((height,width,3))
yield arr
if p.returncode!=0:
raise RuntimeError("avconv error")
if __name__=="__main__":
fname="/home/lieuwe/Downloads/Apollo 13 (1995)/Apollo.13.1995.720p.BluRay.x264.YIFY.mp4"
framewindow=960
skip=16
width,height=video_get_size(fname)
window=tk.Tk()
window.geometry("+{}+{}".format(width,height))
label=tk.Label(window)
label.pack()
currentframe=0
outframecount=0
for frameset in grouper(int(framewindow/skip),extract_frames(fname,skip)):
result=numpy.zeros([height,width,3],dtype="float64")
for frame in frameset:
result+=frame
result=(result/len(frameset)).astype(numpy.uint8)
img=Image.fromarray(result,"RGB")
img.save("frames/frame{:05d}.png".format(outframecount))
outframecount+=1
timg=ImageTk.PhotoImage(img)
label.configure(image=timg)
window.update()
currentframe+=len(frameset)
print "frame",currentframe*skip
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment