-
Notifications
You must be signed in to change notification settings - Fork 11
/
colorHistogram.ts
212 lines (171 loc) · 5.83 KB
/
colorHistogram.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
/*
* Copyright (c) 2015, Leon Sorokin
* All rights reserved. (MIT Licensed)
*
* ColorHistogram.js - an image quantization lib
*/
/**
* @preserve TypeScript port:
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* colorHistogram.ts - part of Image Quantization Library
*/
import { HueStatistics } from '../../utils/hueStatistics';
import { PointContainer } from '../../utils/pointContainer';
import { stableSort } from '../../utils/arithmetic';
interface Box {
x: number;
y: number;
h: number;
w: number;
}
export class ColorHistogram {
private static _boxSize = [64, 64];
private static _boxPixels = 2;
private static _hueGroups = 10;
// 1 = by global population, 2 = subregion population threshold
private _method: number;
// HueStatistics instance
private _hueStats: HueStatistics;
private _histogram: { [color: string]: number };
// # of highest-frequency colors to start with for palette reduction
private _initColors: number;
// if > 0, enables hues stats and min-color retention per group
private _minHueCols: number;
constructor(method: number, colors: number) {
// 1 = by global population, 2 = subregion population threshold
this._method = method;
// if > 0, enables hues stats and min-color retention per group
this._minHueCols = colors << 2;// opts.minHueCols || 0;
// # of highest-frequency colors to start with for palette reduction
this._initColors = colors << 2;
// HueStatistics instance
this._hueStats = new HueStatistics(ColorHistogram._hueGroups, this._minHueCols);
this._histogram = Object.create(null); // tslint:disable-line:no-null-keyword
}
sample(pointContainer: PointContainer) {
switch (this._method) {
case 1:
this._colorStats1D(pointContainer);
break;
case 2:
this._colorStats2D(pointContainer);
break;
}
}
getImportanceSortedColorsIDXI32() {
// TODO: fix typing issue in stableSort func
const sorted = stableSort(Object.keys(this._histogram), (a, b) => this._histogram[ b ] - this._histogram[ a ]);
if (sorted.length === 0) {
return [];
}
let idxi32: string[];
switch (this._method) {
case 1:
const initialColorsLimit = Math.min(sorted.length, this._initColors);
const last = sorted[ initialColorsLimit - 1 ];
const freq = this._histogram[ last ];
idxi32 = sorted.slice(0, initialColorsLimit);
// add any cut off colors with same freq as last
let pos = initialColorsLimit;
const len = sorted.length;
while (pos < len && this._histogram[ sorted[ pos ] ] === freq) {
idxi32.push(sorted[ pos++ ]);
}
// inject min huegroup colors
this._hueStats.injectIntoArray(idxi32);
break;
case 2:
idxi32 = sorted;
break;
default:
// TODO: rethink errors
throw new Error('Incorrect method');
}
// int32-ify values
return idxi32.map(function (v: string) { // TODO: why no-inferred-types rule cannot find this (v: string) ?
return +v;
});
}
// global top-population
private _colorStats1D(pointContainer: PointContainer) {
const histG = this._histogram;
const pointArray = pointContainer.getPointArray();
const len = pointArray.length;
for (let i = 0; i < len; i++) {
const col = pointArray[ i ].uint32;
// collect hue stats
this._hueStats.check(col);
if (col in histG) {
histG[ col ]++;
} else {
histG[ col ] = 1;
}
}
}
// population threshold within subregions
// FIXME: this can over-reduce (few/no colors same?), need a way to keep
// important colors that dont ever reach local thresholds (gradients?)
private _colorStats2D(pointContainer: PointContainer) {
const width = pointContainer.getWidth();
const height = pointContainer.getHeight();
const pointArray = pointContainer.getPointArray();
const boxW = ColorHistogram._boxSize[ 0 ];
const boxH = ColorHistogram._boxSize[ 1 ];
const area = boxW * boxH;
const boxes = this._makeBoxes(width, height, boxW, boxH);
const histG = this._histogram;
boxes.forEach(box => {
let effc = Math.round((box.w * box.h) / area) * ColorHistogram._boxPixels;
if (effc < 2) effc = 2;
const histL: { [key: string ]: number } = {};
this._iterateBox(box, width, (i) => {
const col = pointArray[ i ].uint32;
// collect hue stats
this._hueStats.check(col);
if (col in histG) {
histG[ col ]++;
} else if (col in histL) {
if (++histL[ col ] >= effc) {
histG[ col ] = histL[ col ];
}
} else {
histL[ col ] = 1;
}
});
});
// inject min huegroup colors
this._hueStats.injectIntoDictionary(histG);
}
// iterates @bbox within a parent rect of width @wid; calls @fn, passing index within parent
private _iterateBox(bbox: Box, wid: number, fn: (i: number) => void) {
const b = bbox;
const i0 = b.y * wid + b.x;
const i1 = (b.y + b.h - 1) * wid + (b.x + b.w - 1);
const incr = wid - b.w + 1;
let cnt = 0;
let i = i0;
do {
fn.call(this, i);
i += (++cnt % b.w === 0) ? incr : 1;
} while (i <= i1);
}
/**
* partitions a rectangle of width x height into
* array of boxes stepX x stepY (or less)
*/
private _makeBoxes(width: number, height: number, stepX: number, stepY: number) {
const wrem = width % stepX;
const hrem = height % stepY;
const xend = width - wrem;
const yend = height - hrem;
const boxesArray: Box[] = [];
for (let y = 0; y < height; y += stepY) {
for (let x = 0; x < width; x += stepX) {
boxesArray.push({ x, y, w: (x === xend ? wrem : stepX), h: (y === yend ? hrem : stepY) });
}
}
return boxesArray;
}
}