@xprite/pixelate 0.1.2 → 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,27 +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";
8
+ import { cleanStraySpeckles, removeOrphanPixels } from "./orphan-pixels.js";
9
9
  import { snapPalette } from "./palette-snap.js";
10
+ import { settlePixelAlpha } from "./pixel-alpha.js";
10
11
  import { detectWithAlgorithm, detectWithAlgorithmAsync, recoverWithGrid, } from "./pixelation-algorithm-registry.js";
12
+ import { resizeCrisp2Means } from "./resize-crisp.js";
13
+ import { resizeLanczos } from "./resize-lanczos.js";
11
14
  import { resizeBox, resizeNearest } from "./resize.js";
12
15
  import { samplePixelation } from "./sampling.js";
13
- import { OutlinePrepass, PixelationMethod, PixelationMode, PixelationAlgorithm, } from "./types.js";
16
+ import { OutlinePrepass, PixelationAlgorithm, PixelationDither, PixelationMethod, PixelationMode, } from "./types.js";
14
17
  const WORKING_SCALE = 4;
15
18
  const MAX_WORKING_PIXELS = 1_048_576;
16
19
  const MAX_OUTLINE_STRENGTH = 100;
17
- function prepareSource(image, target, outlineStrength) {
20
+ function capWorkingSize(image, target) {
18
21
  const scale = Math.min(WORKING_SCALE, Math.sqrt(MAX_WORKING_PIXELS / (target.width * target.height)));
19
22
  const width = Math.min(image.width, Math.max(1, Math.ceil(target.width * scale)));
20
23
  const height = Math.min(image.height, Math.max(1, Math.ceil(target.height * scale)));
21
- const working = image.width === width && image.height === height
24
+ return image.width === width && image.height === height
22
25
  ? image
23
26
  : resizeBox(image, width, height, "premultiplied");
24
- return protectPixelationContours(working, outlineStrength);
25
27
  }
26
28
  function uniformBlocks(image, target) {
27
29
  return {
@@ -31,59 +33,127 @@ function uniformBlocks(image, target) {
31
33
  algorithm: PixelationAlgorithm.UniformGrid,
32
34
  };
33
35
  }
34
- function sampleImage(image, options, method) {
35
- // Grid recovery runs when asked for, or when only an algorithm was named and it finds a reliable grid.
36
- const wantsGrid = options.mode === PixelationMode.RecoverGrid ||
37
- (options.mode === undefined && options.algorithm !== undefined);
38
- const grid = options.grid ??
39
- (wantsGrid
40
- ? detectWithAlgorithm(image, options.algorithm ?? PixelationAlgorithm.Auto)
41
- : 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) {
42
50
  const mode = options.mode ??
43
- (grid && (!("reliable" in grid) || grid.reliable)
51
+ (detectedGrid && (!("reliable" in detectedGrid) || detectedGrid.reliable)
44
52
  ? PixelationMode.RecoverGrid
45
53
  : PixelationMode.Convert);
46
54
  if (mode !== PixelationMode.Convert && mode !== PixelationMode.RecoverGrid)
47
55
  throw new RangeError("Unknown pixelation mode.");
48
- const prepass = options.prepass ?? OutlinePrepass.None;
49
- const guide = prepass === OutlinePrepass.PixeloeLines ? (options.lineGuide ?? DEFAULT_LINE_GUIDE) : undefined;
50
56
  if (mode === PixelationMode.RecoverGrid) {
51
- const found = grid ?? detectWithAlgorithm(image, options.algorithm ?? PixelationAlgorithm.Auto);
52
- if ("reliable" in found && !found.reliable)
57
+ if (!detectedGrid || ("reliable" in detectedGrid && !detectedGrid.reliable))
53
58
  throw new Error("No consistent pixel grid was detected. Turn off Automatic grid and choose cell sizes.");
54
- const cell = (found.cellWidth + found.cellHeight) / 2;
55
- const analysis = found;
56
- const upright = prepareGridSampling(image, analysis);
57
- const gridForRecover = { ...analysis, rotation: undefined, sampling: undefined };
58
- // Custom size's even blocks with PixelOE + Contrast: stock PixelOE to that size.
59
- if (runsStockPixeloe({ ...options, mode }, found))
60
- return runPixeloe(upright, { width: found.width, height: found.height }, guide);
61
- 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
+ };
62
84
  }
63
- const target = resolveTargetSize(image, options);
64
- // PixelOE + Contrast without a recovered grid is stock PixelOE: the reference result.
65
- if (runsStockPixeloe({ ...options, mode }, undefined))
66
- return runPixeloe(image, target, guide);
67
- // Otherwise an independent pre-pass; whatever sampler or colour picker follows works on its result.
68
- image = applyOutlinePrepass(image, (image.width / target.width + image.height / target.height) / 2, prepass, options.lineGuide);
69
- const strength = options.outlineStrength ?? 0;
70
- if (!Number.isFinite(strength) || strength < 0 || strength > MAX_OUTLINE_STRENGTH)
71
- throw new RangeError("Outline protection must be between 0 and 100.");
72
- if (options.blockPicker)
73
- 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;
74
101
  const alphaMode = options.alphaMode ?? "straight";
75
102
  if (alphaMode !== "straight" && alphaMode !== "premultiplied")
76
103
  throw new RangeError("alphaMode must be 'straight' or 'premultiplied'");
77
- const prepared = strength || method === PixelationMethod.Dominant || method === PixelationMethod.Structure
78
- ? prepareSource(image, target, strength)
79
- : image;
80
- if (method === PixelationMethod.Nearest)
81
- return resizeNearest(prepared, target.width, target.height);
82
- if (method === PixelationMethod.Box)
83
- return resizeBox(prepared, target.width, target.height, alphaMode);
84
- if (method === PixelationMethod.MostFrequent)
85
- return resizeMostFrequent(prepared, target.width, target.height);
86
- return samplePixelation(prepared, target.width, target.height, method);
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).
126
+ let sampled;
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);
133
+ }
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);
87
157
  }
88
158
  function sizeFromBlock(blockSize, image) {
89
159
  if (typeof blockSize === "number") {
@@ -145,70 +215,45 @@ function validateMethod(value) {
145
215
  throw new RangeError("Unknown pixelation method.");
146
216
  return method;
147
217
  }
218
+ function finishPixelation(sampled, source, { removeNoise, paletteSnap, preserveDimensions }, crispSpeckleDeltaE = 0) {
219
+ let result = removeNoise ? smoothPixelation(sampled) : sampled;
220
+ if (paletteSnap)
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
+ }
227
+ if (removeNoise) {
228
+ result = removeOrphanPixels(result, { absorbInterior: !dithered });
229
+ }
230
+ if (preserveDimensions && (result.width !== source.width || result.height !== source.height))
231
+ result = resizeNearest(result, source.width, source.height);
232
+ return result;
233
+ }
148
234
  /**
149
- * Pixelate an RGBA buffer without touching the source. Nearest mode follows
150
- * nearest-neighbor `floor(dst * src / dst)` mapping. Box mode averages the
151
- * source area covered by each destination pixel. Local dominant and structural
152
- * sampling preserve contrasting regions; grid recovery restores one RGBA pixel
153
- * 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.
154
237
  */
155
238
  export function pixelateImage(image, options = {}) {
156
239
  assertPixelBuffer(image);
157
240
  const method = validateMethod(options.method);
158
- const sampled = sampleImage(image, options, method);
159
- const smoothed = options.removeNoise ? smoothPixelation(sampled) : sampled;
160
- // Limit colors: Lab k-means that keeps rare colours, or snapping to a loaded palette.
161
- let result = options.paletteSnap ? snapPalette(smoothed, options.paletteSnap) : smoothed;
162
- if (options.preserveDimensions &&
163
- (result.width !== image.width || result.height !== image.height)) {
164
- result = resizeNearest(result, image.width, image.height);
165
- }
166
- return result;
167
- }
168
- async function sampleImageAsync(image, options, method) {
169
- const wantsGrid = options.mode === PixelationMode.RecoverGrid ||
170
- (options.mode === undefined && options.algorithm !== undefined);
171
241
  const grid = options.grid ??
172
- (wantsGrid
173
- ? await detectWithAlgorithmAsync(image, options.algorithm ?? PixelationAlgorithm.Auto)
242
+ (wantsGridDetection(options)
243
+ ? detectWithAlgorithm(image, options.algorithm ?? PixelationAlgorithm.Auto)
174
244
  : undefined);
175
- const mode = options.mode ??
176
- (grid && (!("reliable" in grid) || grid.reliable)
177
- ? PixelationMode.RecoverGrid
178
- : PixelationMode.Convert);
179
- if (mode !== PixelationMode.Convert && mode !== PixelationMode.RecoverGrid)
180
- throw new RangeError("Unknown pixelation mode.");
181
- const prepass = options.prepass ?? OutlinePrepass.None;
182
- const guide = prepass === OutlinePrepass.PixeloeLines ? (options.lineGuide ?? DEFAULT_LINE_GUIDE) : undefined;
183
- if (mode === PixelationMode.RecoverGrid) {
184
- const found = grid ??
185
- (await detectWithAlgorithmAsync(image, options.algorithm ?? PixelationAlgorithm.Auto));
186
- if ("reliable" in found && !found.reliable)
187
- throw new Error("No consistent pixel grid was detected. Turn off Automatic grid and choose cell sizes.");
188
- const cell = (found.cellWidth + found.cellHeight) / 2;
189
- const analysis = found;
190
- const upright = prepareGridSampling(image, analysis);
191
- const gridForRecover = { ...analysis, rotation: undefined, sampling: undefined };
192
- if (runsStockPixeloe({ ...options, mode }, found))
193
- return runPixeloe(upright, { width: found.width, height: found.height }, guide);
194
- return recoverWithGrid(applyOutlinePrepass(upright, cell, prepass, options.lineGuide), gridForRecover, options.colorPicker);
195
- }
196
- // Convert path is sync — reuse sampleImage body for non-recover.
197
- return sampleImage(image, { ...options, grid: undefined, mode: PixelationMode.Convert }, method);
245
+ return runPipeline(buildPlan(image, options, method, grid), options, method);
198
246
  }
199
247
  /**
200
- * Async pixelate for product Auto path (import-worker). Same output as pixelateImage;
201
- * 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.
202
250
  */
203
251
  export async function pixelateImageAsync(image, options = {}) {
204
252
  assertPixelBuffer(image);
205
253
  const method = validateMethod(options.method);
206
- const sampled = await sampleImageAsync(image, options, method);
207
- const smoothed = options.removeNoise ? smoothPixelation(sampled) : sampled;
208
- let result = options.paletteSnap ? snapPalette(smoothed, options.paletteSnap) : smoothed;
209
- if (options.preserveDimensions &&
210
- (result.width !== image.width || result.height !== image.height)) {
211
- result = resizeNearest(result, image.width, image.height);
212
- }
213
- return result;
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);
214
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;