/
rgbquant.ts
196 lines (164 loc) · 5.84 KB
/
rgbquant.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
/*
* Copyright (c) 2015, Leon Sorokin
* All rights reserved. (MIT Licensed)
*
* RGBQuant.js - an image quantization lib
*/
/**
* @preserve TypeScript port:
* Copyright 2015-2018 Igor Bezkrovnyi
* All rights reserved. (MIT Licensed)
*
* rgbquant.ts - part of Image Quantization Library
*/
import { Palette } from '../../utils/palette';
import { Point } from '../../utils/point';
import { PointContainer } from '../../utils/pointContainer';
import { AbstractDistanceCalculator } from '../../distance/distanceCalculator';
import { ColorHistogram } from './colorHistogram';
import { AbstractPaletteQuantizer } from '../paletteQuantizer';
import { PaletteQuantizerYieldValue } from '../paletteQuantizerYieldValue';
import { stableSort } from '../../utils/arithmetic';
import { ProgressTracker } from '../../utils';
class RemovedColor {
readonly index: number;
readonly color: Point;
readonly distance: number;
constructor(index: number, color: Point, distance: number) {
this.index = index;
this.color = color;
this.distance = distance;
}
}
// TODO: make input/output image and input/output palettes with instances of class Point only!
export class RGBQuant extends AbstractPaletteQuantizer {
// desired final palette size
private readonly _colors: number;
// color-distance threshold for initial reduction pass
private readonly _initialDistance: number;
// subsequent passes threshold
private readonly _distanceIncrement: number;
// accumulated histogram
private readonly _histogram: ColorHistogram;
private readonly _distance: AbstractDistanceCalculator;
constructor(
colorDistanceCalculator: AbstractDistanceCalculator,
colors = 256,
method = 2,
) {
super();
this._distance = colorDistanceCalculator;
// desired final palette size
this._colors = colors;
// histogram to accumulate
this._histogram = new ColorHistogram(method, colors);
this._initialDistance = 0.01;
this._distanceIncrement = 0.005;
}
// gathers histogram info
sample(image: PointContainer) {
/*
var pointArray = image.getPointArray(), max = [0, 0, 0, 0], min = [255, 255, 255, 255];
for (var i = 0, l = pointArray.length; i < l; i++) {
var color = pointArray[i];
for (var componentIndex = 0; componentIndex < 4; componentIndex++) {
if (max[componentIndex] < color.rgba[componentIndex]) max[componentIndex] = color.rgba[componentIndex];
if (min[componentIndex] > color.rgba[componentIndex]) min[componentIndex] = color.rgba[componentIndex];
}
}
var rd = max[0] - min[0], gd = max[1] - min[1], bd = max[2] - min[2], ad = max[3] - min[3];
this._distance.setWhitePoint(rd, gd, bd, ad);
this._initialDistance = (Math.sqrt(rd * rd + gd * gd + bd * bd + ad * ad) / Math.sqrt(255 * 255 + 255 * 255 + 255 * 255)) * 0.01;
*/
this._histogram.sample(image);
}
// reduces histogram to palette, remaps & memoizes reduced colors
*quantize() {
const idxi32 = this._histogram.getImportanceSortedColorsIDXI32();
if (idxi32.length === 0) {
throw new Error('No colors in image');
}
yield* this._buildPalette(idxi32);
}
// reduces similar colors from an importance-sorted Uint32 rgba array
private *_buildPalette(
idxi32: number[],
): IterableIterator<PaletteQuantizerYieldValue> {
// reduce histogram to create initial palette
// build full rgb palette
const palette = new Palette();
const colorArray = palette.getPointContainer().getPointArray();
const usageArray = new Array(idxi32.length); // tslint:disable-line:prefer-array-literal
for (let i = 0; i < idxi32.length; i++) {
colorArray.push(Point.createByUint32(idxi32[i]));
usageArray[i] = 1;
}
const len = colorArray.length;
const memDist = [];
let palLen = len;
let thold = this._initialDistance;
// palette already at or below desired length
const tracker = new ProgressTracker(palLen - this._colors, 99);
while (palLen > this._colors) {
memDist.length = 0;
// iterate palette
for (let i = 0; i < len; i++) {
if (tracker.shouldNotify(len - palLen)) {
yield {
progress: tracker.progress,
};
}
if (usageArray[i] === 0) continue;
const pxi = colorArray[i];
// if (!pxi) continue;
for (let j = i + 1; j < len; j++) {
if (usageArray[j] === 0) continue;
const pxj = colorArray[j];
// if (!pxj) continue;
const dist = this._distance.calculateNormalized(pxi, pxj);
if (dist < thold) {
// store index,rgb,dist
memDist.push(new RemovedColor(j, pxj, dist));
usageArray[j] = 0;
palLen--;
}
}
}
// palette reduction pass
// console.log("palette length: " + palLen);
// if palette is still much larger than target, increment by larger initDist
thold +=
palLen > this._colors * 3
? this._initialDistance
: this._distanceIncrement;
}
// if palette is over-reduced, re-add removed colors with largest distances from last round
if (palLen < this._colors) {
// sort descending
stableSort(memDist, (a, b) => b.distance - a.distance);
let k = 0;
while (palLen < this._colors && k < memDist.length) {
const removedColor = memDist[k];
// re-inject rgb into final palette
usageArray[removedColor.index] = 1;
palLen++;
k++;
}
}
let colors = colorArray.length;
for (let colorIndex = colors - 1; colorIndex >= 0; colorIndex--) {
if (usageArray[colorIndex] === 0) {
if (colorIndex !== colors - 1) {
colorArray[colorIndex] = colorArray[colors - 1];
}
--colors;
}
}
colorArray.length = colors;
palette.sort();
yield {
palette,
progress: 100,
};
}
}