-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
histogram.ts
54 lines (52 loc) · 1.43 KB
/
histogram.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { Color } from "../deps/color.ts";
/**
* Histogram of colors with reduced space
* Effectively quantizes the image into 32768 colors
*/
export class ColorHistogram {
#data: Uint32Array;
constructor() {
this.#data = new Uint32Array(32768);
}
#getIndex(color: Color) {
// ignore alpha
const index = ((color.r >> 3) << (10)) + ((color.g >> 3) << 5) +
(color.b >> 3);
return index;
}
get(color: Color): number {
const index = this.#getIndex(color);
return this.#data[index];
}
getQuantized(color: [number, number, number]): number {
const index = (color[0] << 10) + (color[1] << 5) + color[2];
return this.#data[index];
}
add(color: Color, amount: number): number {
const index = this.#getIndex(color);
return Atomics.add(this.#data, index, amount);
}
get raw(): Uint32Array {
return this.#data;
}
get length(): number {
return this.#data.filter((x) => x).length;
}
static getColor(index: number): Color {
const ri = index >> 10;
const gi = (index - (ri << 10)) >> 5;
const bi = (index - (ri << 10) - (gi << 5));
return new Color(ri << 3, gi << 3, bi << 3, 255);
}
}
/** Get a histogram of frequency of colors. */
export function getHistogram(colors: Color[]): ColorHistogram {
const histo = new ColorHistogram();
let i = 0;
while (i < colors.length) {
const hIndex = colors[i];
histo.add(hIndex, 1);
i += 1;
}
return histo;
}