Creating a Time Lapse - Video Editing With Python

Mathias Pfeil

Author

General Programming

Category

July 23 2019

Time Created

Turning a video clip into a time lapse is one of the more basic things you can do with Python and OpenCV. So simple that we can write such a script in 20 lines. Here is an example:




import cv2

vid = cv2.VideoCapture('./assets/key.mov')
frames = []
success = 1
count = 0
speed = 8

while success:
    success, image = vid.read()
    if(count % speed == 0):
        frames.append(image)
    count += 1

writer = cv2.VideoWriter('./output/tl.mp4', cv2.VideoWriter_fourcc(*"MP4V"), 29.98, (1280, 720))

for frame in frames:
    writer.write(frame)
writer.release()

If you would prefer to walk through the code with me, here is a quick video.



Here is what is happening. First, we create a Python list where we will store all of our frames. We then load in the video clip and run through it frame by frame. If we appended every frame to our list, the output video would play at normal speed, so we need to cut out some of the frames. This can be done by only appending frames that occur when our counter is divisible by a number like 8 (our speed variable). Using this method, and considering our original clip is 30 FPS, we would get 3 frames for every second of our input clip. Once we have gone through the entirety of our input clip, we will then take the frames we collected and create a new output video at the same 30 FPS. Once you are finished, your output should be a sped up video. You can adjust the speed of your video by changing the value for your "speed" variable.



If you have trouble installing OpenCV (cv2), you can also try the following command: pip install opencv-python