Timelapse with a Pi
Nov 28, 2022

I've been looking for a project with my spare Raspberry Pi and assorted components. I came across an interesting idea to create timelapses with the Pi Camera and ffmpeg.

Using a few python libraries and some basic logic, I've modified the original more to my liking. Eventually I plan on using GCP or Firebase to upload the images to the cloud and use that to produce the final timelapse video instead of the Pi itself since it can take upwards of an hour on my Pi Zero W.

Here's my sample code below:

from picamera import PiCamera
from os import system
import datetime
from time import sleep

tlminutes = 4 * 60 #set this to the number of minutes you wish to run your timelapse camera
secondsinterval = 10 #number of seconds delay between each photo taken
fps = 30 #frames per second timelapse video
numphotos = int((tlminutes*60)/secondsinterval) #number of photos to take
print("number of photos to take = ", numphotos)

dateraw = datetime.datetime.now()
datetimeformat = dateraw.strftime("%Y-%m-%d_%H:%M")
print("RPi started taking photos for your timelapse at: " + datetimeformat)

camera = PiCamera()
camera.resolution = (768, 1024)
camera.rotation = 270

system('rm /home/pi/timelapse/pictures/*.jpg') #delete all photos in the Pictures folder before timelapse start

for i in range(numphotos):
    camera.capture('/home/pi/timelapse/pictures/image{0:06d}.jpg'.format(i))
    sleep(secondsinterval)
print("Done taking photos.")
print("Please standby as your timelapse video is created.")

system('ffmpeg -r {} -f image2 -s 1024x768 -nostats -loglevel 0 -pattern_type glob -i "/home/pi/timelapse/pictures/*.jpg" -vcodec libx264 -crf 25  -pix_fmt yuv420p /home/pi/timelapse/videos/{}.mp4'.format(fps, datetimeformat))
#system('rm /home/pi/Pictures/*.jpg')
print('Timelapse video is complete. Video saved as /home/pi/timelapse/videos/{}.mp4'.format(datetimeformat))

This includes some of my own needs such as rotating the image and modifying the directories where images are stored and then processed. Along with the cloud processing of images, I plan on updating this to have command-line arguments along with possibly installing a GPIO button to start the process instead of having to start via ssh.