Getting the dimensions of a video file in Python

There might be a better way to do this, but in a pinch, it works, as long as you have ffmpeg installed:

import subprocess, re
pattern = re.compile(r'Stream.*Video.*([0-9]{3,})x([0-9]{3,})')

def get_size(pathtovideo):
p = subprocess.Popen(['ffmpeg', '-i', pathtovideo],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
match = pattern.search(stderr)
if match:
x, y = map(int, match.groups()[0:1])
else:
x = y = 0
return x, y
Remember it's stderr, not stdout, because ffmpeg fails if you don't provide an output file. We don't really care, though, because it still prints out the stats of the infile.

7 comments

Post a Comment