Skip to content

Instantly share code, notes, and snippets.

@figa12
Created May 23, 2014 07:05
Show Gist options
  • Save figa12/f869f10345da85f719c2 to your computer and use it in GitHub Desktop.
Save figa12/f869f10345da85f719c2 to your computer and use it in GitHub Desktop.
from argparse import ArgumentParser
#requires numpy, moviepy, and PIL libraries
from moviepy.editor import VideoFileClip
from numpy import zeros, array, uint8
from PIL import Image
import math
def frange(x, y, inc):
while x < y:
yield x
x += inc
def average_video(filepath, outpath, start, end, sample_every=24):
# load video
vid = VideoFileClip(filepath, audio=False)
width = vid.w
height = vid.h
# compute time increment for sampling by frames
sample_inc = sample_every / vid.fps
# create starting matrix of zeros
avgmatrix = zeros(shape=(height, width, 3), dtype=int)
# loop through frames, sampling at each chosen frame
totalframes = 0
old = "none"
for f in frange(start, end, sample_inc):
avgmatrix += vid.get_frame(f)
totalframes += 1
progress ="{}{}".format(math.floor((f/end)*100),"%")
if progress != old:
print(progress)
old = progress
# average out the values for each frame
avgmatrix = avgmatrix / totalframes
#create final image
final_img = Image.fromarray(avgmatrix.astype(uint8))
final_img.save(outpath)
if __name__ == "__main__":
parser = ArgumentParser(description="Creates image with averaged pixels"
"for a given movie clip")
parser.add_argument("-i", required=True, type=str,
help="filepath to movie clip")
parser.add_argument("-o", required=True, type=str,
help="filepath to save image to")
parser.add_argument("-s", type=int, required=True,
help="Start time for image processing, in seconds")
parser.add_argument("-e", type=int, required=True,
help="End time for image processing, in seconds")
parser.add_argument("-f", type=int, default=24,
help="Sample every f frames (default 24)")
args = parser.parse_args()
average_video(args.i, args.o, args.s, args.e, args.f)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment