Navigation

Version

p5.videomotion

From the p5.videomotion documentation, a camera motion tracking library for p5.js
p5.videomotion
Typep5.js add-on library
PurposeCamera motion tracking
Version0.1.0
Requiresp5.js 2.x (also runs on 1.x)
FeaturesMotion mask, blobs with tracking, active zones, optical flow
ProcessingCPU, single pass per frame
DependenciesNone
LicenseMIT
Based onIdeas from p5.vida by Paweł Janicki
DocsReference · Examples

p5.videomotion is an add-on library for p5.js that detects movement in a webcam or video image and turns it into values you can draw with. It finds where things move (a motion mask and tracked blobs), whether anything moves inside regions you define (zones), and which way and how fast things move (optical flow).

It is written for interactive installations, performances and teaching. Everything is reported in canvas pixels, it updates itself every frame, and it uses the same callback style as p5.js. It is a rewrite of the ideas in p5.vida: about four to five times faster, and with optical flow added.

Overview

A sketch using p5.videomotion creates one motion object from a video source and reads results from it in draw():

Installation

CDN

Load p5.videomotion after p5.js:

<script src="https://cdn.jsdelivr.net/npm/p5@2/lib/p5.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/bmoren/p5.videomotion/p5.videomotion.js"></script>
<script src="sketch.js"></script>

Other CDN links:

To pin a version, add a tag, for example .../gh/bmoren/p5.videomotion@0.1.0/p5.videomotion.js.

Download

Download p5.videomotion.js and load it after p5.js:

<script src="https://cdn.jsdelivr.net/npm/p5@2/lib/p5.min.js"></script>
<script src="p5.videomotion.js"></script>
<script src="sketch.js"></script>

In the p5.js Web Editor, upload p5.videomotion.js to the sketch and add the second line to index.html, or paste the CDN line instead.

Serving the page

Browsers only allow camera access on pages served over https:// or from http://localhost. Opening index.html straight from disk (file://) will not work. From the sketch's folder, run any small web server, for example:

npx serve
# or
python3 -m http.server 8000

then open the address it prints (for example http://localhost:8000).

p5.js versions

p5.videomotion is written for p5.js 2.x and registers itself with the 2.x add-on system. It also runs on p5.js 1.x (tested with 1.11), where it uses the older pre-draw hook. Older 1.x versions without createCapture(VIDEO, { flipped: true }) can use the flip: true option instead, mirroring the drawn image themselves with scale(-1, 1).

Quick start

let cam, motion;

function setup() {
  createCanvas(640, 480);
  cam = createCapture(VIDEO, { flipped: true });   // mirror, like a mirror
  cam.hide();

  motion = createMotion(cam);                      // updates itself every frame

  motion.zone('left', 40, 140, 160, 200)           // x, y, w, h in canvas pixels
    .onEnter(z => console.log(z.id, 'ON'))
    .onExit(z => console.log(z.id, 'OFF'));
}

function draw() {
  image(cam, 0, 0, width, height);
  motion.debug();                                  // see what is detected
}

From here, read motion.blobs, zone.amount or motion.flowAt() to drive your own drawing. The examples show each of these.

Concepts

Coordinates

Internally the camera image is shrunk to a small processing resolution (320 pixels wide by default), because motion analysis does not need full camera detail and every pixel costs time. You never deal with that resolution directly: everything you give p5.videomotion (zone rectangles, flowAt() positions) and everything it gives back (blob boxes, flow vectors) is in canvas pixels.

By default the camera is assumed to cover the whole canvas, which matches image(cam, 0, 0, width, height). If you draw it somewhere else, tell the tracker with mapTo(x, y, w, h) and all coordinates follow. Blobs also have normalized (0–1) coordinates if you need them independent of the canvas.

How a frame is processed

  1. The source is drawn once into a small hidden canvas at processing resolution (mirrored if needed) and its pixels are read once.
  2. The pixels are converted to brightness (grayscale) and lightly blurred to remove camera noise.
  3. Each pixel is compared with the background model. Pixels that differ by more than threshold become motion. This is the motion mask.
  4. A running total of the mask (a summed-area table) is built, so the amount of motion in any rectangle can be found with four lookups. This is what makes zones cheap.
  5. Blobs are found by grouping touching mask pixels, then matched with the previous frame's blobs.
  6. Optical flow is measured on a grid by comparing this frame with the previous one.
  7. Zones are evaluated and their events fire.

Background models

Motion is anything that differs from the background, the tracker's idea of what the empty scene looks like. Choose with the background option:

ModeHow the background is learnedGood forDrawback
'adaptive' (default)Continuously, blending a little of each new frame in (adapt).Most installations. Follows slow lighting changes.Someone who stands still slowly fades into the background.
'static'Once, from the first frame, or again after captureBackground().Controlled lighting where people may stand still: presence detection.Any lighting change or camera bump shows up as motion until you relearn.
'frame'The previous frame is the background.Pure movement: gestures, trails, flicker effects.Still objects vanish instantly. Only edges of moving shapes show.

The background is stored with full precision, so even slow, small brightness changes (dusk light, a cloud) are absorbed by the adaptive model instead of leaving stuck pixels.

Blobs

A blob is a group of touching motion pixels (diagonal neighbours count as touching). Blobs smaller than minArea are ignored, and only the maxBlobs largest are kept. Each blob is matched to the nearest blob of the previous frame within trackDistance, so its id stays the same as it moves. A blob that briefly disappears keeps its id for up to lostFrames frames. onBlobEnter and onBlobExit report blobs appearing and leaving.

One person is not always one blob. Clothes that match the background can split a body into pieces, and two people standing close merge into one. Raising minArea removes small fragments.

Zones

A zone measures the fraction of its area that is in the motion mask (amount). When that reaches the zone's threshold (2% by default) the zone becomes active and onEnter fires; when it drops below, onExit fires. Zones also report the average direction of movement inside them (zone.flow). Thanks to the summed-area table, a zone costs the same however large it is, so dozens of zones are fine.

Optical flow

Optical flow estimates how each part of the image moved between two frames. p5.videomotion uses the Lucas–Kanade method on a grid of points (every 8 processing pixels by default). For each point it finds the small shift that best lines up a patch of the previous frame with the current one. It works on an image pyramid: first on heavily shrunk copies of the frame to catch large movements, then on sharper copies to refine them. With the default 4 levels, movements of about 10 processing pixels per frame (roughly 20 canvas pixels on a 640-wide canvas) are measured accurately.

Limits that come from the method itself:

By default flow is only measured where the motion mask shows movement (maskOnly), which saves time and stops still areas from jittering.

Performance

Update time per frame for the same synthetic scene in Chrome, compared with p5.vida (converted to p5.js 2.x). The figures come from a headless test machine, so treat them as relative rather than absolute.

Processing sizep5.vidap5.videomotionp5.videomotion + flow
160 × 1202.1 ms0.7 ms1.4 ms
320 × 240 (default)7.0 ms1.6 ms3.2 ms
640 × 48030.4 ms6.2 ms12.0 ms

At 60 frames per second a whole frame has 16.7 ms. Ways to spend less:

Most of the remaining cost is reading the camera pixels back from the browser, which every CPU-based library has to do. See Future directions.

Tuning guide

SymptomTry
Speckles of motion everywhere, zones trigger by themselvesRaise threshold (0.2–0.3). Keep denoise on. Give the room more light: cameras are noisy in the dark.
Movement is missed, or only shows at the edges of peopleLower threshold (0.08–0.12). Increase contrast between people and background.
People who stand still disappearLower adapt (0.01–0.02), or use background: 'static' and relearn the empty room with captureBackground().
Lighting changes cause a burst of motionRaise adapt (0.1+) so the background catches up faster, or relearn when the lights change.
Too many small blobsRaise minArea (0.005–0.02) or lower maxBlobs.
Blob ids keep changingRaise trackDistance for fast motion. Raise lostFrames if blobs flicker.
A zone flickers on and offRaise its threshold with setThreshold(), or make it larger.
Flow is jitteryRaise flow smoothing (0.7–0.9) or minSpeed.
Flow misses fast gesturesAdd pyramid levels (5), or lower resolution.
Flow is zero in some areasThose areas lack texture or are not in the motion mask. Lower minTexture, or set maskOnly: false.

Troubleshooting

Nothing happens and there is no camera image
The page must be served from http://localhost or https:// (see Serving the page), and you must allow camera access. Check the browser's address bar for a blocked-camera icon.
createMotion is not defined
p5.videomotion.js did not load, or loaded before p5.js. Check the order of the <script> tags and the browser console for a 404.
The mask, zones or blobs are mirrored relative to the image
The tracker mirrors only when the capture was created with { flipped: true }, or with the flip option. Make the image you draw and the tracker agree: draw the capture with image() (which respects flipped), or set flip explicitly.
Zones and blobs are offset from the camera image
The camera is drawn somewhere other than the full canvas. Call motion.mapTo() with the same rectangle you pass to image().
Everything is motion for the first moment
The background is learned from the first frame, which some cameras deliver dark or out of focus. The adaptive model recovers in a second or two. With 'static', call captureBackground() once the camera has settled (for example, on a key press).
The sketch is slow
See Performance. The single biggest factor is resolution.

Migrating from p5.vida

p5.videomotion covers the same ground as p5.vida with a different API, so existing Vida sketches need small changes. The main differences: there is no update() call to make, coordinates are canvas pixels instead of normalized 0–1 values, and mirroring is handled by the capture itself.

p5.vidap5.videomotion
vida = new Vida(this)motion = createMotion(cam)
vida.update(cam) in draw()Automatic. Or autoUpdate: false and motion.update()
progressiveBackgroundFlag = truebackground: 'adaptive'
progressiveBackgroundFlag = false + setBackgroundImage(cam)background: 'static' + captureBackground()
imageFilterFeedback = 0.92adapt: 0.08 (adapt = 1 − feedback)
imageFilterThresholdthreshold (scales differ; retune by eye)
mirror = vida.MIRROR_HORIZONTALcreateCapture(VIDEO, { flipped: true }) or flip: true
handleBlobsFlag, trackBlobsFlagblobs option (tracking is always on)
normMinBlobMassminArea
normMaxBlobArea, normMaxBlobMassNo option; filter motion.blobs by b.area
getBlobs()motion.blobs
blob.normRectX … normRectHb.x, b.y, b.w, b.h (canvas px) or b.nx … b.nh
blob.normMassCenterX/Yb.cx, b.cy or b.ncx, b.ncy
blob.approximatedPolygonb.hull() (convex outline)
blob.isNewFlagb.isNew, or onBlobEnter()
addActiveZone(id, nx, ny, nw, nh, callback)zone(id, x, y, w, h).onChange(callback) (canvas pixels: multiply normalized values by width / height)
zone.isMovementDetectedFlagzone.active
zone.normFillFactorzone.amount*
zone.normFillThresholdzone.threshold / setThreshold()*
drawBlobs(), drawActiveZones()motion.debug()
thresholdImagemotion.mask
—Optical flow: flowAt(), averageFlow(), forEachFlow(), zone.flow

* p5.vida divided a zone's motion pixel count by the zone's width plus its height instead of its area, so its fill factors were much larger than true fractions. Zone thresholds carried over from Vida sketches will need lowering.

Limitations

Future directions

p5.js 2.x is adding GPU features that could take most of this work off the CPU: filter shaders written in JavaScript (p5.strands), and an experimental WebGPU mode with compute shaders. The background model, the motion mask and optical flow all suit the GPU. Blob grouping does not, and would still need a small mask read back. Machine-learning person segmentation (for example MediaPipe) is a different way to answer "is someone there?" that ignores lighting changes and still people, at the cost of a model download and more GPU time.

AI usage disclosure

This project follows the spirit of the p5.js AI Usage Policy, which asks people to say which AI tools they used and how.

p5.videomotion is an independent add-on library, not part of p5.js itself. Contributions to this project are welcome. Please use AI tools only as an aid, make sure you understand and have tested what you submit, and say in your pull request which tools you used.

See also