Navigation

Version

p5.videomotion reference

From the p5.videomotion documentation
For an introduction, see the main page. For runnable sketches, see Examples.

This page documents everything p5.videomotion adds to p5.js: the createMotion() function, its options, and the three kinds of object it gives you — the motion object, zones and blobs.

Unless stated otherwise, every position, size, distance and speed is in canvas pixels (speeds are canvas pixels per frame), measured against the area the camera is mapped to (the whole canvas by default; see mapTo()). Values described as fractions run from 0 to 1.

createMotion()

createMotion(source, [options])

Creates a motion tracker that watches source and returns it. By default the tracker updates itself just before every draw(), so you only create it once in setup().

createMotion(source)
createMotion(source, options)
Parameters
source — what to watch. Any of: a capture from createCapture(VIDEO), a video from createVideo(), a p5.Graphics, a p5.Image, or an HTML <video>, <canvas> or <img> element.
options — optional object; see Options.
Returns
A motion object (p5.MotionTracker).
let cam, motion;

function setup() {
  createCanvas(640, 480);
  cam = createCapture(VIDEO, { flipped: true });
  cam.hide();
  motion = createMotion(cam, { resolution: 240, threshold: 0.2 });
}

In instance mode call it as p.createMotion(...). You can create several trackers in one sketch, each with its own source and options.

Options

Pass these to createMotion(), or change them later with motion.set(). Every option is optional.

OptionDefaultDescription
resolution320Width in pixels that the source is scaled down to before processing. The height follows the source's aspect ratio. It is never larger than the source itself. Halving it makes processing roughly four times faster. Changing it relearns the background.
background'adaptive'How the empty scene is modelled. 'adaptive' learns it continuously; 'static' learns it once (relearn with captureBackground()); 'frame' compares each frame with the one before. See Background models.
adapt0.05Learning speed of the 'adaptive' background, 0–1. Each frame the background moves this fraction of the way toward the current image. Higher values follow lighting changes faster, but people who stand still also fade into the background sooner.
threshold0.15How different a pixel's brightness must be from the background to count as motion, as a fraction of the full brightness range (0.15 ≈ 38 of 255 levels).
denoisetrueApplies a light 3×3 blur before processing, which removes most camera noise speckle.
blobstrueDetects and tracks blobs. Turn off to save time when you only use zones or flow.
minArea0.002Smallest blob kept, as a fraction of all the pixels in the frame (0.002 at 320×240 is about 150 pixels).
maxBlobs16Keep at most this many blobs, largest first.
trackDistance0.15The furthest a blob's centre may move between frames and still keep its id, as a fraction of the frame width.
lostFrames3How many frames a blob may disappear for (for example, when someone briefly holds still) before it counts as gone and onBlobExit fires.
flowtrueOptical flow. true or false, or an object of flow options (which also turns it on).
flipautomaticMirror the source horizontally. By default this follows the capture's own setting: a capture made with { flipped: true } is processed mirrored, so the analysis lines up with what image(cam, …) draws.
autoUpdatetrueUpdate automatically before each draw(). Set to false to call update() yourself.

Flow options

Given as an object: createMotion(cam, { flow: { step: 12, smoothing: 0.7 } }). Unlisted values keep their defaults.

OptionDefaultDescription
step8Spacing of the flow grid, in processing pixels. At the default 320 resolution this gives a 40×30 grid. Larger steps are faster and coarser.
window4Radius of the patch compared around each grid point (4 means 9×9 pixels). Larger windows are steadier but blur the edges of motion.
levels4Number of image pyramid levels. Each level doubles the speed that can be measured. With 4 levels, motion of about 10 processing pixels per frame is measured accurately.
iterations3Refinement steps per level.
smoothing0.5Smoothing over time, 0–0.99. 0 uses each frame's measurement as is; higher values are steadier but react later.
minSpeed0.3Vectors slower than this (canvas pixels per frame) are ignored by averageFlow(), zone.flow and debug(). Does not affect flowAt() or forEachFlow().
minTexture4How much detail a patch needs before its motion is trusted (average brightness change per pixel). Flat, single-coloured areas give no reliable flow and are reported as zero.
maskOnlytrueOnly measure flow near pixels that the motion mask marks as moving. Everywhere else is zero. Saves time and removes jitter in still areas.

The motion object

The object returned by createMotion(), an instance of p5.MotionTracker.

Properties

PropertyTypeDescription
readyBooleantrue once the source delivers frames and the latest update succeeded. Before that, the other values are empty or zero.
amountNumberFraction of the whole frame that is moving, 0–1.
blobsArrayThe blobs found in the current frame, largest first. Blobs in their lostFrames grace period are not included.
zonesArrayAll zones, in the order they were added.
maskp5.ImageThe motion mask: white where there is motion, black elsewhere, at processing resolution. Built on first access each frame, so it costs nothing if unused. null before the first frame.
width, heightNumberProcessing resolution in pixels.
frameNumberNumber of frames processed so far.
options, flowOptionsObjectCurrent settings (read only; change them with set()).
source—The source being watched. You can assign a new one; processing resizes if needed.

Methods

zone(id, x, y, w, h)

Adds a rectangular zone and returns it, so calls can be chained. A zone with the same id is replaced.

Parameters
id — any string or number, used to find the zone again.
x, y, w, h — the rectangle in canvas pixels.
Returns
The zone (p5.MotionZone).
motion.zone('door', 500, 100, 120, 300)
  .setThreshold(0.05)
  .onEnter(z => console.log('someone at the door'));

getZone(id)

Returns the zone with that id, or null.

removeZone(id)

Removes the zone with that id. Returns the motion object.

flowAt(x, y)

Returns the motion at a canvas position as a p5.Vector, in canvas pixels per frame, interpolated smoothly between flow grid points. Returns (0, 0) when flow is off or the tracker is not ready.

let v = motion.flowAt(mouseX, mouseY);
line(mouseX, mouseY, mouseX + v.x * 5, mouseY + v.y * 5);

averageFlow()

Returns the average of all flow vectors faster than minSpeed as a p5.Vector, or (0, 0) if nothing is moving. Good for overall gestures such as swipes.

forEachFlow(callback)

Calls callback(x, y, vx, vy) once for every point on the flow grid, including still ones (where vx and vy are 0). x, y is the grid point and vx, vy its motion, all in canvas pixels. Uses plain numbers instead of vectors, so it is cheap to call every frame. Returns the motion object.

motion.forEachFlow((x, y, vx, vy) => {
  if (vx * vx + vy * vy > 1) line(x, y, x + vx * 4, y + vy * 4);
});

onBlobEnter(callback)

Calls callback(blob) once for each new blob, in the frame it first appears. Returns the motion object. Can be called several times to add several callbacks.

onBlobExit(callback)

Calls callback(blob) when a blob has been missing for more than lostFrames frames. The blob passed in still holds its last known position, id and age. Returns the motion object.

captureBackground()

Relearns the background from the next frame. Use with background: 'static' when the scene is empty, or after the camera or lighting changes. Returns the motion object.

mapTo(x, y, w, h)

Tells the tracker where the camera image is drawn on the canvas, so that zones, blobs and flow use matching canvas coordinates. Call with no arguments to go back to the default (the whole canvas, following any resize). Returns the motion object.

image(cam, 20, 20, 320, 240);
motion.mapTo(20, 20, 320, 240);   // usually once, in setup()

set(options)

Changes options while the sketch runs. Only the options given change. Takes effect at the next update. Changing resolution relearns the background, and changing flow levels or step restarts the flow measurement. Returns the motion object.

motion.set({ threshold: 0.25, flow: { smoothing: 0.8 } });

update()

Processes one frame from the source. Only needed with autoUpdate: false. Calling it while autoUpdate is on processes the frame twice. Returns true if a frame was processed, false if the source is not ready yet.

// update every other frame to save time
if (frameCount % 2 === 0) motion.update();

debug([options])

Draws what the tracker sees on top of your sketch: the motion mask in pink, flow vectors in yellow, blobs in green and zones in white (red when active). Draw it after the camera image. Does not change your fill, stroke or other drawing settings. Returns the motion object.

Parameters
options — optional; turn layers off with { mask: false, zones: false, blobs: false, flow: false }.

remove()

Stops automatic updates for this tracker. The object keeps its last results.

Zones

A zone is a rectangle on the canvas that reports how much motion is inside it. Create zones with motion.zone(). Each one is a p5.MotionZone. Checking a zone costs the same however large it is, so you can use many.

Zone properties

PropertyTypeDescription
idString / NumberThe id given when the zone was created.
x, y, w, hNumberThe rectangle in canvas pixels. You can change them directly, or use moveTo().
amountNumberFraction of the zone that is moving, 0–1.
activeBooleantrue while amount is at or above threshold.
thresholdNumberThe amount at which the zone becomes active. Default 0.02 (2% of the zone).
flowp5.VectorAverage direction of movement inside the zone, from the flow vectors faster than minSpeed, in canvas pixels per frame. (0, 0) if flow is off. Each read returns a new vector, so it is safe to change.

Zone methods

onEnter(callback)

Calls callback(zone) when the zone becomes active. Returns the zone.

onExit(callback)

Calls callback(zone) when the zone stops being active. Returns the zone.

onChange(callback)

Calls callback(zone) on every change, in either direction (after any onEnter or onExit callbacks). Check zone.active to see which way it went. Returns the zone.

setThreshold(t)

Sets threshold. Returns the zone.

moveTo(x, y, [w], [h])

Moves the zone, and optionally resizes it. Returns the zone.

contains(x, y)

Returns true if the canvas point is inside the zone.

remove()

Removes the zone from its motion object.

Blobs

A blob is one connected region of motion, such as a person or a hand. Blobs are tracked from frame to frame, so a blob keeps its id while it moves. Read them from motion.blobs. Each one is a p5.MotionBlob.

Property / methodTypeDescription
idNumberUnique number that stays the same while the blob is tracked. Ids are never reused.
ageNumberFrames tracked since the blob appeared (0 in its first frame).
isNewBooleantrue only in the blob's first frame.
x, y, w, hNumberBounding box in canvas pixels.
cx, cyNumberCentre of mass (the average position of its pixels) in canvas pixels. Steadier than the centre of the box.
areaNumberSize as a fraction of the frame, 0–1.
velocityp5.VectorHow far the centre of mass moved since the blob was last seen, in canvas pixels (per frame, unless the blob was briefly lost).
hull()Array of p5.VectorThe blob's outline as a convex hull, in canvas pixels, ready for beginShape() / vertex(). Only valid in the frame the blob was found (call it from draw()). Computed on demand and cached for the frame.
nx, ny, nw, nh, ncx, ncyNumberThe same box and centre as fractions (0–1) of the camera frame, independent of where it is drawn.
for (let b of motion.blobs) {
  beginShape();
  for (let v of b.hull()) vertex(v.x, v.y);
  endShape(CLOSE);
  text('#' + b.id, b.cx, b.cy);
}

Timing and update order

p5.videomotion registers a p5 predraw hook (on p5.js 1.x it uses the equivalent pre hook). Each frame, in order:

  1. Every motion object with autoUpdate on processes the current source image.
  2. During that update, blob and zone callbacks fire (onBlobEnter, onBlobExit, onEnter, onExit, onChange).
  3. Your draw() runs and reads the fresh results.

If your source is something you draw yourself (a p5.Graphics), what you draw during draw() is processed at the start of the next frame.

Globals added to p5

NameDescription
createMotion()Added to every sketch (global and instance mode).
p5.MotionTracker, p5.MotionZone, p5.MotionBlobThe classes, exposed for instanceof checks or extending with your own methods. Create trackers with createMotion() rather than calling these constructors.