-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathSimpleImageMatch.h
1685 lines (1586 loc) · 74.3 KB
/
SimpleImageMatch.h
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
//
// SimpleImageMatch.h
// TexSyn
//
// Created by Craig Reynolds on 6/30/21.
// Copyright © 2021 Craig Reynolds. All rights reserved.
//
//------------------------------------------------------------------------------
// TODO improve
// Evolve textures to match a given example. Uses simple "image similarity" for
// fitness. (Non-interactive, no tournament.) Hoping to to find interesting
// “stylizations” via evolutionary search. Prototype for co-evolutionary version
// of stylization search.
//------------------------------------------------------------------------------
#pragma once
#include "GP.h"
// TODO could inherit from EvoCamoGame instead of stealing bit of its code.
// TODO Or there could be a common base class.
class SimpleImageMatch
{
public:
// TODO parameters
// simple_image_match target_image (pathname string)
// output_directory (pathname string)
// random_seed (int)
// individuals (int)
// subpops (int)
// max_init_tree_size (int)
// min_crossover_tree_size (int)
// max_crossover_tree_size (int)
SimpleImageMatch(const CommandLine& cmd)
: target_image_pathname_(cmd.positionalArgument(1)),
run_name_(fs::path(target_image_pathname_).stem()),
output_directory_(cmd.positionalArgument(2, ".")),
output_directory_this_run_(runOutputDirectory()),
random_seed_(cmd.positionalArgument(3, int(LPRS().defaultSeed()))),
individuals_(cmd.positionalArgument(4, 120)),
subpops_(cmd.positionalArgument(5, 6)),
max_init_tree_size_(cmd.positionalArgument(6, 100)),
min_crossover_tree_size_
(cmd.positionalArgument(7, max_init_tree_size_ * 0.5f)),
max_crossover_tree_size_
(cmd.positionalArgument(8, max_init_tree_size_ * 1.5f)),
target_image_(cv::imread(target_image_pathname_))
{
// Avoid huge differences for tiny parameter mutation.
Texture::setSeedFromHashedArgs(false);
setGuiSize();
// log parameters for this run
std::cout << "SimpleImageMatch parameters:" << std::endl;
std::cout << " "; debugPrint(target_image_pathname_)
std::cout << " "; debugPrint(getTargetImageSize());
std::cout << " "; debugPrint(run_name_);
std::cout << " "; debugPrint(output_directory_);
std::cout << " "; debugPrint(output_directory_this_run_);
std::cout << " "; debugPrint(random_seed_);
std::cout << " "; debugPrint(individuals_);
std::cout << " "; debugPrint(subpops_);
std::cout << " "; debugPrint(max_init_tree_size_);
std::cout << " "; debugPrint(min_crossover_tree_size_);
std::cout << " "; debugPrint(max_crossover_tree_size_);
assert((target_image_.cols > 0) &&
(target_image_.rows > 0) &&
"target image missing or empty");
//~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
std::cout << "~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~" << std::endl;
debugPrint(imageUniformity2(target_image_));
debugPrint(imageNonuniformity(target_image_));
std::cout << "~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~" << std::endl;
//~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
// Build "MIP map like" resolution pyramid for target image.
makeResolutionPyramid(target_image_, target_pyramid_);
// TODO do this here, or in the initializers above, or in run()?
std::cout << "Create initial population..." << std::endl;
LPRS().setSeed(random_seed_);
population_ = std::make_shared<Population>(individuals_,
subpops_,
max_init_tree_size_,
min_crossover_tree_size_,
max_crossover_tree_size_,
GP::fs());
std::cout << "...done." << std::endl;
}
// Run the evolution simulation.
// // TODO this is the original "absolute fitness" version.
// void run()
// {
// while (true)
// {
// // logFunctionUsageCounts(out);
// updateGuiWindowTitle();
// population_->evolutionStep([&]
// (Individual* i)
// { return fitnessFunction(i); });
// }
// // Delete Population instance.
// population_ = nullptr;
// }
// TODO this is the new "relative (tournament) fitness" version.
void run()
{
while (true)
{
// logFunctionUsageCounts(out);
updateGuiWindowTitle();
population_->evolutionStep([&]
(TournamentGroup tg)
{ return tournamentFunction(tg); });
}
// Delete Population instance.
population_ = nullptr;
}
//~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~
// float sqrt_of_sub_windows = 3;
// size_t count_of_sub_windows = sq(sqrt_of_sub_windows);
static inline float sqrt_of_sub_windows = 4;
static inline size_t count_of_sub_windows = sq(sqrt_of_sub_windows);
//~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~
//~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
// 0 to 0.39 ish
// static inline float max_nonuniformity = 0;
//~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
// TODO new September 2, 2021
TournamentGroup tournamentFunction(TournamentGroup tg)
{
// Helper class for Individual, Texture, Count of most similar pixels.
class ITC
{
public:
ITC(Individual* i) : ITC(i, GP::textureFromIndividual(i)) {}
// TODO instead of this, maybe setup() should return a ITC instead
// of an Individual. In fact, try again to move setup() into
// the ITC constructor.
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// ITC(Individual* i, Texture* t)
// : individual(i),
// texture(t),
// nonuniformity(1 - imageUniformity(texture->getCvMat())) {}
ITC(Individual* i, Texture* t)
: individual(i),
texture(t),
//~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
// nonuniformity(1 - imageUniformity(texture->getCvMat())),
// nonuniformity(1 - imageUniformity(texture->getCvMat(), 0.8)),
nonuniformity(imageNonuniformity(texture->getCvMat())),
sw_counts(count_of_sub_windows, 0) {}
// sw_counts(count_of_sub_windows, 0)
// {
// debugPrint(nonuniformity);
// max_nonuniformity = std::max(nonuniformity, max_nonuniformity);
// debugPrint(max_nonuniformity);
// }
//~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Individual* individual = nullptr;
Texture* texture = nullptr;
float nonuniformity = 1;
int count = 0;
cv::Mat wins;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
std::vector<int> sw_counts;
void countIJ(int i, int j)
{
cv::Mat mat = texture->getCvMat();
assert(mat.cols == mat.rows); // TODO assume square Mat
int p = i / (wins.cols / sqrt_of_sub_windows);
int q = j / (wins.rows / sqrt_of_sub_windows);
int c = (p * sqrt_of_sub_windows) + q;
assert(c < count_of_sub_windows);
sw_counts.at(c)++;
}
// int swLeastCount()
// {
// int least = std::numeric_limits<int>::max();
// for (auto c : sw_counts) { if (least > c ){ least = c; } }
// return least;
// }
// TODO 20210920: since the two runs I recently tried using "worst
// of subwindow counts" were REALLY not successful (and perhaps just
// randomly, but VERY slow, probably because of lots of Blur) I
// decided to try one with "best of subwindow counts":
// int swLeastCount()
int swMaxCount()
{
// int least = std::numeric_limits<int>::max();
int max_count = std::numeric_limits<int>::min();
int i = 0;
// int least_i = 0;
int max_i = 0;
for (auto c : sw_counts)
{
// if (least > c ){ least = c; least_i = i; }
if (max_count < c ){ max_count = c; max_i = i; }
i++;
}
for (int i = 0; i < wins.cols; i++)
{
for (int j = 0; j < wins.rows; j++)
{
int p = i / (wins.cols / sqrt_of_sub_windows);
int q = j / (wins.rows / sqrt_of_sub_windows);
int c = (p * sqrt_of_sub_windows) + q;
assert(c < count_of_sub_windows);
// if (c != least_i)
if (c != max_i)
{
cv::Point position(j, i);
cv::Vec3b before = wins.at<cv::Vec3b>(position);
// Apply dark red filter to ignored pixels.
before[0] *= 0.1;
before[1] *= 0.1;
before[2] *= 0.4;
wins.at<cv::Vec3b>(position) = before;
}
}
}
// std::cout << vec_to_string(sw_counts);
// std::cout << " → " << least << std::endl;
// return least;
return max_count;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~
int swCountInWinners(const std::vector<Individual*>& sw_winner)
{
int total = 0;
for (int sw = 0; sw < count_of_sub_windows; sw++)
{
if (sw_winner.at(sw) == individual)
{
total += sw_counts.at(sw);
}
}
for (int i = 0; i < wins.cols; i++)
{
for (int j = 0; j < wins.rows; j++)
{
int p = i / (wins.cols / sqrt_of_sub_windows);
int q = j / (wins.rows / sqrt_of_sub_windows);
int sw = (p * sqrt_of_sub_windows) + q;
assert(sw < count_of_sub_windows);
if (sw_winner.at(sw) != individual)
{
cv::Point position(j, i);
cv::Vec3b before = wins.at<cv::Vec3b>(position);
// Apply dark red filter to ignored pixels.
before[0] *= 0.1;
before[1] *= 0.1;
before[2] *= 0.4;
wins.at<cv::Vec3b>(position) = before;
}
}
}
return total;
}
//~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~
};
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// bool weakest_link = false;
bool weakest_link = true;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Ensure each Texture has been rendered
auto setup = [&](TournamentGroupMember& tgm)
{
Individual* i = tgm.individual;
Texture* texture = GP::textureFromIndividual(i);
if (texture->getCvMat().cols == 0)
{
// Timer t("Render");
// std::cout << " ";
int width = target_image_.cols;
int height = target_image_.rows;
texture->rasterizeToImageCache(width, false); // false → square.
cv::Mat mat = texture->getCvMat();
assert((mat.cols == width) && (mat.rows == height));
}
return i;
};
// Build collection of ITCs.
std::vector<ITC> itcs;
for (auto& tgm : tg.members()) { itcs.push_back({ setup(tgm) }); }
// Lookup ITC for given Individual
auto get_itc = [&](Individual* i)
{
ITC* r = &itcs.front() ;
for (auto& itc : itcs) { if (i == itc.individual) { r = &itc; } }
return r;
};
// Set win Mats to be all black
for (auto& itc : itcs)
{
itc.wins = cv::Mat(target_image_.cols, target_image_.rows, CV_8UC3);
itc.wins.setTo(cv::Scalar(0));
}
// For each pixel: score one point to the tournament group member whose
// pixel color is most similar to the target image pixel color.
for (int i = 0; i < target_image_.cols; i++)
{
for (int j = 0; j < target_image_.rows; j++)
{
float max_similarity = std::numeric_limits<float>::lowest();
Individual* max_sim_ind = nullptr;
for (auto& itc : itcs)
{
Color a = getCvMatPixel(i, j, itc.texture->getCvMat());
Color b = getCvMatPixel(i, j, target_image_);
float similarity = Color::similarity(a, b);
if (max_similarity < similarity)
{
max_similarity = similarity;
max_sim_ind = itc.individual;
}
}
assert(max_sim_ind != nullptr);
ITC* max_sim_itc = get_itc(max_sim_ind);
// Increment score of Individual with max similarity this pixel.
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// max_sim_itc->count++;
if (weakest_link)
{
max_sim_itc->countIJ(i, j);
}
else
{
max_sim_itc->count++;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Draw a gray pixel on "wins" map for that Individual.
int n = 255 * max_sim_itc->nonuniformity;
cv::Vec3b gray(n, n, n);
cv::Point position(j, i);
max_sim_itc->wins.at<cv::Vec3b>(position) = gray;
}
}
// Set "arbitrary" alt_fitness only for sake of display ordering in GUI.
for (auto& itc : itcs)
{
Individual* individual = itc.individual;
if (individual->alt_fitness < 0)
{
Texture* texture = itc.texture;
cv::Mat mat = texture->getCvMat();
float similarity = imageAvePixelSimilarity(mat, target_image_);
//float similarity = imageAug3Similarlity(mat, target_image_);
assert(similarity >= 0);
//~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
// TODO 20210925, shouldn't these be scaled by nonuniformity?
// individual->alt_fitness = similarity;
individual->alt_fitness = similarity * itc.nonuniformity;
//~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
}
}
//~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~
// TODO 20210921 very experimental.
std::vector<Individual*> sw_winner(count_of_sub_windows, nullptr);
for (int sw = 0; sw < count_of_sub_windows; sw++)
{
// TODO assume there are three ITCs, rewrite later if kept.
sw_winner[sw] = itcs.at(0).individual;
if (itcs.at(0).sw_counts[sw] < itcs.at(1).sw_counts[sw])
{
sw_winner[sw] = itcs.at(1).individual;
}
else if (itcs.at(0).sw_counts[sw] < itcs.at(2).sw_counts[sw])
{
sw_winner[sw] = itcs.at(2).individual;
}
}
//~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~
// Write the ITC counts into tg "metric" field.
tg.setAllMetrics([&](Individual* i)
{
float m = 0;
for (auto& itc : itcs)
{
Individual* j = itc.individual;
if (i == j)
{
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// cv::Mat mat = GP::textureFromIndividual(i)->getCvMat();
// m = int(itc.count * itc.nonuniformity);
if (weakest_link)
{
// m = int(itc.swLeastCount() * itc.nonuniformity);
//~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~
// m = int(itc.swMaxCount() * itc.nonuniformity);
m = int(itc.swCountInWinners(sw_winner) *
itc.nonuniformity);
//~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~
}
else
{
m = int(itc.count * itc.nonuniformity);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
}
}
return m;
});
// Update "standing"
for (int k = 1; k < tg.members().size(); k++)
{
Individual* current = tg.members().at(k).individual;
Individual* previous = tg.members().at(k - 1).individual;
current->adjustStandingForWinAgainst(*previous);
}
std::cout << " counts:";
for (auto& tgm : tg.members()) { std::cout << " " << int(tgm.metric); }
std::cout << " \"fitnesses\":";
auto get_nonuni = [&](Individual* i){return get_itc(i)->nonuniformity;};
bool fitness_in_order = true;
float prev_fitness = std::numeric_limits<float>::lowest();
for (auto& tgm : tg.members())
{
float n = get_nonuni(tgm.individual);
float f = n * tgm.individual->alt_fitness;
if (prev_fitness > f) fitness_in_order = false;
prev_fitness = f;
std::cout << " " << f;
}
if (!fitness_in_order) std::cout << " (ooo)";
std::cout << " (nonuniformities:";
for (auto& tgm : tg.members())
{
std::cout << " " << std::setprecision(2);
std::cout << get_nonuni(tgm.individual);
std::cout << std::setprecision(8);
}
std::cout << ")" << std::endl;
std::cout << " relative_fitness:";
for (auto& tgm : tg.members())
{
std::cout << " " << tgm.individual->getFitness();
}
// Collect pointers to all Individuals, sort by "alt_fitness".
std::vector<Individual*> all_alt_fitnesses;
population_->applyToAllIndividuals([&]
(Individual* i)
{ all_alt_fitnesses.push_back(i); });
// Sort with largest fitness Individuals at the front.
std::sort(all_alt_fitnesses.begin(),
all_alt_fitnesses.end(),
[](Individual* a, Individual* b)
{ return a->alt_fitness > b->alt_fitness; });
float average_alt_fitness = 0;
int aaf_count = 0;
for (auto& individual: all_alt_fitnesses)
{
float af = individual->alt_fitness;
if (af >= 0) { average_alt_fitness += af; aaf_count++; }
}
average_alt_fitness /= aaf_count;
std::cout << std::setprecision(2);
std::cout << " average_alt_fitness: " << average_alt_fitness;
std::cout << " top_alt_fitness: (";
for (int k = 0; k < 5; k++)
{
if (k > 0) { std::cout << " "; }
std::cout << all_alt_fitnesses.at(k)->alt_fitness;
}
std::cout << ")";
std::cout << std::endl;
// Draw.
std::vector<const cv::Mat*> mats;
cv::Mat blank(target_image_.cols, target_image_.rows, CV_8UC3);
blank.setTo(cv::Scalar(127, 127, 127));
mats.push_back(&target_image_);
for (auto& tgm : tg.members())
{
Individual* i = tgm.individual;
mats.push_back(&blank);
mats.push_back(&(GP::textureFromIndividual(i)->getCvMat()));
mats.push_back(&(get_itc(i)->wins));
}
// Two rows of highest alt_fitness.
for (int a = 0; a < 20; a++)
{
Individual* i = all_alt_fitnesses.at(a);
mats.push_back(&(GP::textureFromIndividual(i)->getCvMat()));
}
drawGuiForFitnessFunction(mats);
drawLineUnderNthRowInGUI(1, Color(1));
drawLineUnderNthRowInGUI(3, Color(1));
gui().refresh();
return tg;
}
float fitnessFunction(Individual* individual)
{
Texture& texture = *GP::textureFromIndividual(individual);
texture.rasterizeToImageCache(getTargetImageSize().x(), false);
cv::Mat mat = texture.getCvMat();
drawGuiForFitnessFunction(mat, target_image_);
// float similarity = imageOhDearGodSimilarity(mat, target_image_);
// float similarity = imageTotalErrorSquared(mat, target_image_);
// float similarity = imageYetAnotherSimilarlity(mat, target_image_);
// float similarity = imageJuly30Similarlity(mat, target_image_);
// float similarity = imageJuly31Similarlity(mat, target_image_);
// float similarity = imageAug2Similarlity(mat, target_image_);
// float similarity = imageAug3Similarlity(mat, target_image_);
// float similarity = imageThresholdSimilarity(mat, target_image_);
float similarity = imageCoarseToFineSimilarity(mat, target_image_);
float nonuniformity = 1 - imageUniformity(mat);
float fitness = similarity * nonuniformity;
// float fitness = similarity;
std::cout << " fitness=" << fitness;
// std::cout << " (oh_dear_god_similarity=" << similarity;
// std::cout << " (imageTotalErrorSquared=" << similarity;
// std::cout << " (imageYetAnotherSimilarlity=" << similarity;
// std::cout << " (imageJuly30Similarlity=" << similarity;
// std::cout << " (imageJuly31Similarlity=" << similarity;
// std::cout << " (imageAug2Similarlity=" << similarity;
// std::cout << " (imageAug3Similarlity=" << similarity;
// std::cout << " (imageThresholdSimilarity=" << similarity;
// std::cout << " nonuniformity=" << nonuniformity << ")" << std::endl;
// std::cout << " (imageCoarseToFineSimilarity=" << similarity << ")";
// std::cout << std::endl;
std::cout << " (imageCoarseToFineSimilarity=" << similarity;
std::cout << " nonuniformity=" << nonuniformity << ")" << std::endl;
return fitness;
}
// Returns a number on [0, 1] by a MIP-map-ish approach operating at various
// levels of resolution.
//
// TODO problem, this wants to compare with target_pyramid_, but currently
// gets args passed in as two Mats (m0, m1) just assuming m0 is "newest" and
// m1 is "target". Needs redesign.
//
// 0 64x64 4096
// 1 32x32 1024
// 2 16x16 256
// 3 8x8 64
// 4 4x4 16
// 5 2x2 4
// 6 1x1 1
//
float imageMipMapSimilarity(const cv::Mat& m0, const cv::Mat& m1) const
{
// Build "MIP map like" resolution pyramid for newest evolved image.
std::vector<cv::Mat> newest_pyramid;
makeResolutionPyramid(m0, newest_pyramid);
assert(newest_pyramid.size() == target_pyramid_.size()); // TODO temp
#if 1 // use ONLY the 16x16 down sampled version
// TODO TEMP -- July 18, 2021 10:40-ish
// use ONLY the 16x16 down sampled version
// Index of the 1x1 image level in pyramid.
size_t p = newest_pyramid.size() - 1;
int step = 4;
// debugPrint(newest_pyramid.at(p - step).cols); -> 16 as expected
return imageAvePixelSimilarity(newest_pyramid.at(p - step),
target_pyramid_.at(p - step));
#else // use ONLY the 16x16 down sampled version
//~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~
// // TODO July 15, pure multiplicative
// float score = 1;
// TODO July 15, average of layers
float score = 0;
//~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~
// int steps = 7; // 64x64 = 4096 at highest resolution level
// int steps = 5; // 16x16 = 256 at highest resolution level
// int steps = 4; // 8x8 = 64 at highest resolution level
// int steps = 3; // 4x4 = 16 at highest resolution level
// int steps = 4; // 8x8 = 64 at highest resolution level (July 17)
// int steps = 3; // 4x4 = 16 at highest resolution level
int steps = 5; // 16x16 = 256 at highest resolution level (July 18)
for (int step = 0; step < steps; step++)
{
// Index of the 1x1 image level in pyramid.
size_t p = newest_pyramid.size() - 1;
// Increment score by similarity at this pyramid level.
//~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~
// // TODO July 15, pure multiplicative
// score *= imageProductPixelSimilarity(newest_pyramid.at(p - step),
// target_pyramid_.at(p - step));
score += imageAvePixelSimilarity(newest_pyramid.at(p - step),
target_pyramid_.at(p - step));
//~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~
}
//~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~
// // TODO July 15, pure multiplicative
// return score;
// TODO July 15, average of layers
return score / steps;
//~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~~
#endif // use ONLY the 16x16 down sampled version
}
// Returns a number on [0, 1]: the product of all pixel similarities.
float imageProductPixelSimilarity(const cv::Mat& m0, const cv::Mat& m1) const
{
float product_pixel_similarity = 1;
similarityHelper(m0, m1, [&](float s){product_pixel_similarity *= s;});
// similarityHelper(m0, m1, [&](float s){product_pixel_similarity *= sq(s);});
// float min_value = 0.0000000001; // TODO
float min_value = std::numeric_limits<float>::min() * 1024;
return std::max(product_pixel_similarity, min_value);
}
// Applies a given function to the float value from Color::similarity() for
// each pair of corresponding pixels in the two given cv::Mat references.
void similarityHelper(const cv::Mat& m0,
const cv::Mat& m1,
std::function<void(float)> pixel_similarity) const
{
assert((m0.cols == m1.cols) && (m0.rows == m1.rows) &&
(m0.cols > 0) && (m0.rows > 0));
for (int x = 0; x < m0.cols; x++)
{
for (int y = 0; y < m0.rows; y++)
{
float similar = Color::similarity(getCvMatPixel(x, y, m0),
getCvMatPixel(x, y, m1));
assert (between(similar, 0, 1));
pixel_similarity(similar);
}
}
}
// Returns a number on [0, 1] measuring: 1 - pixel_error_square_average.
// TODO July 18, remove squaring to keep things simple for single-level MIP.
float imageAvePixelSimilarity(const cv::Mat& m0, const cv::Mat& m1) const
{
float sum = 0; // sum of per-pixel similarity squared
similarityHelper(m0, m1, [&](float s){ sum += s; });
return sum / (m0.cols * m0.rows);
}
// TODO found this on August 6, when I was about to implement some that
// matches the comment and name, but not the body of the function. Decided
// to overwrite this with the thing I want now.
// // Returns a number on [0, 1]: fraction of pixels with at least "threshold"
// // similarity.
// float imageThresholdSimilarity(const cv::Mat& m0, const cv::Mat& m1) const
// {
// float threshold = 0.8;
// float sum = 0; // sum of per-pixel similarities larger than threshold.
// similarityHelper(m0,
// m1,
// [&](float s)
// {
// sum += remapIntervalClip(s, threshold, 1, 0, 1);
// });
// return sum / (m0.cols * m0.rows);
// }
// // Returns a number on [0, 1]: fraction of pixels with at least "threshold"
// // similarity.
// float imageThresholdSimilarity(const cv::Mat& m0, const cv::Mat& m1) const
// {
// float threshold = 0.9;
// int count = 0; // count per-pixel similarities larger than threshold.
// similarityHelper(m0, m1, [&](float s){ if (s > threshold) count++; });
// return count / float(m0.cols * m0.rows);
// }
// // Returns a number on [0, 1]: fraction of pixels with at least "threshold"
// // similarity.
// float imageThresholdSimilarity(const cv::Mat& m0, const cv::Mat& m1) const
// {
// // float threshold = 0.9;
// float threshold = 0.98;
// // int count = 0; // count per-pixel similarities larger than threshold.
// float sum = 0;
// similarityHelper(m0, m1, [&](float s) {sum += (s > threshold) ? 1 : s / 100;});
// return sum / (m0.cols * m0.rows);
// }
// Returns a number on [0, 1]: fraction of pixels with at least "threshold"
// similarity.
float imageThresholdSimilarity(const cv::Mat& m0, const cv::Mat& m1) const
{
float sum = 0;
similarityHelper(m0, m1, [&](float s){ sum += ((s > 0.95) ?
1 :
((s > 0.90) ?
0.5 :
s / 100));});
return sum / (m0.cols * m0.rows);
}
// Returns a number on [0, 1]: one last try (I really mean it THIS time).
// Realized that imageThresholdSimilarity()--after tweaks-- was very similar
// to taking average of squared per-pixel similarity. This just generalizes
// the square as an expentiation. (Trying 5 on July 19, 2021)
// TODO OK one more tweak, higher power, a bit more at the low end, see:
// https://www.wolframalpha.com/input/?i=plot++y+%3D+%28%28x+*+0.05%29+%2B+%280.95+*+x%5E10%29%29%2C+x%3D+0+to+1%2C+y+%3D+0+to+1
float imageOhDearGodSimilarity(const cv::Mat& m0, const cv::Mat& m1) const
{
float sum = 0; // sum of exponentiated per-pixel similarities.
similarityHelper(m0,
m1,
[&](float s){ sum += ((0.05 * s) +
(0.95 * std::pow(s, 10))); });
return sum / (m0.cols * m0.rows);
}
// TODO July 22, 2021
float imageTotalErrorSquared(const cv::Mat& m0, const cv::Mat& m1) const
{
double sum = 0;
float q = 10;
similarityHelper(m0, m1, [&](float s) { sum += sq(q * (1 - s)); });
float max = sq(q) * m0.cols * m0.rows;
return (max - sum) / max; // TODO fix inline tuning
}
// similar to imageProductPixelSimilarity()
float imageYetAnotherSimilarlity(const cv::Mat& m0, const cv::Mat& m1) const
{
float p = 1;
similarityHelper(m0, m1, [&](float s){p *= remapInterval(s,0,1,0.999,1);});
return p;
}
// TODO July 30 version
float imageJuly30Similarlity(const cv::Mat& m0, const cv::Mat& m1) const
{
// Use an n² downsampled version of the two textures
// const int step = 4; // n = 16
const int step = 6; // n = 64
const int n = std::pow(2, step);
// Build "MIP map like" resolution pyramid for newest evolved image.
std::vector<cv::Mat> newest_pyramid;
makeResolutionPyramid(m0, newest_pyramid);
assert(newest_pyramid.size() == target_pyramid_.size()); // TODO temp
size_t p = newest_pyramid.size() - 1; // Index of 1x1 level in pyramid.
assert(newest_pyramid.at(p - step).cols == n);
return imageProductPixelSimilarity(newest_pyramid.at(p - step),
target_pyramid_.at(p - step));
}
// TODO July 31 version
float imageJuly31Similarlity(const cv::Mat& m0, const cv::Mat& m1) const
{
assert(m0.cols == m1.cols);
assert(m0.rows == m1.rows);
float product_of_similarities = 1;
// const int n = 400; // take n random samples
const int n = 200; // take n random samples
for (int i = 0; i < n; i++)
{
int x = LPRS().random2(0, m0.cols);
int y = LPRS().random2(0, m0.rows);
Color a = getCvMatPixel(x, y, m0);
Color b = getCvMatPixel(x, y, m1);
product_of_similarities *= Color::similarity(a, b);
}
return product_of_similarities;
}
// TODO Aug 2 version
float imageAug2Similarlity(const cv::Mat& m0, const cv::Mat& m1) const
{
float sum = 0;
float max = std::numeric_limits<float>::min();
float min = std::numeric_limits<float>::max();
similarityHelper(m0,
m1,
[&](float s)
{
sum += s;
max = std::max(max, s);
min = std::min(min, s);
});
// float ave = sum / (m0.cols * m0.rows);
// std::cout << " (ave, min, max = " << ave << ", "
// << min << ", " << max << ")" << std::endl;
// return ave * min * max;
std::cout << " (min, max = " << min << ", " << max << ")";
return min * max;
}
// TODO August 3 version
float imageAug3Similarlity(const cv::Mat& m0, const cv::Mat& m1) const
{
assert(m0.cols == m1.cols);
assert(m0.rows == m1.rows);
// Make 32x32 grid of 1024 sample points on size-x-size.
int n = 32;
int size = m0.cols;
std::vector<Vec2> offsets;
jittered_grid_NxN_in_square(n, size, LPRS(), offsets);
float product_of_similarities = 1;
for (auto v : offsets)
{
int x = v.x() + size / 2;
int y = v.y() + size / 2;
assert(between(x, 0, size - 1));
assert(between(y, 0, size - 1));
float similarity = Color::similarity(getCvMatPixel(x, y, m0),
getCvMatPixel(x, y, m1));
// TODO 20210805 try this tweak, probably not significant
// float min = 1 - (1.0 / 128.0);
float min = 1 - (1.0 / 64);
float remap_similarity = remapInterval(similarity, 0, 1, min, 1);
product_of_similarities *= remap_similarity;
}
return product_of_similarities;
}
// Returns a number on [0, 1] measuring minimum-of-all-pixel-similarities.
float imageMinPixelSimilarity(const cv::Mat& m0, const cv::Mat& m1) const
{
int m0w = m0.cols;
int m0h = m0.rows;
int m1w = m1.cols;
int m1h = m1.rows;
assert((m0w == m1w) && (m0h == m1h) && (m0w > 0) && (m0h > 0));
float min_pixel_similarity = std::numeric_limits<float>::max();
for (int x = 0; x < m0w; x++)
{
for (int y = 0; y < m0h; y++)
{
float similar = Color::similarity(getCvMatPixel(x, y, m0),
getCvMatPixel(x, y, m1));
assert (between(similar, 0, 1));
if (min_pixel_similarity > similar)
{
min_pixel_similarity = similar;
}
}
}
return min_pixel_similarity;
}
// // Written on Aug 20 2021, started from imageJuly30Similarlity()
// // TODO note that this incorrectly depends on m1 being target_image_.
// float imageCoarseToFineSimilarity(const cv::Mat& m0, const cv::Mat& m1) const
// {
// // Use (up to) "steps" levels of the MIP maps
// const int steps = 6; // n = 64
//
// // level side area
// // i 2^i (2^i)^2 0.99^area
// // - --- ------- -----------------
// // 0 1 1 0.99
// // 1 2 4 0.96059601
// // 2 4 16 0.851457771094876
// // 3 8 64 0.525596487525562
// // 4 16 256 0.076314983906594
// // 5 32 1024 0.000033918705402
//
// // Build "MIP map like" resolution pyramid for newest evolved image.
// std::vector<cv::Mat> newest_pyramid;
// makeResolutionPyramid(m0, newest_pyramid);
// assert(newest_pyramid.size() == target_pyramid_.size()); // TODO temp
// size_t p = newest_pyramid.size() - 1; // Index of 1x1 level in pyramid.
// assert(newest_pyramid.at(p - steps).cols == std::pow(2, steps));
//
// // TODO maybe this should be a member function of its own, but for now
// // the imageProductPixelSimilarity() name is already taken for a since
// // modified ad hoc version.
// //
// // Returns a number on [0, 1]: the product of all pixel similarities.
// auto product_of_pixel_similarities =
// [&]
// (const cv::Mat& m0, const cv::Mat& m1)
// {
// float product_pixel_similarity = 1;
// // similarityHelper(m0,m1,[&](float s){product_pixel_similarity *= s;});
// similarityHelper(m0,
// m1,
// [&](float s){ product_pixel_similarity *= s; });
// return product_pixel_similarity;
// };
//
// // Traverse levels of the two MIP maps in parallel, starting at the 1x1
// // "coarse" end, compute score for each level based on product of all
// // pixel similarlties. Return the average (weighted sum) of each level
// // score as the final fitness for m0.
// //
// // TODO another way to structure this to enforce coarse-to-fine is to
// // stop after any level where the score is too low (eg less than 0.8),
// // so only the 1x1 level is considered until that is 80% similar, then
// // we move on to 2x2...
// //
// float sum_of_per_level_scores = 0;
// for (int i = 0; i < steps; i++)
// {
// cv::Mat a = newest_pyramid.at(p - i);
// cv::Mat b = target_pyramid_.at(p - i);
// float level_score = product_of_pixel_similarities(a, b);
// sum_of_per_level_scores += level_score;
//
// std::cout << " ";
// std::cout << i << " score=" << level_score;
// std::cout << " total=" << sum_of_per_level_scores;
// std::cout << " normed=" << sum_of_per_level_scores / steps;
// std::cout << std::endl;
//
// // float min_level_score_to_continue = 0.3;
// float min_level_score_to_continue = 0.05;
// if (level_score < min_level_score_to_continue) break;
// }
// return sum_of_per_level_scores / steps;
// }
// // TODO note that this incorrectly depends on m1 being target_image_.
// float imageCoarseToFineSimilarity(const cv::Mat& m0, const cv::Mat& m1) const
// {
// // Use (up to) "steps" levels of the MIP maps
// const int steps = 6; // n = 64
//
// // Build "MIP map like" resolution pyramid for newest evolved image.
// std::vector<cv::Mat> newest_pyramid;
// makeResolutionPyramid(m0, newest_pyramid);
// assert(newest_pyramid.size() == target_pyramid_.size()); // TODO temp
// size_t p = newest_pyramid.size() - 1; // Index of 1x1 level in pyramid.
// assert(newest_pyramid.at(p - steps).cols == std::pow(2, steps));
//
// // TODO maybe this should be a member function of its own, but for now
// // the imageProductPixelSimilarity() name is already taken for a since
// // modified ad hoc version.
// //
// // Returns a number on [0, 1]: the product of all pixel similarities.
// // auto product_of_pixel_similarities =
// // [&]
// // (const cv::Mat& m0, const cv::Mat& m1)
// // {
// // float product_pixel_similarity = 1;
// // similarityHelper(m0,
// // m1,
// // [&](float s){ product_pixel_similarity *= s; });
// // return product_pixel_similarity;
// // };
// auto product_of_pixel_similarities =
// [&](const cv::Mat& m0, const cv::Mat& m1)
// {
// float product_pixel_similarity = 1;
// // similarityHelper(m0,
// // m1,
// // [&](float s){ product_pixel_similarity *= s; });
//
// assert((m0.cols==m0.rows)&&(m0.cols==m1.cols)&&(m0.cols==m1.rows));
// int area = m0.cols * m0.rows;
// float min = 1 - (1.0 / std::max(1.0, area / 8.0));
// auto pf = [&](float s)
// {
// product_pixel_similarity *= remapInterval(s, 0, 1, min, 1);
// };
// similarityHelper(m0, m1, pf);
//
// return product_pixel_similarity;
// };
//
// // Traverse levels of the two MIP maps in parallel, starting at the 1x1
// // "coarse" end, compute score for each level based on product of all
// // pixel similarlties. Return the average (weighted sum) of each level
// // score as the final fitness for m0.
// //
// // TODO another way to structure this to enforce coarse-to-fine is to
// // stop after any level where the score is too low (eg less than 0.8),
// // so only the 1x1 level is considered until that is 80% similar, then
// // we move on to 2x2...
// //
// float sum_of_per_level_scores = 0;
// for (int i = 0; i < steps; i++)
// {
// cv::Mat a = newest_pyramid.at(p - i);
// cv::Mat b = target_pyramid_.at(p - i);
// float level_score = product_of_pixel_similarities(a, b);
// sum_of_per_level_scores += level_score;
//