Object detection in the browser: COCO-SSD on TensorFlow.js
SafeOS’s People and Wildlife pages run a pretrained object-detection model, COCO-SSD, with TensorFlow.js inside the page that watches. This post follows one camera frame through the code that does it: the agreement before a 18.6 MB download, Cache Storage, the choice between WebGL and the processor, a 320 by 240 canvas, a gate that keeps the model idle while the picture holds still, and the boxes that come out. To try it on a feeder at home, set up an old phone as a backyard wildlife camera.
The short version, with the other parts of SafeOS beside it, is the models section of how SafeOS watches a room in your browser. An earlier post, how SafeOS Guardian checks for motion before it runs a model, tells the same story in fewer steps. Here is the whole path:
- The camera’s video.
- A 320 by 240 canvas, every 500 ms on People and every 1 s on Wildlife.
- The gate: does any one of the 8 by 6 cells change by 15 or more? If not, the model does not run, and the page waits for the next check.
- COCO-SSD: the graph resizes the canvas to 300 by 300 and runs on WebGL where the browser allows it, otherwise on the processor.
- Boxes, each with a class name and a score of 0.5 or more.
- People: more people than the allowed number raises the alert. Wildlife: one of the 10 animal classes is kept as a sighting. While a People alert is on, the model also runs every 5 seconds, whatever moved.
One model, one loader
Both pages call one function, loadDetectionModel() in detection-model.ts, and share the model it returns. That file is the only one in the web app that imports @tensorflow-models/coco-ssd. The Motion and sound page and Lost and Found load no model: they compare pixels with arithmetic, which the next post, on webcam motion detection in JavaScript, takes apart. These are the loader’s working lines:
const tf = await import('@tensorflow/tfjs');
const coco = await import('@tensorflow-models/coco-ssd');
await tf.setBackend('webgl');
await tf.ready();
if (!routerRegistered) {
// TensorFlow's router contract uses null for a non-match, although its
// published type omits null (the library is built without strict nulls).
const router = (url: string | string[]) => url === MODEL_ROUTE
? tf.io.browserHTTPRequest(MODEL_URL, { fetchFunc: cachedModelFetch })
: null;
tf.io.registerLoadRouter(router as Parameters<typeof tf.io.registerLoadRouter>[0]);
routerRegistered = true;
}
model = await coco.load({ base: 'lite_mobilenet_v2', modelUrl: MODEL_ROUTE });detection-model.ts, lines 84–97 at commit 017b33bBoth imports are dynamic, so the TensorFlow.js scripts load the first time the loader runs, not with the page. MODEL_ROUTE is an address of SafeOS’s own, safeos-model://coco-ssd-v1. The router registered for it turns a load of that address into an HTTP load of MODEL_URL, and gives TensorFlow.js a fetch function of SafeOS’s own for every request, which the section after next shows.
What the file is
MODEL_URL points at TensorFlow’s own copy on Google’s storage, storage.googleapis.com/tfjs-models/savedmodel/ssdlite_mobilenet_v2/model.json (detection-model-facts.ts). TensorFlow lists it on Kaggle as the TF.js deployment of ssdlite_mobilenet_v2, a network from its object detection model zoo trained on the COCO dataset, available as the ssdlite_mobilenet_v2_coco_2018_05_09 archive, under the Apache License 2.0 and published on npm as @tensorflow-models/coco-ssd (TensorFlow’s listing). SSDLite is the object-detection framework the MobileNetV2 paper introduced for mobile networks. The npm package calls itself “a TensorFlow.js port of the COCO-SSD model” and knows 80 classes of object (its README). At this commit the lockfile resolves @tensorflow/tfjs 4.22.0 and @tensorflow-models/coco-ssd 2.2.3 (package-lock.json).
The manifest, model.json, is 527,315 bytes, and the weight files it lists hold 18,034,528 bytes: 18.6 MB in all. Every SafeOS page that states the size prints it from those two constants (detection-model-facts.ts). The manifest describes a graph of 641 nodes holding about 4.5 million weights stored as 32-bit floats.
18.6 MB, only after a yes, kept in Cache Storage
Nothing downloads until setup is finished and the person presses the download key on People, Wildlife or Settings, Models. The hook those pages use, useDetectionModel(), starts the load on its own only when setup is complete and an agreement is already stored. Its download() stores the agreement under the localStorage key safeos-detection-model-consent and starts the load (detection-model.ts). Every request TensorFlow.js makes for the manifest and the weight files then goes through this function:
const cachedModelFetch: typeof fetch = async (input, init) => {
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
let cache: Cache | null = null;
try {
if (typeof caches === 'undefined') throw new Error('Cache Storage is unavailable.');
cache = await caches.open(MODEL_CACHE);
const cached = await cache.match(url);
if (cached) return cached;
} catch (error) {
cache = null;
refuseStorage(error);
}
const response = await fetch(input, init);
if (!response.ok) throw new Error(`Model download returned HTTP ${response.status}.`);
if (cache) {
try { await cache.put(url, response.clone()); } catch (error) { refuseStorage(error); }
}
return response;
};detection-model.ts, lines 42–60 at commit 017b33bA response already in the cache comes back without touching the network. A new one is written to the cache safeos-detection-model-v1 and only then handed to TensorFlow.js, so a model the page reports as saved is also there for the next start without a connection. Where the browser has no Cache Storage or refuses the write, as a private window or a full quota can, the model still loads from the network and the page says it is not saved.
Each file is stored under its own address, so a download cut short leaves some files and not others. The page says the model is on this device only when the agreement is stored and the manifest and every weight file the manifest lists are in the cache (model-on-device.ts). The model outlives app updates: when a new build takes over, the service worker deletes the caches whose names start with safeos-shell- or read safeos-v and a number, and the model’s is neither (sw.js). “Clear all data on this device” does delete it, with every other cache whose name starts with safeos (local-data.ts).
Google’s storage serves the files, so Google sees the device’s IP address when the browser downloads them. The privacy page lists that connection with the others and how to stop each one.
WebGL first, the processor when it will not start
The loader asks for the WebGL backend and then waits for tf.ready(). In TensorFlow.js 4.22.0, setBackend answers false when a backend fails to start, and ready() then starts the registered backends in priority order and keeps the first that works (engine.js). WebGL is registered at priority 2 (its base.js) and the plain JavaScript CPU backend at 1 (its base.js). SafeOS does not read setBackend’s answer, so on a device where WebGL will not start the model runs on the processor and the page shows no message about it. TensorFlow.js writes “Initialization of backend webgl failed” to the browser’s console.
A browser that has WebGL can still refuse it to TensorFlow.js, which asks for its context with failIfMajorPerformanceCaveat: true (canvas_util.js). MDN describes that flag as indicating “if a context will be created if the system performance is low or if no hardware GPU is available” (MDN, Mozilla Contributors, CC BY-SA 2.5). The difference is large: TensorFlow’s guide calls the WebGL backend “up to 100x faster than the vanilla CPU backend” (TensorFlow, CC BY 4.0).
SafeOS’s own measurements show the processor’s side. Each push to master starts the Measure workflow on a GitHub-hosted runner with no graphics card. WebGL would not start there, so the model ran on the cpu backend: a median of 1.7 s a check with the processor at full speed, and 10.8 s with it slowed 6 times. On one server computer with no graphics card, its processor slowed to stand in for a phone. No real phone was measured.
Two more details of where the work runs. The package switches to the CPU backend for its last step, the suppression of overlapping boxes, even after the graph ran on WebGL, and switches back afterwards (coco-ssd’s index.js). And SafeOS starts no Web Worker: the check loop, the gate and each call into the model run on the page’s main thread.
From the camera to 320 by 240, and to 300 by 300 inside the graph
The camera feed asks the browser for 1280 by 720 (camera-constraints.ts). That is an ideal, so the camera may give another size. Whatever arrives, each detector draws the whole video frame into a canvas of its own, 320 by 240 pixels, with one drawImage(video, 0, 0, width, height) (person-detection.ts for People, animal-detection.ts for Wildlife). The frame is scaled to fit that size, so a wide picture is squeezed sideways rather than cropped.
The package reads the canvas into a tensor with tf.browser.fromPixels, adds a batch dimension and runs the graph (coco-ssd’s index.js). The graph’s first steps resize whatever it is given: its ResizeBilinear node takes its size from a constant stored in the last weight file, and that constant is 300 by 300. The network looks at that square, whatever size the canvas has.
A gate before the model
Neither page runs the model on every frame. Each check first compares the new canvas with the one before it, cell by cell, and the model runs only when one part of the picture changed enough:
export function subjectMotionLevel(current: ImageData, previous: ImageData | null): number {
const { width, height, data } = current;
if (!previous || previous.width !== width || previous.height !== height) return 0;
const before = previous.data;
const columns = Math.min(8, width);
const rows = Math.min(6, height);
let largestMean = 0;
for (let row = 0; row < rows; row++) {
const top = Math.floor(row * height / rows);
const bottom = Math.floor((row + 1) * height / rows);
for (let column = 0; column < columns; column++) {
const left = Math.floor(column * width / columns);
const right = Math.floor((column + 1) * width / columns);
let change = 0;
for (let y = top; y < bottom; y++) {
const start = (y * width + left) * 4;
const end = start + (right - left) * 4;
for (let i = start; i < end; i += 4) {
change += Math.abs(data[i] - before[i])
+ Math.abs(data[i + 1] - before[i + 1])
+ Math.abs(data[i + 2] - before[i + 2]);
}
}
const mean = change / ((bottom - top) * (right - left) * 3);
largestMean = Math.max(largestMean, mean);
}
}
return largestMean * 100 / 255;
}subject-motion-gate.ts, lines 5–36 at commit 017b33bThe canvas is cut into 8 by 6 cells, 40 by 40 pixels each. A cell’s change is the mean of the absolute red, green and blue differences between this check and the last one, over every pixel of the cell, scaled from 0 to 255 onto 0 to 100. The reading is the largest cell’s change, and the model runs when it reaches 15. Under that line People’s detector returns nothing and the page keeps the count it had; Wildlife’s returns an empty list (person-detection.ts; animal-detection.ts).
A worked example, arithmetic from that code and nothing measured: if every pixel over half of one cell changes by 80 of 255 levels in each colour, the cell reads 15.7 and the gate opens. The same change over a third of the cell reads 10.5, and the model stays idle. Because the reading is the largest cell and not the whole frame, a change in one corner is not averaged away by the still parts of the picture.
Both pages start with the line at 15. Wildlife’s settings move it from 5 to 50 under “Movement to start the check” (page.tsx); People shows no control for it. People checks every 500 ms by default, and never more often than every 250 ms, whatever its setting; Wildlife checks every 1 s (page.tsx; page.tsx). A tick that comes while a check is still running is skipped.
One rule skips the gate. While a People alert is on, the page runs the model every five seconds, whatever moved, to see whether the people it counted are still there:
const now = Date.now();
const shouldForce =
(armingState === 'triggered' || alertActiveRef.current) &&
now - lastForceDetectionRef.current >= 5000;
const result = shouldForce
? await detectorRef.current.forceDetection(video)
: await detectorRef.current.processFrame(video);page.tsx, lines 425–432 at commit 017b33bWhat comes out
The model returns a list of boxes. Each has a position and a size in the canvas’s pixels, a class name from the package’s list of 80, and a score from 0 to 1. Inside the package each box takes the class with its highest score, and one suppression step for all classes keeps the strongest of any boxes that overlap. The step uses the score line twice, as the overlap allowed and as the lowest score kept: nonMaxSuppression(boxes2, maxScores, maxNumBoxes, minScore, minScore) (coco-ssd’s index.js). SafeOS asks for at most 10 boxes at a score line of 0.5.
People keeps the boxes whose class is person and counts them (person-detection.ts). When the count is over the number of people the person allows, the page raises its alert. It counts shapes the model calls a person. It does not know who anyone is. Wildlife keeps the boxes whose class is one of the 10 animals the model knows, dog, cat, bird, horse, sheep, cow, elephant, bear, zebra and giraffe, from the one list every page prints them from (animal-kinds.ts). Wildlife’s “Alert line” moves the score line from 10 to 90 hundredths (page.tsx).
Limits
Nothing measures how often People or Wildlife is right or wrong. TensorFlow’s model table gives a score for the original network, run by another program at another size and without SafeOS’s canvas or gate, so this post prints no figure from it.
- Something small or far away may change less than one cell’s line, and then the model does not run.
- A change of light changes every cell, so it can open the gate as movement does.
- The model knows 80 classes. An animal outside them is not kept, and the model can give a wrong class with a score over the line.
- The timings come from a server with its processor slowed to stand in for a phone. No phone was measured.
- The model and the checks share the page’s main thread with everything else on it, and a browser slows the timers of a tab it hides.
SafeOS adds an alert. It does not replace a person nearby. A phone or a browser can sleep, lose power or drop the camera, so stay within reach.
Next: webcam motion detection in JavaScript, plus sound levels, the checks the Motion and sound page runs with no model at all.
Object detection: COCO-SSD, ssdlite_mobilenet_v2, by the TensorFlow authors, Apache License 2.0, trained on the COCO dataset. COCO’s annotations are © COCO Consortium, CC BY 4.0 (terms of use). TensorFlow.js, Apache License 2.0. TensorFlow, the TensorFlow logo and any related marks are trademarks of Google Inc. Other product names belong to their owners; SafeOS is not affiliated with them.
— The Frame.dev Team