Skip to content

Commit

Permalink
refactor(pixel): dedupe defIndexed() internals
Browse files Browse the repository at this point in the history
- replace closestColor() w/ argmin() from thi.ng/distance
- update deps
  • Loading branch information
postspectacular committed Sep 24, 2021
1 parent 9c0f003 commit a4a3e61
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 14 deletions.
1 change: 1 addition & 0 deletions packages/pixel/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
"@thi.ng/api": "^7.2.0",
"@thi.ng/binary": "^2.2.11",
"@thi.ng/checks": "^2.9.11",
"@thi.ng/distance": "^1.0.7",
"@thi.ng/errors": "^1.3.4",
"@thi.ng/k-means": "^0.3.6",
"@thi.ng/math": "^4.0.6",
Expand Down
16 changes: 2 additions & 14 deletions packages/pixel/src/format/indexed.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { NumericArray } from "@thi.ng/api";
import { swapLane13 } from "@thi.ng/binary/swizzle";
import { argminN } from "@thi.ng/distance/argmin";
import { assert } from "@thi.ng/errors/assert";
import { Lane } from "../api";
import { defPackedFormat } from "./packed-format";
Expand All @@ -24,7 +25,7 @@ export const defIndexed = (palette: NumericArray, isABGR = false) => {
type: "u8",
size: 8,
channels: [{ size: 8, lane: Lane.RED }],
fromABGR: (x) => closestColor(x, palette),
fromABGR: (x) => argminN(x, palette, distBGR),
toABGR: (x) => palette[x],
});
};
Expand All @@ -35,16 +36,3 @@ const distBGR = (a: number, b: number) =>
((a >> 8) & 0xff) - ((b >> 8) & 0xff),
(a & 0xff) - (b & 0xff)
);

const closestColor = (col: number, palette: NumericArray) => {
let closest = 0;
let minD = Infinity;
for (let i = palette.length; --i >= 0; ) {
const d = distBGR(col, palette[i]);
if (d < minD) {
closest = i;
minD = d;
}
}
return closest;
};

0 comments on commit a4a3e61

Please sign in to comment.