Wednesday, October 7, 2020

Time Lapse with Raspberry Pi and Webcam

The raspberry pi is a great tool for making time lapse videos.  I like to use a weatherproof USB webcam with night mode.  This lets me put the camera in the best location (Example: up on the tree) and have the raspberry pi and power source somewhere more convenient for access (Example: bottom of the tree).

The only problem with this is that there is an issue with the webcam, the driver, or the fswebcam program that causes it to sometimes capture blank images.  For me this is about 25% of my images when running this command:

fswebcam -r 1280x720 /home/pi/photos/$DATE.jpg 

Now, some say that skipping a few frames will help to stabilize the image before capture:

fswebcam -S 30 -r 1280x720 /home/pi/photos/$DATE.jpg

It improves things a bit, but I still get way too many blank frames.  So I try capturing multiple frames:

fswebcam -S 20 -F 2 -r 1280x720 /home/pi/photos/$DATE.jpg

Well now I have a motion blur problem, along with poor exposure control for some reason.  I suspect when it captures one black frame and one image they get overlapped and the image looks dark.


Here is my solution,



#set min file size

#set file name
DATE=$(date +"%s")

#set 0 to the initial file size so the loop starts without errors

#take photos until a suitable file size is generated
while (( fileSize < minSize ));
    fswebcam -S 20 -r 1280x720 /home/pi/photos/$DATE.jpg
    sleep 1
    fileSize=$(stat -c%s /home/pi/photos/$DATE.jpg)


Call the script by crontab every 15 minutes, or whatever you desire:

*/15 * * * * /home/pi/ 2>&1


The script attempts to take a picture and then checks the size of the output.  If the size is less than your threshold it will try to take a new picture and overwrite it.  The script continues doing this until an acceptable size image is captured.  Note that the time in the file name will be off by however many seconds it takes to capture a good image, in practice it's usually just a few seconds so I don't care.  If that's important to you the script could be fixed easily.

You will have to experiment to find the correct threshold size.  For me, good daytime images are about 1MB, good nighttime images are about 200kB, and black junk frames are about 40kB - so I set my threshold for a "good" picture to be 50kB.  Obviously if you change the resolution or anything else you'll have to adjust that setting.

1 comment:

  1. Anonymous29/2/24 23:07

    what command you give to run this and how to store images