@xprite/pixelate 0.1.3 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/pixelate.js CHANGED
@@ -1,29 +1,29 @@
1
1
  import { assertDimension, assertPixelBuffer } from "./base.js";
2
- import { protectPixelationContours } from "./contours.js";
3
2
  import { smoothPixelation } from "./denoise.js";
4
3
  import { blockPartition } from "./grid.js";
5
4
  import { prepareGridSampling } from "./grid-sampling.js";
5
+ import { kuwaharaPrepass } from "./kuwahara.js";
6
6
  import { runPixeloe } from "./line-guided/pixeloe-entry.js";
7
- import { resizeMostFrequent } from "./most-frequent.js";
8
7
  import { applyOutlinePrepass, DEFAULT_LINE_GUIDE, runsStockPixeloe, } from "./outline-prepass.js";
9
- import { removeOrphanPixels } from "./orphan-pixels.js";
8
+ import { cleanStraySpeckles, removeOrphanPixels } from "./orphan-pixels.js";
10
9
  import { snapPalette } from "./palette-snap.js";
11
10
  import { settlePixelAlpha } from "./pixel-alpha.js";
12
11
  import { detectWithAlgorithm, detectWithAlgorithmAsync, recoverWithGrid, } from "./pixelation-algorithm-registry.js";
12
+ import { resizeCrisp2Means } from "./resize-crisp.js";
13
+ import { resizeLanczos } from "./resize-lanczos.js";
13
14
  import { resizeBox, resizeNearest } from "./resize.js";
14
15
  import { samplePixelation } from "./sampling.js";
15
- import { OutlinePrepass, PixelationDither, PixelationMethod, PixelationMode, PixelationAlgorithm, } from "./types.js";
16
+ import { OutlinePrepass, PixelationAlgorithm, PixelationDither, PixelationMethod, PixelationMode, } from "./types.js";
16
17
  const WORKING_SCALE = 4;
17
18
  const MAX_WORKING_PIXELS = 1_048_576;
18
19
  const MAX_OUTLINE_STRENGTH = 100;
19
- function prepareSource(image, target, outlineStrength) {
20
+ function capWorkingSize(image, target) {
20
21
  const scale = Math.min(WORKING_SCALE, Math.sqrt(MAX_WORKING_PIXELS / (target.width * target.height)));
21
22
  const width = Math.min(image.width, Math.max(1, Math.ceil(target.width * scale)));
22
23
  const height = Math.min(image.height, Math.max(1, Math.ceil(target.height * scale)));
23
- const working = image.width === width && image.height === height
24
+ return image.width === width && image.height === height
24
25
  ? image
25
26
  : resizeBox(image, width, height, "premultiplied");
26
- return protectPixelationContours(working, outlineStrength);
27
27
  }
28
28
  function uniformBlocks(image, target) {
29
29
  return {
@@ -33,68 +33,127 @@ function uniformBlocks(image, target) {
33
33
  algorithm: PixelationAlgorithm.UniformGrid,
34
34
  };
35
35
  }
36
- function sampleImage(image, options, method) {
37
- // Grid recovery runs when asked for, or when only an algorithm was named and it finds a reliable grid.
38
- const wantsGrid = options.mode === PixelationMode.RecoverGrid ||
39
- (options.mode === undefined && options.algorithm !== undefined);
40
- const grid = options.grid ??
41
- (wantsGrid
42
- ? detectWithAlgorithm(image, options.algorithm ?? PixelationAlgorithm.Auto)
43
- : undefined);
36
+ /**
37
+ * Strategy table for target-size samplers (`Working Image -> Target Grid`).
38
+ * Adding a new resize algorithm only requires registering an entry here.
39
+ */
40
+ const RESIZE_SAMPLERS = {
41
+ [PixelationMethod.Crisp]: (image, ctx) => resizeCrisp2Means(image, ctx.plan.target.width, ctx.plan.target.height, ctx.outlineStrength),
42
+ [PixelationMethod.Lanczos]: (image, ctx) => resizeLanczos(image, ctx.plan.target.width, ctx.plan.target.height, Boolean(ctx.options.kuwahara)),
43
+ [PixelationMethod.Nearest]: (image, ctx) => resizeNearest(image, ctx.plan.target.width, ctx.plan.target.height),
44
+ [PixelationMethod.Box]: (image, ctx) => resizeBox(image, ctx.plan.target.width, ctx.plan.target.height, ctx.alphaMode),
45
+ [PixelationMethod.Dominant]: (image, ctx) => samplePixelation(capWorkingSize(image, ctx.plan.target), ctx.plan.target.width, ctx.plan.target.height, PixelationMethod.Dominant),
46
+ [PixelationMethod.Structure]: (image, ctx) => samplePixelation(capWorkingSize(image, ctx.plan.target), ctx.plan.target.width, ctx.plan.target.height, PixelationMethod.Structure),
47
+ };
48
+ /** Stage 0: normalize Convert, CustomSize, and RecoverGrid into one of two concrete plans. */
49
+ function buildPlan(image, options, method, detectedGrid) {
44
50
  const mode = options.mode ??
45
- (grid && (!("reliable" in grid) || grid.reliable)
51
+ (detectedGrid && (!("reliable" in detectedGrid) || detectedGrid.reliable)
46
52
  ? PixelationMode.RecoverGrid
47
53
  : PixelationMode.Convert);
48
54
  if (mode !== PixelationMode.Convert && mode !== PixelationMode.RecoverGrid)
49
55
  throw new RangeError("Unknown pixelation mode.");
50
- const prepass = options.prepass ?? OutlinePrepass.None;
51
- const guide = prepass === OutlinePrepass.PixeloeLines ? (options.lineGuide ?? DEFAULT_LINE_GUIDE) : undefined;
52
56
  if (mode === PixelationMode.RecoverGrid) {
53
- const found = grid ?? detectWithAlgorithm(image, options.algorithm ?? PixelationAlgorithm.Auto);
54
- if ("reliable" in found && !found.reliable)
57
+ if (!detectedGrid || ("reliable" in detectedGrid && !detectedGrid.reliable))
55
58
  throw new Error("No consistent pixel grid was detected. Turn off Automatic grid and choose cell sizes.");
56
- const cell = (found.cellWidth + found.cellHeight) / 2;
57
- const analysis = found;
58
- const upright = prepareGridSampling(image, analysis);
59
- const gridForRecover = { ...analysis, rotation: undefined, sampling: undefined };
60
- // Custom size's even blocks with PixelOE + Contrast: stock PixelOE to that size.
61
- if (runsStockPixeloe({ ...options, mode }, found))
62
- return runPixeloe(upright, { width: found.width, height: found.height }, guide);
63
- return recoverWithGrid(applyOutlinePrepass(upright, cell, prepass, options.lineGuide), gridForRecover, options.colorPicker);
59
+ const upright = prepareGridSampling(image, detectedGrid);
60
+ const gridForRecover = { ...detectedGrid, rotation: undefined, sampling: undefined };
61
+ const target = { width: detectedGrid.width, height: detectedGrid.height };
62
+ if (detectedGrid.algorithm === PixelationAlgorithm.CustomSize) {
63
+ const prepass = options.prepass ?? OutlinePrepass.None;
64
+ const usesDirectResize = prepass === OutlinePrepass.None &&
65
+ (options.blockPicker === false ||
66
+ (Boolean(options.kuwahara) &&
67
+ (method === PixelationMethod.Crisp || method === PixelationMethod.Lanczos)));
68
+ return {
69
+ kind: "resize",
70
+ source: upright,
71
+ working: upright,
72
+ target,
73
+ preferBlockPicker: !usesDirectResize,
74
+ grid: gridForRecover,
75
+ };
76
+ }
77
+ return {
78
+ kind: "grid",
79
+ source: image,
80
+ working: upright,
81
+ target,
82
+ grid: gridForRecover,
83
+ };
64
84
  }
65
- const target = resolveTargetSize(image, options);
66
- // PixelOE + Contrast without a recovered grid is stock PixelOE: the reference result.
67
- if (runsStockPixeloe({ ...options, mode }, undefined))
68
- return runPixeloe(image, target, guide);
69
- // Otherwise an independent pre-pass; whatever sampler or colour picker follows works on its result.
70
- image = applyOutlinePrepass(image, (image.width / target.width + image.height / target.height) / 2, prepass, options.lineGuide);
71
- const strength = options.outlineStrength ?? 0;
72
- if (!Number.isFinite(strength) || strength < 0 || strength > MAX_OUTLINE_STRENGTH)
73
- throw new RangeError("Outline protection must be between 0 and 100.");
74
- if (options.blockPicker)
75
- return recoverWithGrid(image, uniformBlocks(image, target), options.colorPicker);
85
+ return {
86
+ kind: "resize",
87
+ source: image,
88
+ working: image,
89
+ target: resolveTargetSize(image, options),
90
+ preferBlockPicker: Boolean(options.blockPicker),
91
+ };
92
+ }
93
+ function wantsGridDetection(options) {
94
+ return (options.mode === PixelationMode.RecoverGrid ||
95
+ (options.mode === undefined && options.algorithm !== undefined));
96
+ }
97
+ /** Stage 1-3: unified synchronous pipeline shared by `pixelateImage` and `pixelateImageAsync`. */
98
+ function runPipeline(plan, options, method) {
99
+ const prepass = options.prepass ?? OutlinePrepass.None;
100
+ const guide = prepass === OutlinePrepass.PixeloeLines ? (options.lineGuide ?? DEFAULT_LINE_GUIDE) : undefined;
76
101
  const alphaMode = options.alphaMode ?? "straight";
77
102
  if (alphaMode !== "straight" && alphaMode !== "premultiplied")
78
103
  throw new RangeError("alphaMode must be 'straight' or 'premultiplied'");
79
- const prepared = strength || method === PixelationMethod.Dominant || method === PixelationMethod.Structure
80
- ? prepareSource(image, target, strength)
81
- : image;
82
- const { width, height } = target;
104
+ const outlineStrength = options.outlineStrength ?? 0;
105
+ if (!Number.isFinite(outlineStrength) || outlineStrength < 0 || outlineStrength > MAX_OUTLINE_STRENGTH)
106
+ throw new RangeError("Outline protection must be between 0 and 100.");
107
+ const ctx = { plan, options, method, prepass, alphaMode, outlineStrength };
108
+ const stockPixeloe = plan.kind === "resize" &&
109
+ runsStockPixeloe({
110
+ prepass,
111
+ colorPicker: options.colorPicker,
112
+ mode: plan.grid ? PixelationMode.RecoverGrid : PixelationMode.Convert,
113
+ }, plan.grid);
114
+ // Stage 1: Prepass strategy (optional Kuwahara simplification, then optional independent PixelOE prepass).
115
+ let working = plan.working;
116
+ if (plan.kind === "resize" && options.kuwahara) {
117
+ working = kuwaharaPrepass(working, plan.target);
118
+ }
119
+ if (!stockPixeloe && prepass !== OutlinePrepass.None) {
120
+ const cell = plan.kind === "grid"
121
+ ? (plan.grid.cellWidth + plan.grid.cellHeight) / 2
122
+ : (working.width / plan.target.width + working.height / plan.target.height) / 2;
123
+ working = applyOutlinePrepass(working, cell, prepass, options.lineGuide);
124
+ }
125
+ // Stage 2: Sampler strategy (end-to-end PixelOE, grid cell picker, or target-size sampler table).
83
126
  let sampled;
84
- switch (method) {
85
- case PixelationMethod.Nearest:
86
- sampled = resizeNearest(prepared, width, height);
87
- break;
88
- case PixelationMethod.Box:
89
- sampled = resizeBox(prepared, width, height, alphaMode);
90
- break;
91
- case PixelationMethod.MostFrequent:
92
- sampled = resizeMostFrequent(prepared, width, height);
93
- break;
94
- default:
95
- sampled = samplePixelation(prepared, width, height, method);
127
+ let needsAlphaSettle = false;
128
+ if (stockPixeloe) {
129
+ sampled = runPixeloe(working, plan.target, guide);
130
+ }
131
+ else if (plan.kind === "grid") {
132
+ sampled = recoverWithGrid(working, plan.grid, options.colorPicker);
96
133
  }
97
- return settlePixelAlpha(image, sampled);
134
+ else if (plan.preferBlockPicker) {
135
+ const grid = !plan.grid || working.width !== plan.working.width || working.height !== plan.working.height
136
+ ? uniformBlocks(working, plan.target)
137
+ : plan.grid;
138
+ sampled = recoverWithGrid(working, grid, options.colorPicker);
139
+ }
140
+ else {
141
+ sampled = RESIZE_SAMPLERS[method](working, ctx);
142
+ needsAlphaSettle = true;
143
+ }
144
+ // Stage 3: Unified alpha settlement for direct resize samplers.
145
+ if (needsAlphaSettle) {
146
+ sampled = settlePixelAlpha(plan.source, sampled);
147
+ }
148
+ // Stage 4: Postprocess + Quantizer strategy.
149
+ const crispSpeckleDeltaE = plan.kind === "resize" &&
150
+ !stockPixeloe &&
151
+ !plan.preferBlockPicker &&
152
+ method === PixelationMethod.Crisp &&
153
+ outlineStrength < 75
154
+ ? 0.22 * (1 - 0.7 * (outlineStrength / 100))
155
+ : 0;
156
+ return finishPixelation(sampled, plan.source, options, crispSpeckleDeltaE);
98
157
  }
99
158
  function sizeFromBlock(blockSize, image) {
100
159
  if (typeof blockSize === "number") {
@@ -156,13 +215,16 @@ function validateMethod(value) {
156
215
  throw new RangeError("Unknown pixelation method.");
157
216
  return method;
158
217
  }
159
- function finishPixelation(sampled, source, { removeNoise, paletteSnap, preserveDimensions }) {
218
+ function finishPixelation(sampled, source, { removeNoise, paletteSnap, preserveDimensions }, crispSpeckleDeltaE = 0) {
160
219
  let result = removeNoise ? smoothPixelation(sampled) : sampled;
161
220
  if (paletteSnap)
162
221
  result = snapPalette(result, paletteSnap);
222
+ const dither = paletteSnap?.dither;
223
+ const dithered = dither === PixelationDither.Ordered || dither === PixelationDither.FloydSteinberg;
224
+ if (crispSpeckleDeltaE > 0 && !dithered) {
225
+ result = cleanStraySpeckles(result, crispSpeckleDeltaE);
226
+ }
163
227
  if (removeNoise) {
164
- const dither = paletteSnap?.dither;
165
- const dithered = dither === PixelationDither.Ordered || dither === PixelationDither.FloydSteinberg;
166
228
  result = removeOrphanPixels(result, { absorbInterior: !dithered });
167
229
  }
168
230
  if (preserveDimensions && (result.width !== source.width || result.height !== source.height))
@@ -170,55 +232,28 @@ function finishPixelation(sampled, source, { removeNoise, paletteSnap, preserveD
170
232
  return result;
171
233
  }
172
234
  /**
173
- * Pixelate an RGBA buffer without touching the source. Nearest mode follows
174
- * nearest-neighbor `floor(dst * src / dst)` mapping. Box mode averages the
175
- * source area covered by each destination pixel. Local dominant and structural
176
- * sampling preserve contrasting regions; grid recovery restores one RGBA pixel
177
- * per detected cell. Limiting colours keeps each pixel's own alpha.
235
+ * Pixelate an RGBA buffer without touching the source.
236
+ * Uses a 4-stage strategy pipeline: Plan -> Prepass -> Sampler -> Alpha & Postprocess.
178
237
  */
179
238
  export function pixelateImage(image, options = {}) {
180
239
  assertPixelBuffer(image);
181
240
  const method = validateMethod(options.method);
182
- return finishPixelation(sampleImage(image, options, method), image, options);
183
- }
184
- async function sampleImageAsync(image, options, method) {
185
- const wantsGrid = options.mode === PixelationMode.RecoverGrid ||
186
- (options.mode === undefined && options.algorithm !== undefined);
187
241
  const grid = options.grid ??
188
- (wantsGrid
189
- ? await detectWithAlgorithmAsync(image, options.algorithm ?? PixelationAlgorithm.Auto)
242
+ (wantsGridDetection(options)
243
+ ? detectWithAlgorithm(image, options.algorithm ?? PixelationAlgorithm.Auto)
190
244
  : undefined);
191
- const mode = options.mode ??
192
- (grid && (!("reliable" in grid) || grid.reliable)
193
- ? PixelationMode.RecoverGrid
194
- : PixelationMode.Convert);
195
- if (mode !== PixelationMode.Convert && mode !== PixelationMode.RecoverGrid)
196
- throw new RangeError("Unknown pixelation mode.");
197
- const prepass = options.prepass ?? OutlinePrepass.None;
198
- const guide = prepass === OutlinePrepass.PixeloeLines ? (options.lineGuide ?? DEFAULT_LINE_GUIDE) : undefined;
199
- if (mode === PixelationMode.RecoverGrid) {
200
- const found = grid ??
201
- (await detectWithAlgorithmAsync(image, options.algorithm ?? PixelationAlgorithm.Auto));
202
- if ("reliable" in found && !found.reliable)
203
- throw new Error("No consistent pixel grid was detected. Turn off Automatic grid and choose cell sizes.");
204
- const cell = (found.cellWidth + found.cellHeight) / 2;
205
- const analysis = found;
206
- const upright = prepareGridSampling(image, analysis);
207
- const gridForRecover = { ...analysis, rotation: undefined, sampling: undefined };
208
- if (runsStockPixeloe({ ...options, mode }, found))
209
- return runPixeloe(upright, { width: found.width, height: found.height }, guide);
210
- return recoverWithGrid(applyOutlinePrepass(upright, cell, prepass, options.lineGuide), gridForRecover, options.colorPicker);
211
- }
212
- // Convert path is sync — reuse sampleImage body for non-recover.
213
- return sampleImage(image, { ...options, grid: undefined, mode: PixelationMode.Convert }, method);
245
+ return runPipeline(buildPlan(image, options, method, grid), options, method);
214
246
  }
215
247
  /**
216
- * Async pixelate for product Auto path (import-worker). Same output as pixelateImage;
217
- * Auto detect overlaps WASM AC+RL with proposers via Promise join (no COOP/COEP).
248
+ * Async counterpart of `pixelateImage`: only grid detection runs asynchronously (WASM consensus
249
+ * on a worker), then feeds the identical synchronous 4-stage pipeline.
218
250
  */
219
251
  export async function pixelateImageAsync(image, options = {}) {
220
252
  assertPixelBuffer(image);
221
253
  const method = validateMethod(options.method);
222
- const sampled = await sampleImageAsync(image, options, method);
223
- return finishPixelation(sampled, image, options);
254
+ const grid = options.grid ??
255
+ (wantsGridDetection(options)
256
+ ? await detectWithAlgorithmAsync(image, options.algorithm ?? PixelationAlgorithm.Auto)
257
+ : undefined);
258
+ return runPipeline(buildPlan(image, options, method, grid), options, method);
224
259
  }
@@ -5,6 +5,10 @@ export type Oklab = readonly [lightness: number, a: number, b: number];
5
5
  export declare function paletteCoordinates(color: Rgba): Rgba;
6
6
  /** Convert opaque sRGB bytes to OKLab coordinates. Cached per packed RGB. */
7
7
  export declare function rgbToOklab(r: number, g: number, b: number): Oklab;
8
+ /** Convert normalized sRGB floats (0..1) to OKLab. */
9
+ export declare function rgbFloatToOklab(r: number, g: number, b: number): Oklab;
10
+ /** Convert OKLab coordinates back to normalized sRGB floats (0..1). */
11
+ export declare function oklabToRgbFloat(lightness: number, a: number, b: number): [number, number, number];
8
12
  /** Convert OKLab coordinates back to 8-bit sRGB. */
9
13
  export declare function oklabToRgb(lightness: number, a: number, b: number): [number, number, number];
10
14
  /** Variance-driven color partitioning keeps accents instead of selecting only frequent shades. */
@@ -8,12 +8,10 @@ const LINEAR_DIVISOR = 12.92;
8
8
  const GAMMA_OFFSET = 0.055;
9
9
  const GAMMA_SCALE = 1.055;
10
10
  const GAMMA_EXPONENT = 2.4;
11
- const linear = (byte) => {
12
- const value = byte / UINT8_MAX;
13
- return value <= LINEAR_THRESHOLD
14
- ? value / LINEAR_DIVISOR
15
- : ((value + GAMMA_OFFSET) / GAMMA_SCALE) ** GAMMA_EXPONENT;
16
- };
11
+ const srgbFloatToLinear = (value) => value <= LINEAR_THRESHOLD
12
+ ? value / LINEAR_DIVISOR
13
+ : ((value + GAMMA_OFFSET) / GAMMA_SCALE) ** GAMMA_EXPONENT;
14
+ const linear = (byte) => srgbFloatToLinear(byte / UINT8_MAX);
17
15
  const LINEAR = Float64Array.from({ length: UINT8_MAX + 1 }, (_, byte) => linear(byte));
18
16
  const linearChannel = (byte) => (byte === 0 ? byte : (LINEAR[byte] ?? linear(byte)));
19
17
  // Oklab matrices published by Björn Ottosson (public domain):
@@ -71,23 +69,32 @@ export function rgbToOklab(r, g, b) {
71
69
  oklabCache.set(key, value);
72
70
  return value;
73
71
  }
74
- function srgbByteFromLinear(value) {
75
- const encoded = value <= LINEAR_TO_SRGB_THRESHOLD
76
- ? value * LINEAR_DIVISOR
77
- : GAMMA_SCALE * value ** (1 / GAMMA_EXPONENT) - GAMMA_OFFSET;
78
- return clampByte(encoded * UINT8_MAX);
72
+ /** Convert normalized sRGB floats (0..1) to OKLab. */
73
+ export function rgbFloatToOklab(r, g, b) {
74
+ return linearRgbToOklab(srgbFloatToLinear(r), srgbFloatToLinear(g), srgbFloatToLinear(b));
79
75
  }
80
- /** Convert OKLab coordinates back to 8-bit sRGB. */
81
- export function oklabToRgb(lightness, a, b) {
76
+ function linearToSrgbFloat(value) {
77
+ const c = Math.max(0, Math.min(1, value));
78
+ return c <= LINEAR_TO_SRGB_THRESHOLD
79
+ ? c * LINEAR_DIVISOR
80
+ : GAMMA_SCALE * c ** (1 / GAMMA_EXPONENT) - GAMMA_OFFSET;
81
+ }
82
+ /** Convert OKLab coordinates back to normalized sRGB floats (0..1). */
83
+ export function oklabToRgbFloat(lightness, a, b) {
82
84
  const l = dot(OKLAB_TO_LMS[0], lightness, a, b) ** 3;
83
85
  const m = dot(OKLAB_TO_LMS[1], lightness, a, b) ** 3;
84
86
  const s = dot(OKLAB_TO_LMS[2], lightness, a, b) ** 3;
85
87
  return [
86
- srgbByteFromLinear(dot(LMS_TO_LINEAR_SRGB[0], l, m, s)),
87
- srgbByteFromLinear(dot(LMS_TO_LINEAR_SRGB[1], l, m, s)),
88
- srgbByteFromLinear(dot(LMS_TO_LINEAR_SRGB[2], l, m, s)),
88
+ linearToSrgbFloat(dot(LMS_TO_LINEAR_SRGB[0], l, m, s)),
89
+ linearToSrgbFloat(dot(LMS_TO_LINEAR_SRGB[1], l, m, s)),
90
+ linearToSrgbFloat(dot(LMS_TO_LINEAR_SRGB[2], l, m, s)),
89
91
  ];
90
92
  }
93
+ /** Convert OKLab coordinates back to 8-bit sRGB. */
94
+ export function oklabToRgb(lightness, a, b) {
95
+ const [r, g, bl] = oklabToRgbFloat(lightness, a, b);
96
+ return [clampByte(r * UINT8_MAX), clampByte(g * UINT8_MAX), clampByte(bl * UINT8_MAX)];
97
+ }
91
98
  function box(samples) {
92
99
  const sum = [0, 0, 0, 0], squares = [0, 0, 0, 0];
93
100
  let count = 0;
@@ -0,0 +1,11 @@
1
+ import { type PixelBuffer } from "./base.ts";
2
+ /**
3
+ * Surround-contrast 2-means non-AA downsampler (C5):
4
+ * Splits each output cell in OKLab into two colour clusters instead of averaging across boundaries:
5
+ * - On straight edges, the dominant side wins cleanly with zero anti-aliased grey halo;
6
+ * - On thin bright (eye sclera, pearl, lantern), dark (pupil, ink line), or high-chroma (lips,
7
+ * iris, red seal) micro-features, the higher OKLab ΔE against the 3×3 cell surround wins cleanly.
8
+ * `detailStrength` (0-100, default 50) tunes the trade-off between clean flat clusters (0) and
9
+ * aggressive 1 px thin-line / micro-detail preservation (100).
10
+ */
11
+ export declare function resizeCrisp2Means(image: PixelBuffer, width: number, height: number, detailStrength?: number): PixelBuffer;
@@ -0,0 +1,213 @@
1
+ import { assertDimension, assertPixelBuffer, clampByte, UINT8_MAX } from "./base.js";
2
+ import { gaussianBlur, resizeAreaFloat, toFloatRgba, toOklabPlanes } from "./float-image.js";
3
+ import { oklabToRgbFloat } from "./quantization.js";
4
+ import { resizeNearest } from "./resize.js";
5
+ const WORKING_SCALE = 4;
6
+ const CHANNELS = 4;
7
+ const CRISP_CHROMA_WEIGHT = 2.2;
8
+ const CRISP_SURROUND_CHROMA_WEIGHT = 3.8;
9
+ const DEFAULT_CRISP_DETAIL = 50;
10
+ /**
11
+ * Surround-contrast 2-means non-AA downsampler (C5):
12
+ * Splits each output cell in OKLab into two colour clusters instead of averaging across boundaries:
13
+ * - On straight edges, the dominant side wins cleanly with zero anti-aliased grey halo;
14
+ * - On thin bright (eye sclera, pearl, lantern), dark (pupil, ink line), or high-chroma (lips,
15
+ * iris, red seal) micro-features, the higher OKLab ΔE against the 3×3 cell surround wins cleanly.
16
+ * `detailStrength` (0-100, default 50) tunes the trade-off between clean flat clusters (0) and
17
+ * aggressive 1 px thin-line / micro-detail preservation (100).
18
+ */
19
+ export function resizeCrisp2Means(image, width, height, detailStrength = DEFAULT_CRISP_DETAIL) {
20
+ assertPixelBuffer(image);
21
+ assertDimension(width, "width");
22
+ assertDimension(height, "height");
23
+ if (image.width <= width && image.height <= height) {
24
+ return resizeNearest(image, width, height);
25
+ }
26
+ const t = Math.max(0, Math.min(1, detailStrength / 100));
27
+ const surroundGain = 1.4 + 3.2 * t;
28
+ const countExponent = 0.92 - 0.16 * t;
29
+ const minFeatureRatio = 0.28 - 0.12 * t;
30
+ const splitThreshold = 0.07 - 0.035 * t;
31
+ const maxWorkW = Math.max(width, width * WORKING_SCALE);
32
+ const maxWorkH = Math.max(height, height * WORKING_SCALE);
33
+ const floatSrc = toFloatRgba(image);
34
+ const working = floatSrc.w > maxWorkW || floatSrc.h > maxWorkH
35
+ ? resizeAreaFloat(floatSrc, Math.min(floatSrc.w, maxWorkW), Math.min(floatSrc.h, maxWorkH))
36
+ : floatSrc;
37
+ const { r, g, b, a, w, h, opaque } = working;
38
+ const { L, A, B } = toOklabPlanes(working, 0.5);
39
+ const sx = w / width;
40
+ const sy = h / height;
41
+ const bgSigma = Math.max(1.2, ((sx + sy) * 0.5) * 1.125);
42
+ let Lbg = gaussianBlur(L, w, h, bgSigma);
43
+ let Abg = gaussianBlur(A, w, h, bgSigma);
44
+ let Bbg = gaussianBlur(B, w, h, bgSigma);
45
+ if (!opaque) {
46
+ // Normalize surround blur by visible-pixel weight so transparent pixels (L=0) never act
47
+ // like a fake black surround that suppresses dark outer outlines on transparent sprites.
48
+ const n = w * h;
49
+ const visMask = new Float32Array(n);
50
+ for (let i = 0; i < n; i++)
51
+ if (a[i] > 0.5)
52
+ visMask[i] = 1;
53
+ const wBg = gaussianBlur(visMask, w, h, bgSigma);
54
+ for (let i = 0; i < n; i++) {
55
+ const inv = wBg[i] > 1e-4 ? 1 / wBg[i] : 0;
56
+ Lbg[i] *= inv;
57
+ Abg[i] *= inv;
58
+ Bbg[i] *= inv;
59
+ }
60
+ }
61
+ const out = new Uint8ClampedArray(width * height * CHANNELS);
62
+ const pts = [];
63
+ for (let gy = 0; gy < height; gy++) {
64
+ const y0 = Math.floor(gy * sy);
65
+ const y1 = Math.min(h, Math.max(y0 + 1, Math.ceil((gy + 1) * sy)));
66
+ for (let gx = 0; gx < width; gx++) {
67
+ const x0 = Math.floor(gx * sx);
68
+ const x1 = Math.min(w, Math.max(x0 + 1, Math.ceil((gx + 1) * sx)));
69
+ pts.length = 0;
70
+ let total = 0;
71
+ let sBgL = 0;
72
+ let sBgA = 0;
73
+ let sBgB = 0;
74
+ for (let y = y0; y < y1; y++) {
75
+ const row = y * w;
76
+ for (let x = x0; x < x1; x++) {
77
+ const idx = row + x;
78
+ total += 1;
79
+ if (!opaque && a[idx] <= 0.5)
80
+ continue;
81
+ pts.push(idx);
82
+ sBgL += Lbg[idx];
83
+ sBgA += Abg[idx];
84
+ sBgB += Bbg[idx];
85
+ }
86
+ }
87
+ const oi = (gy * width + gx) * CHANNELS;
88
+ const visible = pts.length;
89
+ if (visible === 0 || (!opaque && visible * 2 < total))
90
+ continue;
91
+ if (visible === 1) {
92
+ const p = pts[0];
93
+ out[oi] = clampByte(r[p] * UINT8_MAX);
94
+ out[oi + 1] = clampByte(g[p] * UINT8_MAX);
95
+ out[oi + 2] = clampByte(b[p] * UINT8_MAX);
96
+ out[oi + 3] = UINT8_MAX;
97
+ continue;
98
+ }
99
+ const bgL = sBgL / visible;
100
+ const bgA = sBgA / visible;
101
+ const bgB = sBgB / visible;
102
+ // Seed 2-means with the two farthest visible pixels in chroma-weighted OKLab.
103
+ let pA = pts[0];
104
+ let maxD0 = -1;
105
+ for (let k = 0; k < visible; k++) {
106
+ const i = pts[k];
107
+ const d = (L[i] - bgL) ** 2 + CRISP_CHROMA_WEIGHT * ((A[i] - bgA) ** 2 + (B[i] - bgB) ** 2);
108
+ if (d > maxD0) {
109
+ maxD0 = d;
110
+ pA = i;
111
+ }
112
+ }
113
+ let pB = pts[0];
114
+ let maxD1 = -1;
115
+ const lA = L[pA];
116
+ const aA = A[pA];
117
+ const bA = B[pA];
118
+ for (let k = 0; k < visible; k++) {
119
+ const i = pts[k];
120
+ const d = (L[i] - lA) ** 2 + CRISP_CHROMA_WEIGHT * ((A[i] - aA) ** 2 + (B[i] - bA) ** 2);
121
+ if (d > maxD1) {
122
+ maxD1 = d;
123
+ pB = i;
124
+ }
125
+ }
126
+ let chosenL;
127
+ let chosenA;
128
+ let chosenB;
129
+ if (Math.sqrt(maxD1) < splitThreshold) {
130
+ let sl = 0;
131
+ let sa = 0;
132
+ let sb = 0;
133
+ for (let k = 0; k < visible; k++) {
134
+ const i = pts[k];
135
+ sl += L[i];
136
+ sa += A[i];
137
+ sb += B[i];
138
+ }
139
+ chosenL = sl / visible;
140
+ chosenA = sa / visible;
141
+ chosenB = sb / visible;
142
+ }
143
+ else {
144
+ let c0L = L[pA];
145
+ let c0A = A[pA];
146
+ let c0B = B[pA];
147
+ let c1L = L[pB];
148
+ let c1A = A[pB];
149
+ let c1B = B[pB];
150
+ let n0 = 0;
151
+ let n1 = 0;
152
+ for (let iter = 0; iter < 3; iter++) {
153
+ let s0L = 0;
154
+ let s0A = 0;
155
+ let s0B = 0;
156
+ let s1L = 0;
157
+ let s1A = 0;
158
+ let s1B = 0;
159
+ n0 = 0;
160
+ n1 = 0;
161
+ for (let k = 0; k < visible; k++) {
162
+ const i = pts[k];
163
+ const d0 = (L[i] - c0L) ** 2 + CRISP_CHROMA_WEIGHT * ((A[i] - c0A) ** 2 + (B[i] - c0B) ** 2);
164
+ const d1 = (L[i] - c1L) ** 2 + CRISP_CHROMA_WEIGHT * ((A[i] - c1A) ** 2 + (B[i] - c1B) ** 2);
165
+ if (d0 <= d1) {
166
+ s0L += L[i];
167
+ s0A += A[i];
168
+ s0B += B[i];
169
+ n0 += 1;
170
+ }
171
+ else {
172
+ s1L += L[i];
173
+ s1A += A[i];
174
+ s1B += B[i];
175
+ n1 += 1;
176
+ }
177
+ }
178
+ if (n0 > 0) {
179
+ c0L = s0L / n0;
180
+ c0A = s0A / n0;
181
+ c0B = s0B / n0;
182
+ }
183
+ if (n1 > 0) {
184
+ c1L = s1L / n1;
185
+ c1A = s1A / n1;
186
+ c1B = s1B / n1;
187
+ }
188
+ }
189
+ const dev0 = Math.sqrt((c0L - bgL) ** 2 + CRISP_SURROUND_CHROMA_WEIGHT * ((c0A - bgA) ** 2 + (c0B - bgB) ** 2));
190
+ const dev1 = Math.sqrt((c1L - bgL) ** 2 + CRISP_SURROUND_CHROMA_WEIGHT * ((c1A - bgA) ** 2 + (c1B - bgB) ** 2));
191
+ const minFeaturePixels = Math.max(1, Math.round(visible * minFeatureRatio));
192
+ const eff0 = n0 >= minFeaturePixels ? n0 ** countExponent * (1 + surroundGain * dev0) : n0 * 0.4;
193
+ const eff1 = n1 >= minFeaturePixels ? n1 ** countExponent * (1 + surroundGain * dev1) : n1 * 0.4;
194
+ if (eff0 >= eff1) {
195
+ chosenL = c0L;
196
+ chosenA = c0A;
197
+ chosenB = c0B;
198
+ }
199
+ else {
200
+ chosenL = c1L;
201
+ chosenA = c1A;
202
+ chosenB = c1B;
203
+ }
204
+ }
205
+ const [or, og, ob] = oklabToRgbFloat(chosenL, chosenA, chosenB);
206
+ out[oi] = clampByte(or * UINT8_MAX);
207
+ out[oi + 1] = clampByte(og * UINT8_MAX);
208
+ out[oi + 2] = clampByte(ob * UINT8_MAX);
209
+ out[oi + 3] = UINT8_MAX;
210
+ }
211
+ }
212
+ return { width, height, data: out };
213
+ }
@@ -0,0 +1,7 @@
1
+ import { type PixelBuffer } from "./base.ts";
2
+ /**
3
+ * Alpha-aware separable Lanczos-3 resampler with anti-ringing clamping:
4
+ * each output pixel is clamped to its local source footprint's min/max RGB so negative filter
5
+ * lobes never introduce overshoot halos along hard outlines.
6
+ */
7
+ export declare function resizeLanczos(image: PixelBuffer, width: number, height: number, sharpen?: boolean): PixelBuffer;