from PIL import Image
import os
import sys
import operator
import subprocess
import shutil

def extract_frames(destination):
    os.makedirs(destination, exist_ok=True)
    subprocess.run(["ffmpeg", "-i", "aurora.mp4", "frames/out-%03d.png"])
    print()

def parse_frame(file):
    img = Image.open(file)
    pix = img.load()
    return img.size, pix

if __name__ == "__main__":
    
    output_directory = "frames"
    pixel_sum = None
    count = 0

    extract_frames(output_directory)
    for file in sorted(os.listdir(output_directory)):
        if file.endswith(".png"):
            sys.stdout.write(f"\rAnalyzing: {file}")
            (width, height), pix = parse_frame(os.path.join(output_directory, file))
            if pixel_sum is None:
                pixel_sum = [[(0,0,0) for y in range(height)] for x in range(width)]

            for x in range(width):
                for y in range(height):
                    pixel_sum[x][y] = tuple(map(operator.add, pixel_sum[x][y], pix[x,y]))
            
            count += 1
            
    print("\nComposing new image")
    img = Image.new("RGB", (width, height))
    pix = img.load()

    for x in range(width):
        for y in range(height):
            pix[x,y] = tuple(map(operator.floordiv, pixel_sum[x][y], [count] * 3))

    img.save(f"result.png")
    shutil.rmtree(output_directory)