realias.py - undo anti-aliasing, resampling blur and compression artefacts on
flat-colour images (cartoons, clipart, pixel art, logos, line art) and snap
every pixel back to a small palette of solid colours.
Nothing here needs tuning per image: every threshold is measured from the image
itself. The pipeline:
1. MEASURE noise level (JPEG-style speckle) from the flat areas.
2. REGIONS Palette #1 comes from "flat" pixels - pixels in a 2x2 block of
(near) identical colour. Anti-aliased edge pixels almost never
form such a block, so the big fills fall out cleanly at any image
size, with no pixel-count threshold to hand-tune.
3. CALIBRATE Work out how far real edge pixels stray from a perfect blend of
their neighbours in *this* image (lossless AA hugs the ideal
mixing line; JPEG ringing does not, and JPEG smears colour wider
than brightness) and how wide the blurred edge bands are.
4. FEATURES Thin / small things (1px outlines, lettering, eyes, sparkles)
never form a 2x2 block. A pixel colour that cannot be explained
as a blend of palette colours that are actually nearby is a
genuine colour and is promoted to the palette, most extreme
first; the blended flanks of a stroke are then explained by it
and correctly thrown away instead of becoming fake colours.
5. LABEL Every pixel gets the nearest palette colour among the colours
physically close to it (plus the colour it is blended with), so
an edge pixel picks one of the two regions it sits between, and
thin strokes are biased to stay connected instead of dissolving.
6. REGULARISE Boundaries are smoothed with a small MRF (Potts prior, solved by
iterated conditional modes): specks that only marginally prefer
their own colour join their surroundings and edges lose their
jaggies, while pixels that clearly ARE another colour and
1-pixel gaps in strokes are kept / closed.
7. CLEAN UP Near-identical shades of one stroke colour (lettering, outlines)
are unified into a single colour; small islands and thin
slivers that are only a slightly different shade of what
surrounds them are absorbed; stray shades of a bigger colour
and one-off colours are folded away; and flat regions that are
rectangles apart from a ragged rim become exact rectangles.