SoFunction
Updated on 2024-11-14

Simple time-lapse technique in Python using a webcam

Time-lapse photography is a photographic technique in which an image or video is captured at a lower frame rate and then played back at a normal or faster rate. In a time-lapse video, the slow process of changing an object or scene is compressed into a short period of time, resulting in a strange and exciting scene that would normally be imperceptible to the naked eye. Time-lapse photography can be thought of as the opposite of high-speed photography. Time-lapse photography is often used to photograph cityscapes, natural landscapes, astronomical phenomena, biological evolution and other subjects."

grow grass

Recently bought something got a small gift, is a kind of fast-growing grass, back to planted on the desk. Today sprouted, on a whim intended to do a time-lapse photography, the office happened to have a very old 640x480 camera, so there is the following time-lapse photography motion picture (in order to upload the compressed screen size):

realization


It needs to be prepared:

1) Computer
2) Webcam (if the computer does not have it), Taobao a lot of 20 or less shipping!
3) Python 2.7, because you need to use opencv, so use Python2
4) Python binding for opencv, go to the official website to download it, if you don't want to compile it yourself, just go to \build\python\2.7\ below and you can find the 32-bit and 64-bit ones, and copy this file directly to \Python27\Lib\site-packages\.

The code is as follows:

import cv2
import time

interval = 20  # seconds
num_frames = 500
out_fps = 24

capture = (0)
size =(int((.CV_CAP_PROP_FRAME_WIDTH)),
    int((.CV_CAP_PROP_FRAME_HEIGHT)))
video = ("time_lapse.avi", .CV_FOURCC('I','4','2','0'), out_fps, size)

# for low quality webcams, discard the starting unstable frames
for i in xrange(42):
  ()

# capture frames to video
for i in xrange(num_frames):
  _, frame = ()
  (frame)

  ## Optional, in case you need the frames for GIF or so
  filename = '{:4}.png'.format(i).replace(' ', '0')
  (filename, frame)

  print('Frame {} is captured.'.format(i))
  (interval)

()
()



Since it's a simple time-lapse, the code is also very simple. Set the shooting interval, the total number of frames and the output frame rate, use VideoCapture to get the image from the camera, use VideoWriter to write the video, taking into account that some poor-quality cameras are unstable during initialization (such as this old camera I used), you can consider skipping the initial dozens of frames before formally capturing the image, and you can also directly output the image during the capturing process for easy GIF or other uses.

And finally a full view of a water droplet evaporating on a tin box: