/
MMCQ.java
528 lines (445 loc) · 11.7 KB
/
MMCQ.java
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
package mezz.jei.util.color;
/*
* Java Color Thief
* by Sven Woltmann, Fonpit AG
* <p>
* http://www.androidpit.com
* http://www.androidpit.de
* <p>
* License
* -------
* Creative Commons Attribution 2.5 License:
* http://creativecommons.org/licenses/by/2.5/
* <p>
* Thanks
* ------
* Lokesh Dhakar - for the original Color Thief JavaScript version
* available at http://lokeshdhakar.com/projects/color-thief/
*/
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
@SuppressWarnings("ALL")
public class MMCQ {
private static final int SIGBITS = 5;
private static final int RSHIFT = 8 - SIGBITS;
private static final int MULT = 1 << RSHIFT;
private static final int HISTOSIZE = 1 << (3 * SIGBITS);
private static final int VBOX_LENGTH = 1 << SIGBITS;
private static final double FRACT_BY_POPULATION = 0.75;
private static final int MAX_ITERATIONS = 1000;
/**
* Get reduced-space color index for a pixel.
*
* @param r the red value
* @param g the green value
* @param b the blue value
* @return the color index
*/
static int getColorIndex(int r, int g, int b) {
return (r << (2 * SIGBITS)) + (g << SIGBITS) + b;
}
/**
* 3D color space box.
*/
public static class VBox {
int r1;
int r2;
int g1;
int g2;
int b1;
int b2;
private final int[] histo;
private int[] _avg;
private Integer _volume;
private Integer _count;
public VBox(int r1, int r2, int g1, int g2, int b1, int b2, int[] histo) {
this.r1 = r1;
this.r2 = r2;
this.g1 = g1;
this.g2 = g2;
this.b1 = b1;
this.b2 = b2;
this.histo = histo;
}
@Nonnull
@Override
public String toString() {
return "r1: " + r1 + " / r2: " + r2 + " / g1: " + g1 + " / g2: "
+ g2 + " / b1: " + b1 + " / b2: " + b2;
}
public int volume(boolean force) {
if (_volume == null || force) {
_volume = ((r2 - r1 + 1) * (g2 - g1 + 1) * (b2 - b1 + 1));
}
return _volume;
}
public int count(boolean force) {
if (_count == null || force) {
int npix = 0;
int i, j, k, index;
for (i = r1; i <= r2; i++) {
for (j = g1; j <= g2; j++) {
for (k = b1; k <= b2; k++) {
index = getColorIndex(i, j, k);
npix += histo[index];
}
}
}
_count = npix;
}
return _count;
}
@Nonnull
@Override
public VBox clone() {
return new VBox(r1, r2, g1, g2, b1, b2, histo);
}
public int[] avg(boolean force) {
if (_avg == null || force) {
int ntot = 0;
int rsum = 0;
int gsum = 0;
int bsum = 0;
int hval, i, j, k, histoindex;
for (i = r1; i <= r2; i++) {
for (j = g1; j <= g2; j++) {
for (k = b1; k <= b2; k++) {
histoindex = getColorIndex(i, j, k);
hval = histo[histoindex];
ntot += hval;
rsum += (hval * (i + 0.5) * MULT);
gsum += (hval * (j + 0.5) * MULT);
bsum += (hval * (k + 0.5) * MULT);
}
}
}
if (ntot > 0) {
_avg = new int[]{~~(rsum / ntot), ~~(gsum / ntot),
~~(bsum / ntot)};
} else {
_avg = new int[]{~~(MULT * (r1 + r2 + 1) / 2),
~~(MULT * (g1 + g2 + 1) / 2),
~~(MULT * (b1 + b2 + 1) / 2)};
}
}
return _avg;
}
public boolean contains(int[] pixel) {
int rval = pixel[0] >> RSHIFT;
int gval = pixel[1] >> RSHIFT;
int bval = pixel[2] >> RSHIFT;
return (rval >= r1 && rval <= r2 && gval >= g1 && gval <= g2
&& bval >= b1 && bval <= b2);
}
}
/**
* Color map.
*/
public static class CMap {
public final ArrayList<VBox> vboxes = new ArrayList<VBox>();
public void push(VBox box) {
vboxes.add(box);
}
@Nonnull
public int[][] palette() {
int numVBoxes = vboxes.size();
int[][] palette = new int[numVBoxes][];
for (int i = 0; i < numVBoxes; i++) {
palette[i] = vboxes.get(i).avg(false);
}
return palette;
}
public int size() {
return vboxes.size();
}
@Nullable
public int[] map(int[] color) {
int numVBoxes = vboxes.size();
for (int i = 0; i < numVBoxes; i++) {
VBox vbox = vboxes.get(i);
if (vbox.contains(color)) {
return vbox.avg(false);
}
}
return nearest(color);
}
@Nullable
public int[] nearest(int[] color) {
double d1 = Double.MAX_VALUE;
double d2;
int[] pColor = null;
int numVBoxes = vboxes.size();
for (int i = 0; i < numVBoxes; i++) {
int[] vbColor = vboxes.get(i).avg(false);
d2 = ColorUtil.fastPerceptualColorDistanceSquared(color, vbColor);
if (d2 < d1) {
d1 = d2;
pColor = vbColor;
}
}
return pColor;
}
}
/**
* Histo (1-d array, giving the number of pixels in each quantized region of
* color space), or null on error.
*/
private static int[] getHisto(int[][] pixels) {
int[] histo = new int[HISTOSIZE];
int index, rval, gval, bval;
int numPixels = pixels.length;
for (int i = 0; i < numPixels; i++) {
int[] pixel = pixels[i];
rval = pixel[0] >> RSHIFT;
gval = pixel[1] >> RSHIFT;
bval = pixel[2] >> RSHIFT;
index = getColorIndex(rval, gval, bval);
histo[index]++;
}
return histo;
}
private static VBox vboxFromPixels(int[][] pixels, int[] histo) {
int rmin = 1000000, rmax = 0;
int gmin = 1000000, gmax = 0;
int bmin = 1000000, bmax = 0;
int rval, gval, bval;
// find min/max
int numPixels = pixels.length;
for (int i = 0; i < numPixels; i++) {
int[] pixel = pixels[i];
rval = pixel[0] >> RSHIFT;
gval = pixel[1] >> RSHIFT;
bval = pixel[2] >> RSHIFT;
if (rval < rmin) {
rmin = rval;
} else if (rval > rmax) {
rmax = rval;
}
if (gval < gmin) {
gmin = gval;
} else if (gval > gmax) {
gmax = gval;
}
if (bval < bmin) {
bmin = bval;
} else if (bval > bmax) {
bmax = bval;
}
}
return new VBox(rmin, rmax, gmin, gmax, bmin, bmax, histo);
}
private static VBox[] medianCutApply(int[] histo, VBox vbox) {
if (vbox.count(false) == 0) {
return null;
}
// only one pixel, no split
if (vbox.count(false) == 1) {
return new VBox[]{vbox.clone(), null};
}
int rw = vbox.r2 - vbox.r1 + 1;
int gw = vbox.g2 - vbox.g1 + 1;
int bw = vbox.b2 - vbox.b1 + 1;
int maxw = Math.max(Math.max(rw, gw), bw);
// Find the partial sum arrays along the selected axis.
int total = 0;
int[] partialsum = new int[VBOX_LENGTH];
Arrays.fill(partialsum, -1); // -1 = not set / 0 = 0
int[] lookaheadsum = new int[VBOX_LENGTH];
Arrays.fill(lookaheadsum, -1); // -1 = not set / 0 = 0
int i, j, k, sum, index;
if (maxw == rw) {
for (i = vbox.r1; i <= vbox.r2; i++) {
sum = 0;
for (j = vbox.g1; j <= vbox.g2; j++) {
for (k = vbox.b1; k <= vbox.b2; k++) {
index = getColorIndex(i, j, k);
sum += histo[index];
}
}
total += sum;
partialsum[i] = total;
}
} else if (maxw == gw) {
for (i = vbox.g1; i <= vbox.g2; i++) {
sum = 0;
for (j = vbox.r1; j <= vbox.r2; j++) {
for (k = vbox.b1; k <= vbox.b2; k++) {
index = getColorIndex(j, i, k);
sum += histo[index];
}
}
total += sum;
partialsum[i] = total;
}
} else
/* maxw == bw */ {
for (i = vbox.b1; i <= vbox.b2; i++) {
sum = 0;
for (j = vbox.r1; j <= vbox.r2; j++) {
for (k = vbox.g1; k <= vbox.g2; k++) {
index = getColorIndex(j, k, i);
sum += histo[index];
}
}
total += sum;
partialsum[i] = total;
}
}
for (i = 0; i < VBOX_LENGTH; i++) {
if (partialsum[i] != -1) {
lookaheadsum[i] = total - partialsum[i];
}
}
// determine the cut planes
return maxw == rw ? doCut('r', vbox, partialsum, lookaheadsum, total)
: maxw == gw ? doCut('g', vbox, partialsum, lookaheadsum, total)
: doCut('b', vbox, partialsum, lookaheadsum, total);
}
private static VBox[] doCut(char color, VBox vbox, int[] partialsum, int[] lookaheadsum, int total) {
int vbox_dim1;
int vbox_dim2;
if (color == 'r') {
vbox_dim1 = vbox.r1;
vbox_dim2 = vbox.r2;
} else if (color == 'g') {
vbox_dim1 = vbox.g1;
vbox_dim2 = vbox.g2;
} else
/* color == 'b' */ {
vbox_dim1 = vbox.b1;
vbox_dim2 = vbox.b2;
}
int left, right;
VBox vbox1 = null, vbox2 = null;
int d2, count2;
for (int i = vbox_dim1; i <= vbox_dim2; i++) {
if (partialsum[i] > total / 2) {
vbox1 = vbox.clone();
vbox2 = vbox.clone();
left = i - vbox_dim1;
right = vbox_dim2 - i;
if (left <= right) {
d2 = Math.min(vbox_dim2 - 1, ~~(i + right / 2));
} else {
// 2.0 and cast to int is necessary to have the same
// behaviour as in JavaScript
d2 = Math.max(vbox_dim1, ~~((int) (i - 1 - left / 2.0)));
}
// avoid 0-count boxes
while (d2 < 0 || partialsum[d2] <= 0) {
d2++;
}
count2 = lookaheadsum[d2];
while (count2 == 0 && d2 > 0 && partialsum[d2 - 1] > 0) {
count2 = lookaheadsum[--d2];
}
// set dimensions
if (color == 'r') {
vbox1.r2 = d2;
vbox2.r1 = d2 + 1;
} else if (color == 'g') {
vbox1.g2 = d2;
vbox2.g1 = d2 + 1;
} else
/* color == 'b' */ {
vbox1.b2 = d2;
vbox2.b1 = d2 + 1;
}
return new VBox[]{vbox1, vbox2};
}
}
throw new RuntimeException("VBox can't be cut");
}
@Nullable
public static CMap quantize(int[][] pixels, int maxcolors) {
// short-circuit
if (pixels.length == 0 || maxcolors < 1 || maxcolors > 256) {
return null;
}
int[] histo = getHisto(pixels);
// get the beginning vbox from the colors
VBox vbox = vboxFromPixels(pixels, histo);
ArrayList<VBox> pq = new ArrayList<VBox>();
pq.add(vbox);
// Round up to have the same behaviour as in JavaScript
int target = (int) Math.ceil(FRACT_BY_POPULATION * maxcolors);
// first set of colors, sorted by population
iter(pq, COMPARATOR_COUNT, target, histo);
// Re-sort by the product of pixel occupancy times the size in color
// space.
Collections.sort(pq, COMPARATOR_PRODUCT);
// next set - generate the median cuts using the (npix * vol) sorting.
iter(pq, COMPARATOR_PRODUCT, maxcolors - pq.size(), histo);
// Reverse to put the highest elements first into the color map
Collections.reverse(pq);
// calculate the actual colors
CMap cmap = new CMap();
for (VBox vb : pq) {
cmap.push(vb);
}
return cmap;
}
/**
* Inner function to do the iteration.
*/
private static void iter(List<VBox> lh, Comparator<VBox> comparator, int target, int[] histo) {
int ncolors = 1;
int niters = 0;
VBox vbox;
while (niters < MAX_ITERATIONS) {
vbox = lh.get(lh.size() - 1);
if (vbox.count(false) == 0) {
Collections.sort(lh, comparator);
niters++;
continue;
}
lh.remove(lh.size() - 1);
// do the cut
VBox[] vboxes = medianCutApply(histo, vbox);
VBox vbox1 = vboxes[0];
VBox vbox2 = vboxes[1];
if (vbox1 == null) {
throw new RuntimeException(
"vbox1 not defined; shouldn't happen!");
}
lh.add(vbox1);
if (vbox2 != null) {
lh.add(vbox2);
ncolors++;
}
Collections.sort(lh, comparator);
if (ncolors >= target) {
return;
}
if (niters++ > MAX_ITERATIONS) {
return;
}
}
}
private static final Comparator<VBox> COMPARATOR_COUNT = new Comparator<VBox>() {
@Override
public int compare(VBox a, VBox b) {
return a.count(false) - b.count(false);
}
};
private static final Comparator<VBox> COMPARATOR_PRODUCT = new Comparator<VBox>() {
@Override
public int compare(VBox a, VBox b) {
int aCount = a.count(false);
int bCount = b.count(false);
int aVolume = a.volume(false);
int bVolume = b.volume(false);
// If count is 0 for both (or the same), sort by volume
if (aCount == bCount) {
return aVolume - bVolume;
}
// Otherwise sort by products
return aCount * aVolume - bCount * bVolume;
}
};
}