Detecting movements with Motion

Who Goes There?


The motion detector software, Motion, monitors the video signal from one or multiple cameras and is able to detect whether a significant part of the picture has changed, record and track movement, or launch arbitrary external commands to trigger other actions.

By Kristian Kißling

Martin Hochrein, photocase.com

The free Motion [1] software, by Jeroen Vreeken and Kenneth Jahn Lavrsen, can help monitor your office or home while you are away. Motion takes photos and captures videos when movement occurs and, if needed, the computer running the software can mail or text you the images. You can install Motion locally or use a web interface to control it. If needed, the software can monitor multiple cameras.

The install on Ubuntu is relatively simple. Feisty Fawn (7.04) and Edgy Eft (6.10) include version 3.2.3 of the software in their Universe repositories. You also need to install the FFmpeg and nasm packages. Users with Ubuntu 6.10 and 6.06, Debian Sid, and Fedora Core 4 can use the latest version 3.2.7 of Motion. Users with Ubuntu Feisty Fawn will need to build from the source code to have the latest version. Users with SUSE (SUSE Linux 10.1 or openSUSE 10.2) will need to build Motion whatever, as the "Building Motion" box describes.

Building Motion

Users with SUSE 10.1 need to launch YaST and add the Packman repository [2] as an additional package source (Software | Change Installation Source ). Next, start by installing ffmpeg, libffmpeg0-devel, nasm, libjpeg, libjpeg-devel, mysql, mysql-devel, postgresql, postgresql-devel, and checkinstall.

You also need the Build environment to compile the source code. Select Software | Install and Remove Software in YaST, and select Selections in the drop-down menu next to Filter. Check the box for C/C++ Compiler and Tools and then click Apply.

Start by unpacking the Motion source-code archive at the command line, then change to the new directory this step created and type ./configure to configure the source code.

If you are not missing a critical package, you should see a success message at the end with the word YES next to all the dependencies. Now type make to compile the source code. Then become root, and type checkinstall to build an RPM package. Just press Enter to confirm the Checkinstall prompts.

Then - still working as root - type rpm -Uhv /usr/src/packages/RPMS/i386/motion-3.2.7-1.i386.rpm to install the package. When you are done, copy the configuration file, /usr/local/etc/motion-dist.conf, to /usr/local/etc/motion.conf and edit the file as described in the text. For example, the target_dir label lets you set the target directory for your photos and videos. After launching the program you should see the webcam image in your browser at http://127.0.0.1:8081. The camera captures movies and grabs stills at the same time.

The approach for openSUSE 10.2 is similar except for a few changes. You don't need the nasm package, and you can install the build tools by selecting Schemes | Basic Development in YaST. You need the Packman repository to install Ffmpeg, etc. Note that YaST will complain about being unable to resolve a dependency, which can be ignored in this case.

Cameras Rolling

To use motion detection, you obviously need a camera - a webcam will do fine. Motion does not include camera drivers, so you will need to install the driver yourself. Ubuntu users will typically launch Synaptic or Adept to install the spca5xx-source or gspca-source packages. RPM packages for SUSE users are available [3]. Make sure the packages match your kernel version; type uname -r to discover your current kernel.

Let's configure the software to avoid losing the images and movies. If you built Motion from scratch, the configuration file will be in /usr/local/etc/motion.conf. Ubuntu users can look in /etc/motion/motion.conf. The file contains important camera control parameters.

The normal way to start the software is by typing motion -n. Open the configuration file in a text editor and look for the target_dir line. If the line is missing, you will need to add it. To the right of the label - separated by a blank - add the absolute path to the folder in which you want Motion to save your photos and movies, such as /home/User/motion. If this folder does not exist, create it. Then look for the webcam_port keyword and type 8081 as the port number so the browser displays the camera image.

The next question concerns your cameras frame rate; typing framerate 25 tells the camera to shoot 25 frames per second, which corresponds to PAL quality. The videodevice option needs the right path to your video interface; typing xawtv -hwscan will tell you the name, which is typically /dev/video0.

Save your changes and point the camera at a stationary target. Open a console and type motion -n to launch the software in daemon mode. Motion will output a couple of lines ending in: Started stream webcam server in port 8081; this is all that happens. As long as everything is quiet, Motion will just sit and wait. If the software keeps recording even though the target is not moving, refer to the "Masking Phantom Images" box.


PAL: Phase Alternating Line, a popular TV standard in Europe that uses 625 lines, 25 frames per second, and a scan rate of 50Hz.

Picture Generator

If you now type the address http://127.0.0.1:8081 in your browser's address bar, the image from your webcam should appear on your screen. Just hold your hand in front of the lens and Motion should output a message on the console (Figure 1); the program will grab still images or capture video clips.

Figure 1: Wave your hand in front of the camera; Motion should register the movement and output a message on the console.

If you are using the Ubuntu packages from the repository, Motion will only capture still images at first. If this happens to you, add a ffmpeg_cap_new on line to your motion.conf file. If you built Motion yourself, the program will capture images and also write the data to an AVI file and create a video clip either in MPEG4 or MSMPEG4 format. The ffmpeg_video_codec option lets you specify which format you prefer. The Microsoft player will play back MSMPEG4 format without requiring you to add a special codec. Pressing Ctrl+C quits Motion.

Masking Phantom Images

When we launched the program on Ubuntu in our lab, Motion immediately started to cram the target directory full of images even though the subject hadn't budged. This was caused by artefacts in the image that were probably generated by the webcam driver. Things like this happen, especially with low-budget cameras. Even without artefacts, Motion can trip up over a couple of things, for example, if trees or cars move across the video image. To prevent motion from triggering an alarm every time, you need to mask the image. For examply, you can limit the area in which the software searches for movement to a door frame.

To do this, first create a PGM-formatted monochrome image in GIMP (Figure 2). Color the area you want Motion to monitor white, and color the area you want Motion to ignore black. To find out how big the image has to be, check out the width and height parameters in your configuration file. You can use the Image | Scale image menu to scale your monochrome image to the right size. Then save the image in, for example, /home/User/motion_image/ and add a mask_file option line with the full path to the mask to your motion.conf file. Now restart Motion to make sure the program only searches where you specify.

The smart_mask_speed switch, which is configurable between 1 and 10, gives you a smart masking option. The smart mask is self-learning and automatically masks areas that move continually, such as trees or bushes in a high wind. If nothing happens in these areas for an extended period of time, Motion increases the sensitivity value again. This parameter is perfect for long-term monitoring projects with moving and changing subjects, although you can anticipate an increase in false positives. Your only other alternative is to modify the mask manually at regular intervals.

Figure 2: You can use GIMP to create this PGM image. Thanks to the mask, Motion will only register movements in the white areas.

Tons of Options

The detailed documentation in Kenneth Jahn Lavrsen's wiki [4] gives you a comprehensive overview of what the options in the Motion configuration file do. The parameters are logically structured and organized by topic in the "Basic Features" [5] section, and this is where to go for help if you need functionality beyond the scope of this article.

Lavrsen groups options that influence image output below "Image File Output", for example. There is a note explaining the possible values for each switch, the defaults, and a short explanation of what the parameter does. For example, output_motion tells Motion to create a special kind of grayscale movie with just the pixels that change. This is a Boolean value that only supports on or off as arguments, and where off is the default. The next option in this section is output_normal. If you enable this, Motion will just grab a JPEG image if anything moves. The quality option expects an integer value between 1 and 100; it defines the recording quality for images captured by Motion.

To improve the image quality delivered by your camera, read the "Video4linux (V4L) devices" section. You can adjust the brightness, the frame rate, the contrast, and the image size. Some options only apply if you use a video card to receive the camera signal instead of using a USB camera. norm lets you specify the TV standard that Motion will use. 0 is the standard setting and refers to PAL. The rotate option is interesting; it expects a value out of a set of 0, 90, 180, 270, and rotates the captured image through the degree you specify.

Besides supporting a local video camera, Motion will also detect motion in camera images that it receives off the Internet. For your experiments you might like to use the fantastic view of a crossroads in Scotland (Figure 3) [6]. The matching options are grouped in the "Network Cameras" section. This feature requires the camera on the website to send JPEGs or a raw MJPEG stream without embedding in an HTML page. Incidentally, googling with search key of live view axis search string returns many cameras that fulfill these conditions. Just click on the camera image, select View Image from the drop-down menu, and copy the URL. Then add the URL to your motion.conf file in the line with the netcam_url parameter and comment out the videodevice option.

Figure 3: Motion detects motion in images provided by remote webcams on the Internet.

Motion Detector

The parameters grouped below "Motion Detection Settings" in the wiki are important for fine-tuning Motion. The despeckle option expects various parameters to help reduce the noise in the image, which in turn makes it easier to detect motion. For example, e and E remove diamonds or squares from the image; a combination of eE filters out circles. Besides the wiki, there is also a website [7] with useful information about these parameters. EedDl is useful as a starting point for your experiments.

The gap option expects a value in seconds (default 60). If the camera does not register a movement within 60 seconds, a new event starts. Motion creates a new MPEG4 file. However, if you define too large an interval, you might experience problems trying to create a movie from scenes or even lose your material. Motion restricts the maximum length of a movie to one hour to avoid this; the parameter is max_mpeg_time 3600.

The minimum_motion_frames option lets you specify how many frames have to change before Motion detects a movement. The recommended value is between five and ten frames.

Noise and Shade

The noise_level and noise_tune options have to do with noise sensitivity. If you are using a low-quality camera with a noisy image, you must adjust the values to prevent the software from grabbing an image whenever you have interference in the image. If you enable noise_tune, Motion will ignore the noise_level setting, along with the threshold and threshold_tune values. The last option disables the first. According to the wiki, these are the most critical motion-detection options because they do not take effect until after masking, (i.e., after removing noise and despeckling).

A night_compensate option gives the program night vision. If the subject becomes too dark, the camera will generate more artefacts and noise. Enabling this option, which is typically disabled, reduces the software's noise sensitivity, but at the price of more false positives.

Phoning Home

If needed, and assuming you pass in the right parameters, Motion will send an email or SMS to let you know that something is on the move. Various events can trigger this response; the "External Commands" section in the wiki explains the parameters. If you add a line for on_event_start send_mail "%Y-%m-%d %T" to your motion.conf file, Motion will run the send_mail script whenever the camera registers an event. The wiki also has a sample script for dispatching an email.

Conclusions

Motion is a well-programmed and fascinating piece of software that you can run with a local webcam, a normal camera, or a webcam stream off the Internet. The program still lacks a GUI. If you intend to monitor a subject over an extended period of time, it makes sense to experiment with the settings and to learn the use of filter and motion options.

Motion is also useful for short movies. The ffmpeg_timelapse option lets you capture images at specific intervals to create a time-lapse movie of clouds moving by, parking lots filling and emptying, or sunsets.

INFO

1] Motion website: http://www.lavrsen.dk/twiki/bin/view/Motion/WebHome

[2] Packman repository: http://packman.iu-bremen.de/suse/10.1/ http://www.linux-user.de/ausgabe/2007/07/040-voip-headsets/index.html
[3] RPM packages for SUSE by Spca5xx and Gspca: http://home.scarlet.be/raoul.linux/rpm/webcam.html
[4] Motion wiki: http://www.lavrsen.dk/twiki/bin/view/Motion/WebHome
[5] Basic documentation for Motion: http://www.lavrsen.dk/twiki/bin/view/Motion/MotionGuideBasicFeatures
[6] Webcam in Kilmarnock: http://cam1.east-ayrshire.gov.uk/mjpg/video.mjpg
[7] Details of the despeckle effect: http://emit.demon.co.uk/motion/