Instruments & Data Tools: solutions for sensing, imaging, analytics

Instruments & Data Tools is specialising in custom algorithms and instrumentation for spectroscopy and imaging.
We develop solutions for science and industry.

Time-lapse photography with Python and OpenCV

In this post we will show you how to produce the simple time-lapse photography in this video with Python and OpenCV, using your USB camera. Here we used a Logitech QuickCam® Pro 9000. The Video Capture feature of OpenCV makes this task very easy. Basic information and a few examples are available here.

In this simple example, we will open a video capture stream, acquire images at fixed time interval and save them. After that, we will see how to use OpenCV to set up some of the parameters of the camera.

OK, let’s get started. The basic command to acquire an image (supposed that your camera is set up already) is this.

import cv2 
import numpy as np 
# Create a VideoCapture object 
cap = cv2.VideoCapture(0) 
# Capture a frame ret, img = cap.read() 
# Release the capture cap.release()

Note: if you have a second camera, you can choose chose it by passing 1 as the parameter of the video capture, for instance by calling cv2.VideoCapture(1), etc.

In addition to the frame, the command cap.read() returns a Boolean that will be True if the capture is successful. The frame itself is a numpy array.

That’s about all we need to do, except for setting up the time interval between exposure. This can be implemented in a for loop, for instance:

import time

nframes = 1024
interval = 5

for i in range(nframes):
    # capture
    ret, img = cap.read()
    # save file
    cv2.imwrite('./img_'+str(i).zfill(4)+'.png', img)
    # wait 5 seconds
    time.sleep(interval)

I pointed the camera outside my window ad saved a bunch of images using this code. Then I put the frames together and this is the result.

If you wish to play around with some of the parameters of your camera, for instance exposure, frame rate, gain, etc. you can refer to this page of the OpenCV documentation.

Use the command cap.set(propId, value) to set the value. The first argument of this function refer to the enumeration of the camera properties, and the second argument is the actual value. For instance, for my camera, the property 14 (CV_CAP_PROP_GAIN), is in the range [0-255], or the property 15 (CV_CAP_PROP_EXPOSURE) accepts value in the range [-2, -9]. Note that in this case the actual exposure time goes from 2^(-2) to 2^(-9).

That’s all for today, thanks for stopping by!