Files
skills/docs/media/image/image-quantisation/src/spatial/cleanup/cleanup.md
2026-05-29 08:20:56 +01:00

2.1 KiB

Spatial Cleanup

(no submodules)

Purpose

Merge small anti-aliasing pools into their nearest spatial neighbours by colour distance. This preserves intentional detail while removing AA noise. Unlike global k-means quantisation, spatial cleanup only merges pools that are physically adjacent, so a small blue dot next to a red region stays blue while a near-red edge pixel gets absorbed into the red region.

Features

  • Spatially-aware merge (not global k-means)
  • Configurable colour distance and pool size thresholds
  • Returns a new pixel buffer (non-destructive)
  • Fast pixel-to-pool index lookup via Int32Array

Usage: Basic Example

import {
    detectPools,
    spatialCleanup,
} from "@suaveplan/image-quantisation";

const pools = detectPools(pixels, 32, 32);
const cleaned = spatialCleanup(pixels, 32, 32, pools);

Usage: Advanced Example

import {
    detectPools,
    spatialCleanup,
    countUniqueColours,
} from "@suaveplan/image-quantisation";

const pools = detectPools(pixels, 64, 64);
const before = countUniqueColours(pixels, 64, 64);

const cleaned = spatialCleanup(pixels, 64, 64, pools, {
    maxDistance: 25,
    maxPoolSize: 3,
});

const after = countUniqueColours(cleaned, 64, 64);
console.log(`Removed ${before - after} colours`);

API Reference

spatialCleanup(pixels, width, height, pools, options?): Uint8Array

  • pixels — RGBA Uint8Array
  • width, height — image dimensions
  • pools — array of Pool from detectPools
  • options.maxDistance — default 30
  • options.maxPoolSize — default 4

Returns a new Uint8Array with merged pixels.

countUniqueColours(pixels, width, height): number

Counts distinct colours in the buffer using a 32-bit packed key.

Implementation Notes

The algorithm builds an adjacency map for pools that are physically adjacent in the image. For each small pool, it finds the neighbour with the minimum rgbDistance. If the distance is within maxDistance, the pool is recoloured. The pixel-to-pool index is stored in an Int32Array initialised to -1 for fast O(1) lookup during adjacency building.