Repository navigation
Expand file tree
/
Copy pathpalette-evolution.html
More file actions
1043 lines (946 loc) · 35.6 KB
/
Copy pathpalette-evolution.html
File metadata and controls
1043 lines (946 loc) · 35.6 KB
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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Palette Evolution — Genetic Image Compression</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500;600&family=IBM+Plex+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
:root{
--bg: #0e1512;
--panel: #131e1a;
--panel-2: #16221d;
--border: #263630;
--border-soft: #1c2924;
--amber: #e4b85c;
--amber-dim: #8a7141;
--sage: #6fa98a;
--sage-dim: #3f5c4c;
--text: #eae6da;
--text-muted: #8fa199;
--text-faint: #5c6b64;
--danger: #c6683f;
--mono: 'IBM Plex Mono', monospace;
--sans: 'IBM Plex Sans', sans-serif;
}
*{ box-sizing: border-box; }
html, body{ margin:0; padding:0; }
body{
background: var(--bg);
color: var(--text);
font-family: var(--sans);
line-height: 1.5;
-webkit-font-smoothing: antialiased;
}
::selection{ background: var(--sage-dim); color: var(--text); }
a{ color: var(--amber); }
.wrap{
max-width: 900px;
margin: 0 auto;
padding: 48px 24px 96px;
}
/* ---------- Header ---------- */
header{
margin-bottom: 40px;
border-bottom: 1px solid var(--border-soft);
padding-bottom: 28px;
}
.eyebrow{
font-family: var(--mono);
font-size: 12.5px;
color: var(--sage);
letter-spacing: 0.02em;
margin: 0 0 10px;
}
h1{
font-size: 34px;
font-weight: 700;
margin: 0 0 12px;
letter-spacing: -0.01em;
line-height: 1.15;
}
header p{
color: var(--text-muted);
max-width: 60ch;
margin: 0;
font-size: 15.5px;
}
section{ margin-bottom: 36px; }
h2{
font-size: 13px;
text-transform: none;
font-family: var(--mono);
color: var(--text-faint);
font-weight: 500;
margin: 0 0 14px;
display:flex;
align-items:center;
gap: 10px;
}
h2::after{
content:'';
flex:1;
height:1px;
background: var(--border-soft);
}
/* ---------- Dropzone ---------- */
.dropzone{
border: 1px dashed var(--border);
background: var(--panel);
padding: 46px 24px;
text-align: center;
cursor: pointer;
transition: border-color .15s ease, background .15s ease;
position: relative;
}
.dropzone:hover, .dropzone.drag{
border-color: var(--sage);
background: var(--panel-2);
}
.dropzone input{ display:none; }
.dz-title{ font-size: 16px; font-weight: 600; margin-bottom: 6px; }
.dz-sub{ color: var(--text-muted); font-size: 13.5px; }
.dz-icon{
width: 34px; height: 34px; margin: 0 auto 16px;
color: var(--amber);
}
.file-chip{
display:inline-flex; align-items:center; gap:8px;
font-family: var(--mono); font-size: 12.5px;
color: var(--text-muted);
margin-top: 14px;
}
.file-chip strong{ color: var(--text); font-weight: 500; }
/* ---------- Controls ---------- */
.controls{
background: var(--panel);
border: 1px solid var(--border-soft);
padding: 22px 22px 8px;
}
.ctrl-row{
display:grid;
grid-template-columns: 140px 1fr 54px;
align-items:center;
gap: 16px;
margin-bottom: 18px;
}
.ctrl-label{
font-size: 13.5px;
color: var(--text-muted);
}
.ctrl-val{
font-family: var(--mono);
font-size: 13px;
color: var(--amber);
text-align: right;
}
input[type=range]{
-webkit-appearance: none;
width: 100%;
height: 2px;
background: var(--border);
outline: none;
}
input[type=range]::-webkit-slider-thumb{
-webkit-appearance: none;
width: 13px; height: 13px;
border-radius: 50%;
background: var(--amber);
cursor: pointer;
border: 2px solid var(--bg);
}
input[type=range]::-moz-range-thumb{
width: 13px; height: 13px;
border-radius: 50%;
background: var(--amber);
cursor: pointer;
border: 2px solid var(--bg);
}
.checkline{
display:flex; align-items:center; gap: 10px;
font-size: 13.5px; color: var(--text-muted);
margin-bottom: 20px;
cursor: pointer;
}
.checkline input{ accent-color: var(--sage); width:14px; height:14px; }
.btn{
font-family: var(--sans);
font-weight: 600;
font-size: 14.5px;
border: 1px solid var(--amber);
background: var(--amber);
color: #16130a;
padding: 12px 22px;
cursor: pointer;
transition: transform .1s ease, background .15s ease;
}
.btn:hover:not(:disabled){ background: #efc772; }
.btn:active:not(:disabled){ transform: translateY(1px); }
.btn:disabled{
opacity: 0.4;
cursor: not-allowed;
}
.btn.secondary{
background: transparent;
color: var(--text);
border-color: var(--border);
}
.btn.secondary:hover:not(:disabled){ border-color: var(--sage); background: var(--panel-2); }
.run-row{
display:flex;
align-items:center;
gap: 16px;
padding: 18px 0 20px;
}
/* ---------- Progress ---------- */
.progress-box{
display:none;
border: 1px solid var(--border-soft);
background: var(--panel);
padding: 18px 20px;
}
.progress-box.active{ display:block; }
.progress-head{
display:flex; justify-content:space-between; align-items:baseline;
font-family: var(--mono); font-size: 12.5px; color: var(--text-muted);
margin-bottom: 12px;
}
.progress-head span.hi{ color: var(--sage); }
.bar-track{
height: 4px; background: var(--border-soft); margin-bottom: 14px; overflow:hidden;
}
.bar-fill{
height:100%; width:0%; background: var(--sage); transition: width .15s ease;
}
canvas#sparkline{ width:100%; height:56px; display:block; }
/* ---------- Results ---------- */
.results{ display:none; }
.results.active{ display:block; }
.compare{
display:grid;
grid-template-columns: 1fr 1fr;
gap: 14px;
margin-bottom: 16px;
}
@media (max-width: 620px){ .compare{ grid-template-columns: 1fr; } }
.frame{
border: 1px solid var(--border-soft);
background: var(--panel);
padding: 10px;
}
.frame-label{
font-family: var(--mono);
font-size: 11.5px;
color: var(--text-faint);
margin-bottom: 8px;
display:flex; justify-content:space-between;
}
.frame canvas, .frame img{
width: 100%;
height: auto;
display:block;
background:
linear-gradient(45deg, #1a2420 25%, transparent 25%),
linear-gradient(-45deg, #1a2420 25%, transparent 25%),
linear-gradient(45deg, transparent 75%, #1a2420 75%),
linear-gradient(-45deg, transparent 75%, #1a2420 75%);
background-size: 16px 16px;
background-position: 0 0, 0 8px, 8px -8px, -8px 0px;
}
.palette-strip{
display:flex;
border: 1px solid var(--border-soft);
margin-bottom: 16px;
overflow: hidden;
}
.swatch{ flex:1; height: 30px; }
.stats{
display:grid;
grid-template-columns: repeat(4, 1fr);
gap: 1px;
background: var(--border-soft);
border: 1px solid var(--border-soft);
margin-bottom: 20px;
}
@media (max-width: 620px){ .stats{ grid-template-columns: repeat(2, 1fr); } }
.stat{
background: var(--panel);
padding: 14px 16px;
}
.stat-label{
font-family: var(--mono);
font-size: 10.5px;
color: var(--text-faint);
margin-bottom: 6px;
}
.stat-val{
font-family: var(--mono);
font-size: 18px;
color: var(--text);
font-weight: 500;
}
.stat-val.good{ color: var(--sage); }
.download-row{
display:flex; gap: 12px; flex-wrap: wrap;
align-items: center;
}
.jpeg-q{
display:flex; align-items:center; gap:10px;
font-family: var(--mono); font-size: 12px; color: var(--text-muted);
}
.jpeg-q input[type=range]{ width:100px; }
/* ---------- How it works ---------- */
details{
border: 1px solid var(--border-soft);
background: var(--panel);
padding: 16px 20px;
}
summary{
cursor:pointer;
font-size: 14px;
font-weight: 600;
list-style: none;
}
summary::-webkit-details-marker{ display:none; }
summary::before{
content: '+ ';
color: var(--amber);
font-family: var(--mono);
}
details[open] summary::before{ content: '– '; }
.how-body{
margin-top: 14px;
color: var(--text-muted);
font-size: 14px;
}
.how-body p{ margin: 0 0 10px; }
.how-body code{
font-family: var(--mono);
background: var(--panel-2);
padding: 1px 5px;
font-size: 12.5px;
color: var(--sage);
}
footer{
margin-top: 48px;
padding-top: 20px;
border-top: 1px solid var(--border-soft);
font-size: 12.5px;
color: var(--text-faint);
font-family: var(--mono);
}
</style>
</head>
<body>
<div class="wrap">
<header>
<p class="eyebrow">GENETIC ALGORITHM · COLOR QUANTIZATION</p>
<h1>Palette Evolution</h1>
<p>Compress an image by evolving a small color palette to match it as closely as possible — selection, crossover, and mutation, running entirely in your browser.</p>
</header>
<section>
<div class="dropzone" id="dropzone">
<svg class="dz-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4">
<path d="M4 16.5V18a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-1.5"/>
<path d="M7 9l5-5 5 5"/>
<path d="M12 4v13"/>
</svg>
<div class="dz-title">Drop an image here, or click to browse</div>
<div class="dz-sub">JPG or PNG. Processed locally — nothing leaves your device.</div>
<input type="file" id="fileInput" accept="image/*">
<div class="file-chip" id="fileChip" style="display:none;">
<strong id="fileName"></strong> <span id="fileMeta"></span>
</div>
</div>
</section>
<section>
<h2>SETTINGS</h2>
<div class="controls">
<div class="ctrl-row">
<div class="ctrl-label">Palette size</div>
<input type="range" id="numColors" min="2" max="64" value="16">
<div class="ctrl-val" id="numColorsVal">16</div>
</div>
<div class="ctrl-row">
<div class="ctrl-label">Population</div>
<input type="range" id="popSize" min="6" max="30" value="14">
<div class="ctrl-val" id="popSizeVal">14</div>
</div>
<div class="ctrl-row">
<div class="ctrl-label">Generations</div>
<input type="range" id="generations" min="10" max="150" value="50">
<div class="ctrl-val" id="generationsVal">50</div>
</div>
<label class="checkline">
<input type="checkbox" id="dither" checked>
Dither (Floyd–Steinberg) — smooths banding on gradients, recommended
</label>
<label class="checkline">
<input type="checkbox" id="edgeAware" checked>
Protect detail (edge-aware) — keeps faces, eyes, and texture free of dither noise
</label>
<div class="ctrl-row" id="sensitivityRow">
<div class="ctrl-label">Detail sensitivity</div>
<input type="range" id="sensitivity" min="0" max="100" value="50">
<div class="ctrl-val" id="sensitivityVal">50</div>
</div>
<label class="checkline">
<input type="checkbox" id="fullRes">
Process at full resolution (slower — otherwise capped at 1200px on the long edge)
</label>
</div>
<div class="run-row">
<button class="btn" id="runBtn" disabled>Evolve palette</button>
<span id="runHint" style="font-size:13px;color:var(--text-faint);">Upload an image to begin</span>
</div>
</section>
<section>
<div class="progress-box" id="progressBox">
<div class="progress-head">
<span>GENERATION <span class="hi" id="genNow">0</span> / <span id="genTotal">0</span></span>
<span>MEAN ERROR <span class="hi" id="fitNow">–</span></span>
</div>
<div class="bar-track"><div class="bar-fill" id="barFill"></div></div>
<canvas id="sparkline" width="800" height="56"></canvas>
</div>
</section>
<section class="results" id="results">
<h2>RESULT</h2>
<div class="compare">
<div class="frame">
<div class="frame-label"><span>ORIGINAL</span><span id="origDims"></span></div>
<canvas id="origCanvas"></canvas>
</div>
<div class="frame">
<div class="frame-label"><span>EVOLVED</span><span id="newDims"></span></div>
<canvas id="resultCanvas"></canvas>
</div>
</div>
<div class="palette-strip" id="paletteStrip"></div>
<div class="stats">
<div class="stat">
<div class="stat-label">ORIGINAL FILE</div>
<div class="stat-val" id="statOrigSize">–</div>
</div>
<div class="stat">
<div class="stat-label">COMPRESSED (PNG)</div>
<div class="stat-val good" id="statNewSize">–</div>
</div>
<div class="stat">
<div class="stat-label">REDUCTION</div>
<div class="stat-val good" id="statRatio">–</div>
</div>
<div class="stat">
<div class="stat-label">QUALITY (PSNR)</div>
<div class="stat-val" id="statPsnr">–</div>
</div>
</div>
<div class="download-row">
<button class="btn secondary" id="downloadPng">Download PNG</button>
<button class="btn secondary" id="downloadJpeg">Download JPEG</button>
<div class="jpeg-q">
Quality <input type="range" id="jpegQuality" min="30" max="95" value="80"> <span id="jpegQualityVal">80</span>
<span id="jpegSize" style="color:var(--text-faint);"></span>
</div>
</div>
</section>
<section>
<details>
<summary>How this works</summary>
<div class="how-body">
<p>Each individual in the population is a candidate palette of <code>N</code> colors. Fitness is the mean squared color error between the image and its nearest-palette approximation — lower is better.</p>
<p>Palettes start from a <code>k-means++</code>-style seeding (picking real pixel colors, weighted toward ones poorly covered so far) instead of pure random RGB values — this alone fixes most of the muddy, banded results you get from random initialization, since the population starts near a decent solution rather than searching blindly.</p>
<p>Each generation: the two best palettes survive unchanged (elitism), the rest are chosen by tournament selection, combined with uniform crossover (each color independently inherited from one parent), and mutated with a small, shrinking random jitter. Fitness is measured on a random pixel sample for speed; the final palette is applied to the full-resolution image at the end.</p>
<p>Color distance is measured with a perceptually-weighted formula rather than plain RGB distance, since the eye is more sensitive to green than to red or blue — this changes which colors the palette prioritizes and noticeably improves skin tones against cool backgrounds.</p>
<p>Snapping every pixel to its single nearest palette color produces visible banding on smooth gradients (skies, snow, skin). Floyd–Steinberg dithering fixes this by carrying each pixel's rounding error into its neighbors, turning hard bands into fine grain the eye blends back into a gradient.</p>
<p>Dithering alone would also scatter that grain over faces and fine texture, reading as blur or noise up close. <strong>Detail protection</strong> runs edge detection on the original image first and exempts high-contrast pixels — eyes, hair, fabric lines — from diffusion entirely, so they render straight from source color while flat regions around them still dither smoothly. Raise "detail sensitivity" if edges still look soft; lower it if flat areas start banding again.</p>
<p>"Compression" here comes from collapsing the image to a handful of colors — a PNG with 16 flat colors compresses far better than one with thousands, because there's far less unique data to encode. The size shown is the real, measured size of the exported file, not an estimate.</p>
</div>
</details>
</section>
<footer>palette-evolution.html — runs client-side, no server or upload required</footer>
</div>
<script>
(function(){
"use strict";
// ---------- DOM ----------
const dropzone = document.getElementById('dropzone');
const fileInput = document.getElementById('fileInput');
const fileChip = document.getElementById('fileChip');
const fileName = document.getElementById('fileName');
const fileMeta = document.getElementById('fileMeta');
const numColorsEl = document.getElementById('numColors');
const popSizeEl = document.getElementById('popSize');
const generationsEl = document.getElementById('generations');
const fullResEl = document.getElementById('fullRes');
const ditherEl = document.getElementById('dither');
const edgeAwareEl = document.getElementById('edgeAware');
const sensitivityEl = document.getElementById('sensitivity');
const sensitivityVal = document.getElementById('sensitivityVal');
sensitivityEl.addEventListener('input', ()=> sensitivityVal.textContent = sensitivityEl.value);
const numColorsVal = document.getElementById('numColorsVal');
const popSizeVal = document.getElementById('popSizeVal');
const generationsVal = document.getElementById('generationsVal');
const runBtn = document.getElementById('runBtn');
const runHint = document.getElementById('runHint');
const progressBox = document.getElementById('progressBox');
const genNow = document.getElementById('genNow');
const genTotal = document.getElementById('genTotal');
const fitNow = document.getElementById('fitNow');
const barFill = document.getElementById('barFill');
const sparkline = document.getElementById('sparkline');
const resultsSec = document.getElementById('results');
const origCanvas = document.getElementById('origCanvas');
const resultCanvas = document.getElementById('resultCanvas');
const origDims = document.getElementById('origDims');
const newDims = document.getElementById('newDims');
const paletteStrip = document.getElementById('paletteStrip');
const statOrigSize = document.getElementById('statOrigSize');
const statNewSize = document.getElementById('statNewSize');
const statRatio = document.getElementById('statRatio');
const statPsnr = document.getElementById('statPsnr');
const downloadPngBtn = document.getElementById('downloadPng');
const downloadJpegBtn = document.getElementById('downloadJpeg');
const jpegQuality = document.getElementById('jpegQuality');
const jpegQualityVal = document.getElementById('jpegQualityVal');
const jpegSize = document.getElementById('jpegSize');
let currentFile = null;
let currentImg = null;
// ---------- slider labels ----------
function syncLabel(input, label){ label.textContent = input.value; }
[[numColorsEl,numColorsVal],[popSizeEl,popSizeVal],[generationsEl,generationsVal]].forEach(([i,l])=>{
syncLabel(i,l);
i.addEventListener('input', ()=>syncLabel(i,l));
});
jpegQuality.addEventListener('input', ()=>{ jpegQualityVal.textContent = jpegQuality.value; updateJpegPreviewSize(); });
// ---------- file handling ----------
dropzone.addEventListener('click', ()=> fileInput.click());
dropzone.addEventListener('dragover', e=>{ e.preventDefault(); dropzone.classList.add('drag'); });
dropzone.addEventListener('dragleave', ()=> dropzone.classList.remove('drag'));
dropzone.addEventListener('drop', e=>{
e.preventDefault();
dropzone.classList.remove('drag');
if (e.dataTransfer.files && e.dataTransfer.files[0]) handleFile(e.dataTransfer.files[0]);
});
fileInput.addEventListener('change', e=>{
if (e.target.files && e.target.files[0]) handleFile(e.target.files[0]);
});
function handleFile(file){
if (!file.type.startsWith('image/')){ return; }
currentFile = file;
const url = URL.createObjectURL(file);
const img = new Image();
img.onload = ()=>{
currentImg = img;
fileName.textContent = file.name;
fileMeta.textContent = ` · ${img.naturalWidth}×${img.naturalHeight} · ${formatBytes(file.size)}`;
fileChip.style.display = 'inline-flex';
runBtn.disabled = false;
runHint.textContent = 'Ready';
resultsSec.classList.remove('active');
progressBox.classList.remove('active');
drawToCanvas(origCanvas, img, img.naturalWidth, img.naturalHeight);
origDims.textContent = `${img.naturalWidth}×${img.naturalHeight}`;
};
img.src = url;
}
function formatBytes(n){
if (n < 1024) return n + ' B';
if (n < 1024*1024) return (n/1024).toFixed(1) + ' KB';
return (n/(1024*1024)).toFixed(2) + ' MB';
}
function drawToCanvas(canvas, img, w, h){
canvas.width = w; canvas.height = h;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, w, h);
}
// ---------- Genetic algorithm ----------
// Perceptually-weighted color distance ("redmean" approximation).
// Plain Euclidean RGB distance under-weights blue and over-weights green
// relative to how the eye perceives differences; this weighting is cheap
// and noticeably improves which colors the palette prioritizes.
function weightedDist2(r1,g1,b1,r2,g2,b2){
const rmean = (r1+r2) / 2;
const dr = r1-r2, dg = g1-g2, db = b1-b2;
const wr = 2 + rmean/256;
const wg = 4;
const wb = 2 + (255-rmean)/256;
return wr*dr*dr + wg*dg*dg + wb*db*db;
}
// k-means++ style seeding: pick real pixel colors, weighted toward
// pixels far from colors already chosen. Produces a strong starting
// palette instead of the random RGB triples the original script used.
function seedPalette(pixels, k){
const n = pixels.length / 3;
const centers = [];
let firstIdx = Math.floor(Math.random() * n);
centers.push([pixels[firstIdx*3], pixels[firstIdx*3+1], pixels[firstIdx*3+2]]);
const distSq = new Float64Array(n).fill(Infinity);
for (let c = 1; c < k; c++){
const last = centers[centers.length-1];
let sum = 0;
for (let i = 0; i < n; i++){
const d = weightedDist2(pixels[i*3], pixels[i*3+1], pixels[i*3+2], last[0], last[1], last[2]);
if (d < distSq[i]) distSq[i] = d;
sum += distSq[i];
}
let r = Math.random() * sum;
let chosen = n - 1;
for (let i = 0; i < n; i++){
r -= distSq[i];
if (r <= 0){ chosen = i; break; }
}
centers.push([pixels[chosen*3], pixels[chosen*3+1], pixels[chosen*3+2]]);
}
return centers;
}
function randomSample(pixels, sampleSize){
const n = pixels.length / 3;
const size = Math.min(sampleSize, n);
const out = new Uint8ClampedArray(size*3);
for (let i = 0; i < size; i++){
const idx = Math.floor(Math.random() * n);
out[i*3] = pixels[idx*3];
out[i*3+1] = pixels[idx*3+1];
out[i*3+2] = pixels[idx*3+2];
}
return out;
}
function fitness(palette, samplePixels){
const n = samplePixels.length / 3;
const k = palette.length;
let total = 0;
for (let i = 0; i < n; i++){
const px = samplePixels[i*3], py = samplePixels[i*3+1], pz = samplePixels[i*3+2];
let best = Infinity;
for (let c = 0; c < k; c++){
const d = weightedDist2(px, py, pz, palette[c][0], palette[c][1], palette[c][2]);
if (d < best) best = d;
}
total += best;
}
return total / n;
}
function tournamentSelect(population, fitnesses, tSize){
let bestIdx = Math.floor(Math.random() * population.length);
for (let i = 1; i < tSize; i++){
const idx = Math.floor(Math.random() * population.length);
if (fitnesses[idx] < fitnesses[bestIdx]) bestIdx = idx;
}
return population[bestIdx];
}
function uniformCrossover(p1, p2){
const k = p1.length;
const child = new Array(k);
for (let i = 0; i < k; i++){
child[i] = (Math.random() < 0.5 ? p1[i] : p2[i]).slice();
}
return child;
}
function mutate(palette, strength, rate){
for (let i = 0; i < palette.length; i++){
for (let ch = 0; ch < 3; ch++){
if (Math.random() < rate){
const delta = (Math.random()*2 - 1) * strength;
palette[i][ch] = Math.min(255, Math.max(0, Math.round(palette[i][ch] + delta)));
}
}
}
return palette;
}
function clonePalette(p){ return p.map(c => c.slice()); }
// Runs the GA, yielding control between generations so the UI can update.
async function runGeneticAlgorithm(pixels, k, popSize, generations, onGen){
const sample = randomSample(pixels, 6000);
let population = [];
for (let i = 0; i < popSize; i++) population.push(seedPalette(pixels, k));
let best = null, bestFit = Infinity;
const history = [];
for (let gen = 0; gen < generations; gen++){
const fitnesses = population.map(p => fitness(p, sample));
let genBestIdx = 0;
for (let i = 1; i < fitnesses.length; i++) if (fitnesses[i] < fitnesses[genBestIdx]) genBestIdx = i;
if (fitnesses[genBestIdx] < bestFit){
bestFit = fitnesses[genBestIdx];
best = clonePalette(population[genBestIdx]);
}
history.push(bestFit);
onGen(gen+1, generations, bestFit, history);
await new Promise(r => setTimeout(r, 0)); // yield to UI thread
if (gen === generations - 1) break;
// elitism: keep best 2 palettes untouched
const order = fitnesses.map((f,i)=>i).sort((a,b)=>fitnesses[a]-fitnesses[b]);
const newPop = [clonePalette(population[order[0]]), clonePalette(population[order[1]] || population[order[0]])];
const mutationStrength = 26 * (1 - gen/generations) + 2;
const mutationRate = 0.12;
while (newPop.length < popSize){
const parent1 = tournamentSelect(population, fitnesses, 3);
const parent2 = tournamentSelect(population, fitnesses, 3);
let child = uniformCrossover(parent1, parent2);
child = mutate(child, mutationStrength, mutationRate);
newPop.push(child);
}
population = newPop;
}
return { palette: best, history };
}
function nearestColor(r, g, b, palette){
let best = Infinity, bestC = palette[0];
for (let c = 0; c < palette.length; c++){
const d = weightedDist2(r, g, b, palette[c][0], palette[c][1], palette[c][2]);
if (d < best){ best = d; bestC = palette[c]; }
}
return bestC;
}
// Sobel edge magnitude on the original (pre-quantization) image. Used to
// tell dithering apart from areas of real detail — eyes, hair, fabric
// texture — so noise isn't scattered over the pixels where sharpness
// matters most.
function computeEdgeMap(imageData){
const w = imageData.width, h = imageData.height;
const data = imageData.data;
const gray = new Float32Array(w*h);
for (let i = 0, j = 0; i < data.length; i += 4, j++){
gray[j] = 0.299*data[i] + 0.587*data[i+1] + 0.114*data[i+2];
}
const mag = new Float32Array(w*h);
const gx = [-1,0,1,-2,0,2,-1,0,1];
const gy = [-1,-2,-1,0,0,0,1,2,1];
for (let y = 1; y < h-1; y++){
for (let x = 1; x < w-1; x++){
let sx = 0, sy = 0, k = 0;
for (let dy = -1; dy <= 1; dy++){
for (let dx = -1; dx <= 1; dx++){
const v = gray[(y+dy)*w + (x+dx)];
sx += v*gx[k]; sy += v*gy[k]; k++;
}
}
mag[y*w+x] = Math.sqrt(sx*sx + sy*sy);
}
}
return mag;
}
// Plain nearest-color quantization — accurate to the palette but produces
// hard banding on smooth gradients (visible as stripes in skies/snow).
function quantizeFlat(imageData, palette){
const data = imageData.data;
const out = new ImageData(imageData.width, imageData.height);
const outData = out.data;
for (let i = 0; i < data.length; i += 4){
const bestC = nearestColor(data[i], data[i+1], data[i+2], palette);
outData[i] = bestC[0]; outData[i+1] = bestC[1]; outData[i+2] = bestC[2]; outData[i+3] = 255;
}
return out;
}
// Floyd–Steinberg dithering: scatters each pixel's quantization error into
// its not-yet-processed neighbors, which breaks up hard banding into fine
// grain the eye blends back into a smooth gradient. When an edge map is
// supplied, pixels flagged as "detail" (edgeMap value above threshold)
// skip diffusion entirely — they read their color straight from the
// untouched original pixel and don't pass error to neighbors — so noise
// never gets laid over faces, eyes, or fine texture, while flat regions
// still dither smoothly.
function quantizeDithered(imageData, palette, edgeMap, edgeThreshold){
const w = imageData.width, h = imageData.height;
const src = imageData.data;
const orig = new Float32Array(w*h*3);
const buf = new Float32Array(w*h*3);
for (let i = 0, j = 0; i < src.length; i += 4, j += 3){
orig[j] = src[i]; orig[j+1] = src[i+1]; orig[j+2] = src[i+2];
buf[j] = src[i]; buf[j+1] = src[i+1]; buf[j+2] = src[i+2];
}
const out = new ImageData(w, h);
const outData = out.data;
const addErr = (x, y, er, eg, eb, factor) => {
if (x < 0 || x >= w || y < 0 || y >= h) return;
const j = (y*w + x) * 3;
buf[j] += er * factor;
buf[j+1] += eg * factor;
buf[j+2] += eb * factor;
};
const hasEdgeMap = !!edgeMap;
for (let y = 0; y < h; y++){
for (let x = 0; x < w; x++){
const idx = y*w + x;
const j = idx * 3;
const isDetail = hasEdgeMap && edgeMap[idx] > edgeThreshold;
let r, g, b;
if (isDetail){
// ignore any diffused error — render this pixel true to source
r = orig[j]; g = orig[j+1]; b = orig[j+2];
} else {
r = Math.min(255, Math.max(0, buf[j]));
g = Math.min(255, Math.max(0, buf[j+1]));
b = Math.min(255, Math.max(0, buf[j+2]));
}
const bestC = nearestColor(r, g, b, palette);
if (!isDetail){
const er = r - bestC[0], eg = g - bestC[1], eb = b - bestC[2];
addErr(x+1, y, er, eg, eb, 7/16);
addErr(x-1, y+1, er, eg, eb, 3/16);
addErr(x, y+1, er, eg, eb, 5/16);
addErr(x+1, y+1, er, eg, eb, 1/16);
}
// detail pixels propagate nothing — keeps edges from bleeding noise
// into neighboring smooth areas
const i = idx * 4;
outData[i] = bestC[0]; outData[i+1] = bestC[1]; outData[i+2] = bestC[2]; outData[i+3] = 255;
}
}
return out;
}
function quantizeImageData(imageData, palette, dither, edgeMap, edgeThreshold){
return dither ? quantizeDithered(imageData, palette, edgeMap, edgeThreshold) : quantizeFlat(imageData, palette);
}
function computePSNR(a, b){
const da = a.data, db = b.data;
let mse = 0, n = 0;
for (let i = 0; i < da.length; i += 4){
for (let c = 0; c < 3; c++){
const diff = da[i+c] - db[i+c];
mse += diff*diff;
n++;
}
}
mse /= n;
if (mse === 0) return Infinity;
return 10 * Math.log10((255*255)/mse);
}
function drawSparkline(history){
const ctx = sparkline.getContext('2d');
const w = sparkline.width, h = sparkline.height;
ctx.clearRect(0,0,w,h);
if (history.length < 2) return;
const max = Math.max(...history), min = Math.min(...history);
const range = (max - min) || 1;
ctx.beginPath();
ctx.strokeStyle = '#6fa98a';
ctx.lineWidth = 1.5;
history.forEach((v,i)=>{
const x = (i/(history.length-1)) * (w-4) + 2;
const y = h - 4 - ((v-min)/range) * (h-8);
if (i===0) ctx.moveTo(x,y); else ctx.lineTo(x,y);
});
ctx.stroke();
// fill
ctx.lineTo(w-2, h-2); ctx.lineTo(2, h-2); ctx.closePath();
ctx.fillStyle = 'rgba(111,169,138,0.08)';
ctx.fill();
}
// ---------- Run button ----------
let lastPngBlob = null;
let lastQuantizedCanvas = null;
runBtn.addEventListener('click', async ()=>{
if (!currentImg) return;
runBtn.disabled = true;
runHint.textContent = 'Evolving…';
progressBox.classList.add('active');
resultsSec.classList.remove('active');
const k = parseInt(numColorsEl.value, 10);
const popSize = parseInt(popSizeEl.value, 10);
const generations = parseInt(generationsEl.value, 10);
const useFullRes = fullResEl.checked;
genTotal.textContent = generations;
genNow.textContent = '0';
fitNow.textContent = '–';
barFill.style.width = '0%';
// working resolution for the GA + preview (capped for speed unless full-res requested)
const maxDim = 1200;
let workW = currentImg.naturalWidth, workH = currentImg.naturalHeight;
if (!useFullRes){
const longest = Math.max(workW, workH);
if (longest > maxDim){
const scale = maxDim / longest;
workW = Math.round(workW * scale);
workH = Math.round(workH * scale);
}
}
const workCanvas = document.createElement('canvas');
workCanvas.width = workW; workCanvas.height = workH;
const workCtx = workCanvas.getContext('2d');
workCtx.drawImage(currentImg, 0, 0, workW, workH);
const workImageData = workCtx.getImageData(0, 0, workW, workH);
// flat RGB array (no alpha) for the GA
const flatPixels = new Uint8ClampedArray((workImageData.data.length/4) * 3);
for (let i = 0, j = 0; i < workImageData.data.length; i += 4, j += 3){
flatPixels[j] = workImageData.data[i];
flatPixels[j+1] = workImageData.data[i+1];
flatPixels[j+2] = workImageData.data[i+2];
}
const { palette, history } = await runGeneticAlgorithm(flatPixels, k, popSize, generations, (gen, total, fit, hist)=>{
genNow.textContent = gen;
fitNow.textContent = fit.toFixed(1);
barFill.style.width = Math.round((gen/total)*100) + '%';
drawSparkline(hist);
});
const quantized = quantizeImageData(
workImageData,
palette,
ditherEl.checked,
(ditherEl.checked && edgeAwareEl.checked) ? computeEdgeMap(workImageData) : null,
160 - parseInt(sensitivityEl.value, 10) * 1.3
);
const psnr = computePSNR(workImageData, quantized);
resultCanvas.width = workW; resultCanvas.height = workH;
resultCanvas.getContext('2d').putImageData(quantized, 0, 0);
newDims.textContent = `${workW}×${workH}`;
lastQuantizedCanvas = resultCanvas;
// palette swatches, sorted for a nicer strip
paletteStrip.innerHTML = '';
const sortedPalette = palette.slice().sort((a,b)=> (a[0]+a[1]+a[2]) - (b[0]+b[1]+b[2]));
sortedPalette.forEach(c=>{
const sw = document.createElement('div');
sw.className = 'swatch';
sw.style.background = `rgb(${c[0]},${c[1]},${c[2]})`;
paletteStrip.appendChild(sw);
});
// measured sizes
statOrigSize.textContent = currentFile ? formatBytes(currentFile.size) : '–';
statPsnr.textContent = isFinite(psnr) ? psnr.toFixed(1) + ' dB' : '∞';
resultCanvas.toBlob((blob)=>{
lastPngBlob = blob;
statNewSize.textContent = formatBytes(blob.size);
if (currentFile){
const ratio = 1 - (blob.size / currentFile.size);
statRatio.textContent = (ratio*100 >= 0 ? '−' : '+') + Math.abs(ratio*100).toFixed(0) + '%';
} else {
statRatio.textContent = '–';
}