import subprocess, sys
from PIL import Image
video, output = sys.argv[1:]
width, height, fps = 1280, 800, 10
process = subprocess.Popen(['ffmpeg', '-v', 'error', '-i', video, '-vf', 'fps=10,scale=1280:800', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-'], stdout=subprocess.PIPE)
best, index, best_index, best_image = -1, 0, 0, None
while True:
    data = process.stdout.read(width*height*3)
    if len(data) < width*height*3: break
    image = Image.frombytes('RGB', (width,height), data)
    score = sum(c < 100 for c in image.crop((260,520,930,650)).convert('L').getdata())
    if score > best: best, best_index, best_image = score, index, image
    index += 1
process.wait()
best_image.save(output)
print(output, 'frame at', best_index/fps, 'score', best)
