@xprite/pixelate 0.1.2 → 0.1.3

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.
@@ -1,5 +1,6 @@
1
1
  import { getColorPickerEntry } from "./cell-color-picker.js";
2
2
  import { MAX_RECOVERED_GRID_SIZE, pixelGridCuts } from "./grid.js";
3
+ import { settleEdgeAlpha } from "./pixel-alpha.js";
3
4
  import { samplePixelation } from "./sampling.js";
4
5
  import { CellColorPicker, PixelationMethod, } from "./types.js";
5
6
  const CHANNELS = 4;
@@ -43,82 +44,6 @@ function roundTripError(input, candidate, cells) {
43
44
  }
44
45
  return pixelCount > 0 ? errorSum / pixelCount : 0;
45
46
  }
46
- /**
47
- * Pixel art is drawn with whole pixels: a cell is either covered or clear. A generated or resampled
48
- * sprite carries a soft edge instead: the pixels along its outline are partly transparent, and its
49
- * covered pixels often sit a little below full opacity. Averaged into cells, that leaves a
50
- * half-transparent ring around the recovered sprite and an almost-opaque inside.
51
- *
52
- * A cell that holds both covered pixels (alpha of at least HALF_ALPHA) and uncovered ones lies on
53
- * the outline. In translucent art, a cell with no covered pixel takes the median alpha of its
54
- * pixels: a shadow keeps its level, a soft outline (mostly clear) is cleared. It is in the art when its covered pixels fill at least half of it, and clear
55
- * otherwise; in opaque art, so is a cell with no covered pixel. A covered cell takes the mean alpha of its covered pixels, raised to OPAQUE when the
56
- * source's art is opaque: at most TRANSLUCENT_SHARE of its visible pixels between TRANSLUCENT_LOW
57
- * and TRANSLUCENT_HIGH. Art drawn translucent (glass, shadows, glow) keeps its alpha, except that a
58
- * covered cell above TRANSLUCENT_HIGH is still raised to OPAQUE.
59
- */
60
- const HALF_ALPHA = 128;
61
- const HALF = 0.5;
62
- const OPAQUE = 255;
63
- const TRANSLUCENT_LOW = 16;
64
- const TRANSLUCENT_HIGH = 224;
65
- /** Share of the visible pixels a soft outline around opaque art stays below. */
66
- const TRANSLUCENT_SHARE = 0.2;
67
- /** Whether the image's visible pixels are opaque but for a soft edge. */
68
- function opaqueArt(image) {
69
- let visible = 0, translucent = 0;
70
- for (let o = COLOR_CHANNELS; o < image.data.length; o += CHANNELS) {
71
- const alpha = image.data[o];
72
- if (!alpha)
73
- continue;
74
- visible++;
75
- if (alpha >= TRANSLUCENT_LOW && alpha <= TRANSLUCENT_HIGH)
76
- translucent++;
77
- }
78
- return visible > 0 && translucent <= TRANSLUCENT_SHARE * visible;
79
- }
80
- function settleEdgeAlpha(image, x, y, out) {
81
- const opaque = opaqueArt(image);
82
- for (let row = 0; row < out.height; row++)
83
- for (let column = 0; column < out.width; column++) {
84
- const offset = (row * out.width + column) * CHANNELS;
85
- if (!out.data[offset + COLOR_CHANNELS])
86
- continue;
87
- const left = Math.max(0, Math.ceil(x[column])), right = Math.min(image.width, Math.ceil(x[column + 1])), top = Math.max(0, Math.ceil(y[row])), bottom = Math.min(image.height, Math.ceil(y[row + 1]));
88
- let covered = 0, coveredAlpha = 0;
89
- const alphas = [];
90
- for (let py = top; py < bottom; py++)
91
- for (let px = left; px < right; px++) {
92
- const alpha = image.data[(py * image.width + px) * CHANNELS + COLOR_CHANNELS];
93
- alphas.push(alpha);
94
- if (alpha < HALF_ALPHA)
95
- continue;
96
- covered++;
97
- coveredAlpha += alpha;
98
- }
99
- const area = (right - left) * (bottom - top);
100
- if (!covered && !opaque) {
101
- // Translucent art fills its cell evenly; a soft outline leaves most of the cell clear.
102
- alphas.sort((a, b) => a - b);
103
- const median = alphas[alphas.length >> 1] ?? 0;
104
- if (median < TRANSLUCENT_LOW)
105
- out.data.fill(0, offset, offset + CHANNELS);
106
- else
107
- out.data[offset + COLOR_CHANNELS] = median;
108
- continue;
109
- }
110
- if (covered < HALF * area)
111
- out.data.fill(0, offset, offset + CHANNELS);
112
- else if (opaque)
113
- out.data[offset + COLOR_CHANNELS] = OPAQUE;
114
- else {
115
- // Translucent art (a shadow, a glow) keeps its alpha, but a covered cell above
116
- // TRANSLUCENT_HIGH is opaque art drawn a little below 255, as everywhere else.
117
- const alpha = covered < area ? coveredAlpha / covered : out.data[offset + COLOR_CHANNELS];
118
- out.data[offset + COLOR_CHANNELS] = alpha > TRANSLUCENT_HIGH ? OPAQUE : Math.round(alpha);
119
- }
120
- }
121
- }
122
47
  /** One RGBA pixel per grid cell: explicit cuts when the grid carries them, else one regular lattice. */
123
48
  export function recoverGrid(image, grid, picker = CellColorPicker.MostCommon) {
124
49
  const x = grid.cutsX ?? pixelGridCuts(image.width, grid.cellWidth, grid.offsetX), y = grid.cutsY ?? pixelGridCuts(image.height, grid.cellHeight, grid.offsetY);
package/dist/index.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  export { analyzePixelArt, analyzePixelArtAsync } from "./analyze.ts";
2
2
  export { extractPalette, extractPixelationPalette, countDistinctColors, reduceToPalette, } from "./palette.ts";
3
3
  export { snapPalette } from "./palette-snap.ts";
4
+ export { removeOrphanPixels, type RemoveOrphanPixelsOptions } from "./orphan-pixels.ts";
5
+ export { settlePixelAlpha } from "./pixel-alpha.ts";
4
6
  export { estimateTilt, straighten, MAX_TILT_DEGREES } from "./deskew.ts";
5
7
  export { resizeNearest } from "./resize.ts";
6
8
  export { pixelateImage, pixelateImageAsync } from "./pixelate.ts";
package/dist/index.js CHANGED
@@ -1,6 +1,8 @@
1
1
  export { analyzePixelArt, analyzePixelArtAsync } from "./analyze.js";
2
2
  export { extractPalette, extractPixelationPalette, countDistinctColors, reduceToPalette, } from "./palette.js";
3
3
  export { snapPalette } from "./palette-snap.js";
4
+ export { removeOrphanPixels } from "./orphan-pixels.js";
5
+ export { settlePixelAlpha } from "./pixel-alpha.js";
4
6
  export { estimateTilt, straighten, MAX_TILT_DEGREES } from "./deskew.js";
5
7
  export { resizeNearest } from "./resize.js";
6
8
  export { pixelateImage, pixelateImageAsync } from "./pixelate.js";
@@ -0,0 +1,11 @@
1
+ import { type PixelBuffer } from "./base.ts";
2
+ export interface RemoveOrphanPixelsOptions {
3
+ /** Replace isolated interior colors. Disable this for dithered art. Defaults to true. */
4
+ absorbInterior?: boolean;
5
+ }
6
+ /**
7
+ * Clear fully opaque pixels separated from visible art on all four sides. In an opaque interior,
8
+ * replace a color unsupported by all eight neighbors only if those neighbors have a strict
9
+ * majority color. Decisions use the original pixels and never change the input buffer.
10
+ */
11
+ export declare function removeOrphanPixels(image: PixelBuffer, { absorbInterior }?: RemoveOrphanPixelsOptions): PixelBuffer;
@@ -0,0 +1,74 @@
1
+ import { assertPixelBuffer, UINT8_MAX } from "./base.js";
2
+ const CHANNELS = 4;
3
+ const ALPHA = 3;
4
+ function rgbAt(data, offset) {
5
+ return (data[offset] << 16) | (data[offset + 1] << 8) | data[offset + 2];
6
+ }
7
+ function majorityNeighborColor(data, offset, neighbors, colors) {
8
+ const center = rgbAt(data, offset);
9
+ let candidate = 0;
10
+ let votes = 0;
11
+ for (let i = 0; i < neighbors.length; i++) {
12
+ const neighbor = offset + neighbors[i];
13
+ if (data[neighbor + ALPHA] !== UINT8_MAX)
14
+ return;
15
+ const color = rgbAt(data, neighbor);
16
+ if (color === center)
17
+ return;
18
+ colors[i] = color;
19
+ // Cancel opposing votes, then verify the candidate has a strict majority.
20
+ if (votes === 0)
21
+ candidate = color;
22
+ votes += color === candidate ? 1 : -1;
23
+ }
24
+ if (votes === 0)
25
+ return;
26
+ let count = 0;
27
+ for (const color of colors)
28
+ if (color === candidate)
29
+ count++;
30
+ if (count > neighbors.length / 2)
31
+ return candidate;
32
+ }
33
+ /**
34
+ * Clear fully opaque pixels separated from visible art on all four sides. In an opaque interior,
35
+ * replace a color unsupported by all eight neighbors only if those neighbors have a strict
36
+ * majority color. Decisions use the original pixels and never change the input buffer.
37
+ */
38
+ export function removeOrphanPixels(image, { absorbInterior = true } = {}) {
39
+ assertPixelBuffer(image);
40
+ const { width, height, data } = image;
41
+ if (width === 1 && height === 1)
42
+ return image;
43
+ const stride = width * CHANNELS;
44
+ const neighbors = [
45
+ -CHANNELS, CHANNELS, -stride, stride,
46
+ -stride - CHANNELS, -stride + CHANNELS, stride - CHANNELS, stride + CHANNELS,
47
+ ];
48
+ const colors = new Uint32Array(neighbors.length);
49
+ let output;
50
+ for (let y = 0; y < height; y++)
51
+ for (let x = 0; x < width; x++) {
52
+ const offset = y * stride + x * CHANNELS;
53
+ const alpha = offset + ALPHA;
54
+ if (data[alpha] !== UINT8_MAX)
55
+ continue;
56
+ if ((x === 0 || data[alpha - CHANNELS] === 0) &&
57
+ (x === width - 1 || data[alpha + CHANNELS] === 0) &&
58
+ (y === 0 || data[alpha - stride] === 0) &&
59
+ (y === height - 1 || data[alpha + stride] === 0)) {
60
+ (output ??= data.slice()).fill(0, offset, offset + CHANNELS);
61
+ continue;
62
+ }
63
+ if (!absorbInterior || x === 0 || y === 0 || x === width - 1 || y === height - 1)
64
+ continue;
65
+ const replacement = majorityNeighborColor(data, offset, neighbors, colors);
66
+ if (replacement === undefined)
67
+ continue;
68
+ output ??= data.slice();
69
+ output[offset] = replacement >> 16;
70
+ output[offset + 1] = (replacement >> 8) & 255;
71
+ output[offset + 2] = replacement & 255;
72
+ }
73
+ return output ? { ...image, data: output } : image;
74
+ }
@@ -0,0 +1,10 @@
1
+ import { type PixelBuffer } from "./base.ts";
2
+ /**
3
+ * Settle soft alpha in a converted sprite using the sampled coverage. The
4
+ * source supplies the opacity heuristic so resampling a hard-edged image keeps
5
+ * its coverage alpha. Pass one buffer to settle alpha at its current size.
6
+ * Returns a new buffer when any pixels change.
7
+ */
8
+ export declare function settlePixelAlpha(source: PixelBuffer, sampled?: PixelBuffer): PixelBuffer;
9
+ /** Settle alpha from the source pixels inside each recovered grid cell. */
10
+ export declare function settleEdgeAlpha(image: PixelBuffer, x: readonly number[], y: readonly number[], out: PixelBuffer): void;
@@ -0,0 +1,108 @@
1
+ import { UINT8_MAX } from "./base.js";
2
+ const CHANNELS = 4;
3
+ const ALPHA = 3;
4
+ const HALF_ALPHA = 128;
5
+ const TRANSLUCENT_LOW = 16;
6
+ const TRANSLUCENT_HIGH = 224;
7
+ /** Share of the visible pixels a soft outline around opaque art stays below. */
8
+ const TRANSLUCENT_SHARE = 0.2;
9
+ /** Whether the image's visible pixels are opaque but for a soft edge. */
10
+ function opaqueArt(image, requireSoftAlpha = false) {
11
+ let visible = 0;
12
+ let translucent = 0;
13
+ let solid = 0;
14
+ let fullyOpaque = 0;
15
+ for (let o = ALPHA; o < image.data.length; o += CHANNELS) {
16
+ const alpha = image.data[o];
17
+ if (!alpha)
18
+ continue;
19
+ visible++;
20
+ if (alpha > TRANSLUCENT_HIGH) {
21
+ solid++;
22
+ if (alpha === UINT8_MAX)
23
+ fullyOpaque++;
24
+ }
25
+ else if (alpha >= TRANSLUCENT_LOW)
26
+ translucent++;
27
+ }
28
+ if (visible === 0 || translucent > TRANSLUCENT_SHARE * visible)
29
+ return false;
30
+ if (!requireSoftAlpha)
31
+ return true;
32
+ // A soft sprite has a solid core and some partial alpha. Look for a change
33
+ // in coverage so an evenly translucent image keeps its original alpha.
34
+ const hasEdge = solid < visible || visible < image.width * image.height;
35
+ return hasEdge && solid > 0 && fullyOpaque < visible;
36
+ }
37
+ function hasPartialAlpha(image) {
38
+ const { data } = image;
39
+ for (let alpha = ALPHA; alpha < data.length; alpha += CHANNELS)
40
+ if (data[alpha] > 0 && data[alpha] < UINT8_MAX)
41
+ return true;
42
+ return false;
43
+ }
44
+ function writeBinaryAlpha(data, offset, covered) {
45
+ if (covered)
46
+ data[offset + ALPHA] = UINT8_MAX;
47
+ else
48
+ data.fill(0, offset, offset + CHANNELS);
49
+ }
50
+ /**
51
+ * Settle soft alpha in a converted sprite using the sampled coverage. The
52
+ * source supplies the opacity heuristic so resampling a hard-edged image keeps
53
+ * its coverage alpha. Pass one buffer to settle alpha at its current size.
54
+ * Returns a new buffer when any pixels change.
55
+ */
56
+ export function settlePixelAlpha(source, sampled = source) {
57
+ if (!hasPartialAlpha(sampled) || !opaqueArt(source, true))
58
+ return sampled;
59
+ const data = sampled.data.slice();
60
+ for (let offset = 0; offset < data.length; offset += CHANNELS) {
61
+ const alpha = data[offset + ALPHA];
62
+ if (alpha > 0 && alpha < UINT8_MAX)
63
+ writeBinaryAlpha(data, offset, alpha >= HALF_ALPHA);
64
+ }
65
+ return { ...sampled, data };
66
+ }
67
+ /** Settle alpha from the source pixels inside each recovered grid cell. */
68
+ export function settleEdgeAlpha(image, x, y, out) {
69
+ const opaque = opaqueArt(image);
70
+ for (let row = 0; row < out.height; row++)
71
+ for (let column = 0; column < out.width; column++) {
72
+ const offset = (row * out.width + column) * CHANNELS;
73
+ if (!out.data[offset + ALPHA])
74
+ continue;
75
+ const left = Math.max(0, Math.ceil(x[column])), right = Math.min(image.width, Math.ceil(x[column + 1])), top = Math.max(0, Math.ceil(y[row])), bottom = Math.min(image.height, Math.ceil(y[row + 1]));
76
+ let covered = 0, coveredAlpha = 0;
77
+ const alphas = [];
78
+ for (let py = top; py < bottom; py++)
79
+ for (let px = left; px < right; px++) {
80
+ const alpha = image.data[(py * image.width + px) * CHANNELS + ALPHA];
81
+ alphas.push(alpha);
82
+ if (alpha < HALF_ALPHA)
83
+ continue;
84
+ covered++;
85
+ coveredAlpha += alpha;
86
+ }
87
+ const area = (right - left) * (bottom - top);
88
+ if (!covered && !opaque) {
89
+ // Translucent art fills its cell evenly; a soft outline leaves most of the cell clear.
90
+ alphas.sort((a, b) => a - b);
91
+ const median = alphas[alphas.length >> 1] ?? 0;
92
+ if (median < TRANSLUCENT_LOW)
93
+ out.data.fill(0, offset, offset + CHANNELS);
94
+ else
95
+ out.data[offset + ALPHA] = median;
96
+ continue;
97
+ }
98
+ const outside = covered < area / 2;
99
+ if (opaque || outside)
100
+ writeBinaryAlpha(out.data, offset, !outside);
101
+ else {
102
+ // Translucent art (a shadow, a glow) keeps its alpha, but a covered cell above
103
+ // TRANSLUCENT_HIGH is opaque art drawn a little below 255, as everywhere else.
104
+ const alpha = covered < area ? coveredAlpha / covered : out.data[offset + ALPHA];
105
+ out.data[offset + ALPHA] = alpha > TRANSLUCENT_HIGH ? UINT8_MAX : Math.round(alpha);
106
+ }
107
+ }
108
+ }
package/dist/pixelate.js CHANGED
@@ -6,11 +6,13 @@ import { prepareGridSampling } from "./grid-sampling.js";
6
6
  import { runPixeloe } from "./line-guided/pixeloe-entry.js";
7
7
  import { resizeMostFrequent } from "./most-frequent.js";
8
8
  import { applyOutlinePrepass, DEFAULT_LINE_GUIDE, runsStockPixeloe, } from "./outline-prepass.js";
9
+ import { removeOrphanPixels } from "./orphan-pixels.js";
9
10
  import { snapPalette } from "./palette-snap.js";
11
+ import { settlePixelAlpha } from "./pixel-alpha.js";
10
12
  import { detectWithAlgorithm, detectWithAlgorithmAsync, recoverWithGrid, } from "./pixelation-algorithm-registry.js";
11
13
  import { resizeBox, resizeNearest } from "./resize.js";
12
14
  import { samplePixelation } from "./sampling.js";
13
- import { OutlinePrepass, PixelationMethod, PixelationMode, PixelationAlgorithm, } from "./types.js";
15
+ import { OutlinePrepass, PixelationDither, PixelationMethod, PixelationMode, PixelationAlgorithm, } from "./types.js";
14
16
  const WORKING_SCALE = 4;
15
17
  const MAX_WORKING_PIXELS = 1_048_576;
16
18
  const MAX_OUTLINE_STRENGTH = 100;
@@ -77,13 +79,22 @@ function sampleImage(image, options, method) {
77
79
  const prepared = strength || method === PixelationMethod.Dominant || method === PixelationMethod.Structure
78
80
  ? prepareSource(image, target, strength)
79
81
  : 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);
82
+ const { width, height } = target;
83
+ 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);
96
+ }
97
+ return settlePixelAlpha(image, sampled);
87
98
  }
88
99
  function sizeFromBlock(blockSize, image) {
89
100
  if (typeof blockSize === "number") {
@@ -145,6 +156,19 @@ function validateMethod(value) {
145
156
  throw new RangeError("Unknown pixelation method.");
146
157
  return method;
147
158
  }
159
+ function finishPixelation(sampled, source, { removeNoise, paletteSnap, preserveDimensions }) {
160
+ let result = removeNoise ? smoothPixelation(sampled) : sampled;
161
+ if (paletteSnap)
162
+ result = snapPalette(result, paletteSnap);
163
+ if (removeNoise) {
164
+ const dither = paletteSnap?.dither;
165
+ const dithered = dither === PixelationDither.Ordered || dither === PixelationDither.FloydSteinberg;
166
+ result = removeOrphanPixels(result, { absorbInterior: !dithered });
167
+ }
168
+ if (preserveDimensions && (result.width !== source.width || result.height !== source.height))
169
+ result = resizeNearest(result, source.width, source.height);
170
+ return result;
171
+ }
148
172
  /**
149
173
  * Pixelate an RGBA buffer without touching the source. Nearest mode follows
150
174
  * nearest-neighbor `floor(dst * src / dst)` mapping. Box mode averages the
@@ -155,15 +179,7 @@ function validateMethod(value) {
155
179
  export function pixelateImage(image, options = {}) {
156
180
  assertPixelBuffer(image);
157
181
  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;
182
+ return finishPixelation(sampleImage(image, options, method), image, options);
167
183
  }
168
184
  async function sampleImageAsync(image, options, method) {
169
185
  const wantsGrid = options.mode === PixelationMode.RecoverGrid ||
@@ -204,11 +220,5 @@ export async function pixelateImageAsync(image, options = {}) {
204
220
  assertPixelBuffer(image);
205
221
  const method = validateMethod(options.method);
206
222
  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;
223
+ return finishPixelation(sampled, image, options);
214
224
  }
package/dist/types.d.ts CHANGED
@@ -205,7 +205,7 @@ export interface PixelateOptions {
205
205
  * palette. Alpha stays per pixel. Off when omitted.
206
206
  */
207
207
  paletteSnap?: PaletteSnapOptions;
208
- /** Light smoothing of similar neighboring colors on the working grid. */
208
+ /** Smooth similar colors and remove isolated pixels on the working grid. */
209
209
  removeNoise?: boolean;
210
210
  /** Box mode defaults to straight channel means; premultiplied is useful for compositing. */
211
211
  alphaMode?: "straight" | "premultiplied";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xprite/pixelate",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "description": "Recover the real pixel grid of AI-generated and upscaled pixel art, and turn images into pixel art.",
5
5
  "keywords": [
6
6
  "ai-art",