p5.videomotion
| Type | p5.js add-on library |
|---|---|
| Purpose | Camera motion tracking |
| Version | 0.1.0 |
| Requires | p5.js 2.x (also runs on 1.x) |
| Features | Motion mask, blobs with tracking, active zones, optical flow |
| Processing | CPU, single pass per frame |
| Dependencies | None |
| License | MIT |
| Based on | Ideas from p5.vida by Paweł Janicki |
| Docs | Reference · 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():
- Motion mask — which pixels differ from the learned background (
motion.mask), and what fraction of the frame is moving (motion.amount). - Blobs — connected regions of motion with bounding box, centre of mass, outline, velocity and a persistent id (
motion.blobs). - Zones — rectangles that report how much of them is moving and fire events when they switch on and off (
motion.zone()). - Optical flow — a grid of motion vectors, readable at any point (
flowAt()), as a whole-frame average (averageFlow()), or per zone (zone.flow). - Debug view — one call (
motion.debug()) draws all of the above over your sketch.
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:
- jsDelivr:
https://cdn.jsdelivr.net/gh/bmoren/p5.videomotion/p5.videomotion.js - unpkg:
https://unpkg.com/p5.videomotion/p5.videomotion.js
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
- The source is drawn once into a small hidden canvas at processing resolution (mirrored if needed) and its pixels are read once.
- The pixels are converted to brightness (grayscale) and lightly blurred to remove camera noise.
- Each pixel is compared with the background model. Pixels that differ by more than
thresholdbecome motion. This is the motion mask. - 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.
- Blobs are found by grouping touching mask pixels, then matched with the previous frame's blobs.
- Optical flow is measured on a grid by comparing this frame with the previous one.
- 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:
| Mode | How the background is learned | Good for | Drawback |
|---|---|---|---|
'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:
- It needs texture. A flat, single-coloured surface looks the same wherever it moves, so no motion can be measured there. Such patches are reported as zero (see
minTexture). Faces, hands, clothing and hair have plenty of texture. Plain walls and dark areas do not. - Edges are ambiguous along their length (the aperture problem). A long straight edge sliding along itself shows no motion. Only movement across it is measured.
- Very fast motion beyond the pyramid's range is underestimated. Add a
levelsor lower the resolution.
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 size | p5.vida | p5.videomotion | p5.videomotion + flow |
|---|---|---|---|
| 160 × 120 | 2.1 ms | 0.7 ms | 1.4 ms |
| 320 × 240 (default) | 7.0 ms | 1.6 ms | 3.2 ms |
| 640 × 480 | 30.4 ms | 6.2 ms | 12.0 ms |
At 60 frames per second a whole frame has 16.7 ms. Ways to spend less:
- Lower
resolution. Time scales with the number of pixels, so 160 is about four times cheaper than 320. - Turn off what you do not use:
{ blobs: false }or{ flow: false }. - Use a larger flow
step(for example 12 or 16). - Use
autoUpdate: falseand callupdate()every second frame. - Ask the camera for a smaller image:
cam.size(320, 240).
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
| Symptom | Try |
|---|---|
| Speckles of motion everywhere, zones trigger by themselves | Raise 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 people | Lower threshold (0.08–0.12). Increase contrast between people and background. |
| People who stand still disappear | Lower adapt (0.01–0.02), or use background: 'static' and relearn the empty room with captureBackground(). |
| Lighting changes cause a burst of motion | Raise adapt (0.1+) so the background catches up faster, or relearn when the lights change. |
| Too many small blobs | Raise minArea (0.005–0.02) or lower maxBlobs. |
| Blob ids keep changing | Raise trackDistance for fast motion. Raise lostFrames if blobs flicker. |
| A zone flickers on and off | Raise its threshold with setThreshold(), or make it larger. |
| Flow is jittery | Raise flow smoothing (0.7–0.9) or minSpeed. |
| Flow misses fast gestures | Add pyramid levels (5), or lower resolution. |
| Flow is zero in some areas | Those 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://localhostorhttps://(see Serving the page), and you must allow camera access. Check the browser's address bar for a blocked-camera icon. createMotion is not definedp5.videomotion.jsdid 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 theflipoption. Make the image you draw and the tracker agree: draw the capture withimage()(which respectsflipped), or setflipexplicitly. - 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 toimage(). - 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', callcaptureBackground()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.vida | p5.videomotion |
|---|---|
vida = new Vida(this) | motion = createMotion(cam) |
vida.update(cam) in draw() | Automatic. Or autoUpdate: false and motion.update() |
progressiveBackgroundFlag = true | background: 'adaptive' |
progressiveBackgroundFlag = false + setBackgroundImage(cam) | background: 'static' + captureBackground() |
imageFilterFeedback = 0.92 | adapt: 0.08 (adapt = 1 − feedback) |
imageFilterThreshold | threshold (scales differ; retune by eye) |
mirror = vida.MIRROR_HORIZONTAL | createCapture(VIDEO, { flipped: true }) or flip: true |
handleBlobsFlag, trackBlobsFlag | blobs option (tracking is always on) |
normMinBlobMass | minArea |
normMaxBlobArea, normMaxBlobMass | No option; filter motion.blobs by b.area |
getBlobs() | motion.blobs |
blob.normRectX … normRectH | b.x, b.y, b.w, b.h (canvas px) or b.nx … b.nh |
blob.normMassCenterX/Y | b.cx, b.cy or b.ncx, b.ncy |
blob.approximatedPolygon | b.hull() (convex outline) |
blob.isNewFlag | b.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.isMovementDetectedFlag | zone.active |
zone.normFillFactor | zone.amount* |
zone.normFillThreshold | zone.threshold / setThreshold()* |
drawBlobs(), drawActiveZones() | motion.debug() |
thresholdImage | motion.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
- Background subtraction detects change, not people. Shadows, reflections, screens and moving projections in view all count as motion.
- All processing runs on the main thread. Very high resolutions compete with your drawing for time.
- Blob outlines are convex hulls, so concave shapes (an arm held out from the body) are filled in.
- Only one horizontal mirror option. Rotate or flip other ways by drawing the source into a
p5.Graphicsfirst.
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.
- Tools used: Claude (Anthropic), through claude.ai and Claude Code.
- How it was used: Much of the library code, documentation, examples and browser tests was written with Claude, working from the maintainer's requests. The maintainer chose the features and the API, reviewed the results, and is responsible for the project.
- How it was checked: Behaviour is checked with automated browser tests (blob and zone accuracy, optical-flow accuracy, and every documentation example) on p5.js 2.x and 1.x, and with live camera testing.
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
- p5.videomotion reference
- p5.videomotion examples (15 sketches)
- createCapture() in the p5.js reference
- p5.vida by Paweł Janicki, the library that inspired this one
- Lucas–Kanade method and Summed-area table on Wikipedia