Image similarity by colour histogram, k-means and edges
SafeOS’s Lost and Found compares what the camera sees with photos of a lost pet, in the browser and with no trained model. This post takes that image similarity apart: what each photo becomes, the four parts of the summary, how several photos combine, how a camera picture is cut into regions and scored, and what the score cannot tell apart. Each part is a few loops over pixels. To use it at home, watch the door for a lost cat or dog with an old phone.
The short version sits in the Lost and Found section of how SafeOS watches a room in your browser. The previous post, webcam motion detection in JavaScript, covers the frame differencing the same page runs beside it.
What one photo becomes
The person adds 1 to 5 photos of the pet, each under 10 MB, and the browser keeps each at up to 768 px on its long edge as a JPEG of quality 0.9 (pet-photo-limits.ts; LostFoundSetup.tsx). For its summary each kept photo is drawn into a canvas of up to 256 by 256 pixels, never enlarged (visual-fingerprint.ts; visual-fingerprint.ts), and those pixels give a colour histogram, a set of main colours, an average colour, an edge grid and a size share (visual-fingerprint.ts).
SafeOS calls this summary a visual fingerprint: a summary of colours, an edge grid and a size, not a mark that identifies one animal. The sections below build it one part at a time.
- A pet’s photo, read at up to 256 by 256 pixels.
- Four parts:
- Colours: 32 of up to 64 buckets
- 5 main colours
- An 8 by 8 edge grid
- The size share, from the corners
- The parts of every photo of the pet merge into one summary.
A colour histogram of up to 64 buckets
Every pixel goes into a bucket by its colour:
function histogramLevels(buckets: number): number {
return Math.max(1, Math.ceil(Math.cbrt(buckets)));
}
/**
* Quantize color to reduce to bucket
*/
function quantizeColor(r: number, g: number, b: number, levels: number): string {
const step = 256 / levels;
const qr = Math.floor(r / step);
const qg = Math.floor(g / step);
const qb = Math.floor(b / step);
return `${qr}-${qg}-${qb}`;
}visual-fingerprint.ts, lines 177–190 at commit 017b33bThe summary asks for 32 buckets, and the cube root of 32, rounded up, is 4. So red, green and blue are each cut into 4 levels 64 wide, which makes 64 possible buckets. Each bucket keeps how many pixels fell into it, their share of the photo, and a running average of their colours, so a bucket’s colour is the colour that was there, not the corner of its cube. The 32 largest buckets are kept (visual-fingerprint.ts).
5 main colours by k-means with a fixed start
The main colours come from k-means clustering over one pixel in four, every fourth pixel along the rows (visual-fingerprint.ts). The start is the part worth copying:
// Simple k-means clustering
let centroids: RGB[] = [];
// Initialize centroids with evenly spaced pixels
const step = Math.floor(pixels.length / count);
for (let i = 0; i < count && i * step < pixels.length; i++) {
centroids.push({ ...pixels[i * step] });
}
// Run k-means iterations
for (let iter = 0; iter < 10; iter++) {visual-fingerprint.ts, lines 304–314 at commit 017b33bThe centres start at evenly spaced pixels of the sample, with nothing random. Each of the 10 rounds gives every pixel to its nearest centre by straight distance in red, green and blue, then moves each centre to the mean of its pixels (visual-fingerprint.ts). Because the start is fixed, the same photo always gives the same 5 colours, and the colours and edges of a summary built today equal those of one built tomorrow from the same file.
An 8 by 8 edge grid from neighbour differences
Colours say nothing about outline, so the summary adds a coarse map of where the picture changes sharply. Each cell of an 8 by 8 grid is measured like this:
for (let y = startY; y < endY; y += 2) {
for (let x = startX; x < endX; x += 2) {
const idx = (y * width + x) * 4;
const idxRight = idx + 4;
const idxDown = idx + width * 4;
if (idxRight < data.length && idxDown < data.length) {
// Horizontal gradient
const hGrad = Math.abs(data[idx] - data[idxRight]) +
Math.abs(data[idx + 1] - data[idxRight + 1]) +
Math.abs(data[idx + 2] - data[idxRight + 2]);
// Vertical gradient
const vGrad = Math.abs(data[idx] - data[idxDown]) +
Math.abs(data[idx + 1] - data[idxDown + 1]) +
Math.abs(data[idx + 2] - data[idxDown + 2]);
edgeStrength += Math.sqrt(hGrad * hGrad + vGrad * vGrad);
samples++;
}
}
}
strengths.push(samples > 0 ? edgeStrength / samples : 0);visual-fingerprint.ts, lines 430–453 at commit 017b33bOver every second pixel each way, the code takes the step to the pixel on the right and the step to the pixel below, each summed over red, green and blue, and adds the length of the two steps. The cell’s strength is the mean over its samples. It is a plain difference between neighbours, with no smoothing step and no kernel. Strengths go onto a fixed scale where 255 reads 100 and anything stronger reads 100 too (visual-fingerprint.ts; visual-fingerprint.ts). The code’s own example: a cell where every sample steps 60 levels in each colour, right and down, has steps of 180 each way and a length of 255, so it reads 100. The camera’s regions are read on the same scale, so a camera’s noise on a blank wall reads as weak as it is.
Size: the share unlike the corners
The last part guesses how much of the photo the pet fills. The mean colour of a small square in each of the four corners stands for the background (visual-fingerprint.ts), and every pixel further than 50 from it counts as subject:
// Count non-background pixels
let foregroundPixels = 0;
const bgThreshold = 50; // Distance threshold
for (let i = 0; i < data.length; i += 4) {
const pixel = { r: data[i], g: data[i + 1], b: data[i + 2] };
if (colorDistance(pixel, bgColor) > bgThreshold) {
foregroundPixels++;
}
}
return foregroundPixels / totalPixels;visual-fingerprint.ts, lines 549–560 at commit 017b33bIts errors are easy to predict. A busy background, a rug or a sofa, counts as subject; a pet the colour of its background counts as background. A photo cropped close to the pet gives a size share, and colours, that are mostly the pet’s.
Several photos become one
Each photo’s summary is built alone, and then the summaries are merged (LostFoundSetup.tsx; visual-fingerprint.ts):
- The histograms are joined by nearest colour. A bucket of a further photo joins the merged bucket nearest to it when the two are closer than one bucket is wide, each photo counts the same, and the 32 largest merged buckets are kept (
visual-fingerprint.ts). - The main colours of all the photos are grouped by distance, and the centres of the largest groups are kept (
visual-fingerprint.ts). - The average colour, its spread and the size share are averaged over the photos.
- The edge grids are averaged cell by cell.
Two photos of a pet from different sides add both sides’ colours to one summary, and a photo of the pet on a red blanket adds the blanket.
Comparing a camera picture
On the Motion and sound page, the comparison runs on its own timer:
useEffect(() => {
if (!isLostFoundWatching || !activeSubject) return;
const intervalMs = Math.max(250, Math.min(1500, lostFoundSettings.processingMode === 'local' ? 500 : 900));
const interval = setInterval(() => {
const video = videoRef.current;
if (video) {
processLostFoundFrame(video);
}
}, intervalMs);page.tsx, lines 325–334 at commit 017b33bThat is every 500 ms in Lost and Found’s local mode, its default, and every 900 ms in its hybrid mode, which runs the same comparison (lost-found-store.ts). Each comparison runs to its end before the next starts, and it reads the camera’s frame at the size the camera gives (subject-matcher.ts). Four steps follow.
- Light. Where the background cells of the frame changed together, as a lamp switched on changes them, the frame is moved back toward the scene’s settled brightness by the median of their change, at most 64 levels, the same on red, green and blue (
subject-matcher.ts;subject-matcher.ts). - A quick check of the whole picture. Its average colour counts 0.4 and the closest pair between the pet’s first main colours and a few main colours of the picture counts 0.6. Under 25, half of the lower line of 50, the comparison stops there (
subject-matcher.ts;visual-fingerprint.ts). - What moved. The frame is cut into 8 by 8 cells, and a cell has moved when its mean change in red, green and blue since the last picture is more than 10 levels (
subject-matcher.ts). - Regions. Overlapping regions of 2 by 2 cells are scored, but only those that touch a cell that moved:
for (let gy = 0; gy < gridSize - 1; gy++) {
for (let gx = 0; gx < gridSize - 1; gx++) {
// Skip if no motion in this region (when motion priority enabled).
// A region covers four cells of the motion mask; it is scanned when
// any of them moved, so motion in the last column or row of cells is
// covered by the regions that end there.
if (this.settings.motionPriority && this.motionMask.length > 0) {
const maskIdx = gy * gridSize + gx;
const moved =
this.motionMask[maskIdx] ||
this.motionMask[maskIdx + 1] ||
this.motionMask[maskIdx + gridSize] ||
this.motionMask[maskIdx + gridSize + 1];
if (!moved) {
continue;
}
}
// Extract region (2x2 cells for overlap)
const regionX = gx * cellWidth;
const regionY = gy * cellHeight;
const regionW = cellWidth * 2;
const regionH = cellHeight * 2;subject-matcher.ts, lines 654–676 at commit 017b33bAn 8 by 8 grid has 7 starting places each way, so there are 49 regions, each overlapping its neighbours by half. On the first picture there is no older frame to compare with, so every region is scored. Each region gets a summary of its own, made the same way as the pet’s but smaller, with its edges read on the pet’s grid:
private createQuickFingerprint(imageData: ImageData): VisualFingerprint {
const colorHistogram = extractColorHistogram(imageData, 16);
const dominantColors = extractDominantColors(imageData, 3);
const averageColor = calculateAverageColor(imageData);
// Edge signatures are compared cell by cell, so the region is read on the
// grid the subject was enrolled on. A subject whose signature is not a
// square grid has no cells to line up with; its region is read on the
// default grid and its edge term is 0.
const edgeGrid = edgeGridSide(this.fingerprint?.edgeSignature ?? []) || DEFAULT_EDGE_GRID_SIZE;
// A subject saved by version 1 that has not been rebuilt from its photos has
// edges scaled to each photo's strongest cell; the region is read the
// same way, so the two are compared on one scale.
const current = this.fingerprint === null || isCurrentFingerprint(this.fingerprint);
const edgeSignature = current
? regionEdgeSignature(imageData, edgeGrid)
: extractVersion1EdgeSignature(imageData, edgeGrid);
const sizeRatio = estimateSizeRatio(imageData);subject-matcher.ts, lines 771–787 at commit 017b33b- The camera’s picture, every 500 ms, or 900 ms in Lost and Found’s hybrid setting.
- The quick check of the whole picture. Under 25: stop until the next picture.
- 8 by 8 cells give 49 overlapping regions of 2 by 2 cells.
- Only regions that touch a cell that moved go on.
- Each region’s score: 0.4 colours + 0.35 main colours + 0.15 edges + 0.1 size.
- The best region at 70 or more raises a possible sighting: the picture beside the pet’s photo, for you to check.
The score: four weights, two lines, a scale
Each region’s summary is scored against the pet’s in four parts, each from 0 to 100:
// Weighted overall score
const overall = Math.round(
colorMatch * weights.color +
dominantMatch * weights.dominant +
edgeMatch * weights.edge +
sizeMatch * weights.size
);visual-fingerprint.ts, lines 976–982 at commit 017b33b- Colours, 0.4. For each of the pet’s buckets, the region’s closest bucket counts by how near the two colours are and by how near their shares are, in the lines below. The pet’s larger buckets count for more (
visual-fingerprint.ts). - Main colours, 0.35. For each of the pet’s main colours, the closest of the region’s, on a distance that weighs red, green and blue unequally (
visual-fingerprint.ts;visual-fingerprint.ts). - Edges, 0.15. 100 minus the mean difference between the two grids, cell by cell (
visual-fingerprint.ts). - Size, 0.1. 100 when the two size shares are equal, dropping in a straight line to 0 at a difference of 50 points (
visual-fingerprint.ts).
const dist = colorDistance(bucket1.color, bucket2.color);
const colorSimilarity = Math.max(0, 1 - dist / 442); // 442 = max RGB distance
const percentSimilarity = 1 - Math.abs(bucket1.percentage - bucket2.percentage) / 100;visual-fingerprint.ts, lines 1009–1011 at commit 017b33bThe colour term reaches 0 at the longest distance two colours can have, the diagonal of the RGB cube, 441.7, which the code rounds up. The share term is 1 minus the difference between the two buckets’ shares of their pictures.
A colour sensitivity of 50, the default, leaves the score as it is. A lower sensitivity raises scores, and a higher one moves a score further from 100, so near scores drop and 100 stays 100 (subject-matcher.ts).
Two lines read the result. The best region at 70 or more raises a possible sighting (subject-matcher.ts). 50 is the lowest score a region is kept at, and half of it is where the quick check stops (subject-matcher.ts). No entry or picture is saved for a comparison under the sighting line (page.tsx; lost-found-store.ts).
The score is a line on a scale, not a likelihood. It says how close two summaries of colours, edges and size are; it does not say how likely it is that the pet is in view, and Lost and Found’s screens show no score (lost-found-words.ts).
What a possible sighting keeps
A comparison at or over the line starts a run of alerts:
// A sighting's run: a check at or over the alert line starts it, it alerts
// again after the Cooldown Period while such checks go on, and it ends after
// 30 seconds with none. One entry a run.
const sightingEventRef = useRef<DetectorEvent>(newDetectorEvent());page.tsx, lines 270–273 at commit 017b33bEach of the run’s alerts asks the question “Could this be” and the pet’s name, keeps the camera’s picture with a box round the region that came close, plays the pet’s sound and asks for a notification if the browser allows one (page.tsx; words.ts). The run’s History entry holds the pet’s name and that picture, and the gallery shows the kept sightings (client-db.ts). The person compares the picture with the pet’s photo and decides.
SafeOS’s own checks run Lost and Found the same way: one enrols three photos of the sample clip’s kitten and fails when the watch raises no sighting on that clip (lost-found-probe.mjs; photos.json). Two of these three photos are frames of the same recording as that clip, so the check shows how it works, not how well.
Limits
- Another animal, or a cushion or a bag in similar colours, can raise a possible sighting. The summary holds colours and a coarse outline, nothing that belongs to one animal.
- The background in a photo counts: it enters the histogram, the main colours and the size share.
- A change of light larger than the correction, or a camera that shifts its colours, changes every part of the score.
- Lost and Found is for pets only.
- Nothing measures how often it is right.
- Speed depends on the device. On the Measure run, with the camera fed from the sample clip, 640 by 480 pixels, Lost and Found compared 2 pictures a second at the processor’s own speed and 0.63 a second 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.
- The comparison runs on the page’s main thread, beside the motion and sound checks.
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: how a PWA works offline: precaching and browser storage, on how SafeOS keeps its own files, the pet’s photos and its summaries in the browser.
— The Frame.dev Team