-
Notifications
You must be signed in to change notification settings - Fork 1
/
imgnnet.cpp
executable file
·3871 lines (3566 loc) · 108 KB
/
imgnnet.cpp
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
/***
imgnnet.cpp
The ImgNNet class, which can predict pixels in a bitmap based on nearby pixels.
Can be used as a "magic eraser", an inpainter/superresolution network, as a fun image
filter, a despeckler/noise reducer, to extend images, for machine vision, image
compression, colorization, etc.
Copyright (c) 2022 Chris Street.
***/
#include "libcodehappy.h"
#include <thread>
TrainData::TrainData() {
citer = 0;
retry = 0;
err_in = 0.;
err_out = 0.;
lrate1 = 0.;
lrate = 0.;
lrate_eff = 0.;
fname_idx = STRINDEX_INVALID;
flip = false;
img_w = 0;
img_h = 0;
}
void TrainData::out_to_ramfile(RamFile* rf, u32 version) const {
/* Version: 1 has img_w/img_h, 0 does not. */
rf->putu32(citer);
rf->putu32(retry);
rf->putdouble(err_in);
rf->putdouble(err_out);
rf->putdouble(lrate1);
rf->putdouble(lrate);
rf->putdouble(lrate_eff);
rf->putbool(flip);
rf->putu32(fname_idx);
tim_start.out_ramfile(rf);
tim_end.out_ramfile(rf);
if (version > 0) {
rf->putu32(img_w);
rf->putu32(img_h);
}
}
void TrainData::dump(StringTable& st, VerboseStream& vs) const {
if (STRINDEX_INVALID == fname_idx) {
vs << "Training data [Filename invalid]\n";
} else {
vs << "Training data [" << st.string(fname_idx) << "]\n";
}
vs << "\tTraining began: " << fmt_datetime_shell_long(&tim_start) << "\n";
vs << "\tTraining ended: " << fmt_datetime_shell_long(&tim_end) << "\n";
vs << "\tError fn in : " << err_in << "\n";
vs << "\tError fn out : " << err_out << "\n";
vs << "\tLearn rate in : " << lrate1 << "\n";
vs << "\tLearn rate out: " << lrate << "\n";
vs << "\tLearn rate eff: ";
if (lrate_eff <= 0.)
vs << "n/a\n";
else
vs << lrate_eff << "\n";
vs << "\tFlip : " << flip << "\n";
if (img_w * img_h > 0)
vs << "\tImage dimen. : " << img_w << " x " << img_h << "\n";
}
void TrainData::read_from_ramfile(RamFile* rf, u32 version) {
/* Version: 1 has img_w/img_h, 0 does not. */
citer = rf->getu32();
retry = rf->getu32();
err_in = rf->getdouble();
err_out = rf->getdouble();
lrate1 = rf->getdouble();
lrate = rf->getdouble();
lrate_eff = rf->getdouble();
fname_idx = STRINDEX_INVALID;
flip = rf->getbool();
fname_idx = rf->getu32();
tim_start.in_ramfile(rf);
tim_end.in_ramfile(rf);
if (version > 0) {
img_w = rf->getu32();
img_h = rf->getu32();
}
}
ValidationSetData::ValidationSetData() {
clear();
}
void ValidationSetData::clear() {
nf = 0;
fs.clear();
off.clear();
inp.clear();
out.clear();
}
void ValidationSetData::in_from_ramfile(RamFile* rf) {
u32 e;
clear();
nf = rf->getu32();
if (0 == nf) {
return;
}
rad = rf->getu32();
for (e = 0; e < nf; ++e) {
fs.push_back(rf->getu32());
off.push_back(rf->getu32());
}
rf->getsp(inp);
rf->getsp(out);
}
void ValidationSetData::out_to_ramfile(RamFile* rf) const {
u32 e;
rf->putu32(nf);
if (0 == nf) {
return;
}
rf->putu32(rad);
for (e = 0; e < nf; ++e) {
rf->putu32(fs[e]);
rf->putu32(off[e]);
}
rf->putsp(inp);
rf->putsp(out);
}
void ValidationSetData::dump(StringTable& st, VerboseStream& vs) const {
vs << "Validation set contains " << nf << " files.\n";
for (u32 e = 0; e < nf; ++e) {
if (STRINDEX_INVALID == fs[e]) {
vs << "Validation set data [Filename invalid]\n";
} else {
vs << "Validation set data [" << st.string(fs[e]) << "]\n";
}
vs << "\tOffset of data : " << off[e] << "\n";
}
vs << "Size of input data (bytes): " << inp.length() << "\n";
vs << "Size of output data (bytes): " << out.length() << "\n";
}
ImgBrush::ImgBrush(u32 r) {
u32 no; /* unused */
ImgNNet::inout_from_radius(r, 0, ni, no);
double vr = RandDouble(-0.1, 0.1), vg = RandDouble(-0.1, 0.1), vb = RandDouble(-0.1, 0.1);
in = new double [ni];
velocity_color = new double [ni];
in[0] = RandDouble(0., 1.);
in[1] = RandDouble(0., 1.);
in[2] = RandDouble(0., 1.);
velocity_color[0] = vr;
velocity_color[1] = vg;
velocity_color[2] = vb;
for (u32 e = 3; e < ni; e += 3) {
velocity_color[e] = velocity_color[e - 3] + RandDouble(-0.002, 0.002);
velocity_color[e + 1] = velocity_color[e - 2] + RandDouble(-0.002, 0.002);
velocity_color[e + 2] = velocity_color[e - 1] + RandDouble(-0.002, 0.002);
in[e] = in[e - 3] + RandDouble(-0.04, 0.04);
in[e + 1] = in[e - 2] + RandDouble(-0.04, 0.04);
in[e + 2] = in[e - 1] + RandDouble(-0.04, 0.04);
in[e] = CLAMP(in[e], 0., 1.);
in[e + 1] = CLAMP(in[e + 1], 0., 1.);
in[e + 2] = CLAMP(in[e + 2], 0., 1.);
}
do {
velocity_brush[0] = RandDouble(-4., 4.);
} while (std::abs(velocity_brush[0]) < 0.5);
do {
velocity_brush[1] = RandDouble(-4., 4.);
} while (std::abs(velocity_brush[1]) < 0.5);
x = 0.;
y = 0.;
rad = r;
}
void ImgBrush::brush_update(u32 w, u32 h) {
x += velocity_brush[0];
if (x < 0.) {
x = 0;
velocity_brush[0] = -velocity_brush[0];
} else if (x >= double(w) - 0.5) {
x = (double)(w - 1);
velocity_brush[0] = -velocity_brush[0];
}
y += velocity_brush[1];
if (y < 0.) {
y = 0;
velocity_brush[1] = -velocity_brush[1];
} else if (y >= double(h) - 0.5) {
y = (double)(h - 1);
velocity_brush[1] = -velocity_brush[1];
}
for (u32 e = 0; e < ni; ++e) {
in[e] += velocity_color[e];
if (in[e] > 1.0) {
velocity_color[e] = -velocity_color[e];
in[e] = 1.0 - (in[e] - 1.0);
} else if (in[e] < 0.0) {
velocity_color[e] = -velocity_color[e];
in[e] = -in[e];
}
}
}
void ImgBrush::set_from_predictions(PredictAccum& pa) {
double* disc = in;
int iy = (int)floor(y + 0.5), ix = (int)floor(x + 0.5);
int xx, yy;
for (yy = iy - ((int)rad); yy <= iy + ((int)rad); ++yy) {
for (xx = ix - ((int)rad); xx <= ix + ((int)rad); ++xx) {
int ds = (ix - xx) * (ix - xx) + (iy - yy) * (iy - yy);
if (ds <= (int)(rad * rad)) {
u32 np = pa.get_num_predictions_lock(xx, yy);
if (np > 0) {
RGBOut ro;
pa.get_avg_prediction_lock(xx, yy, ro);
*(disc++) = ro.r;
*(disc++) = ro.g;
*(disc++) = ro.b;
} else {
disc += 3;
}
}
}
}
}
ImgBrush::~ImgBrush() {
if (in != nullptr)
delete in;
if (velocity_color != nullptr)
delete velocity_color;
}
u32 color_distance(RGBColor c1, RGBColor c2) {
int ret = 0;
ret += std::abs((int)RGB_RED(c1) - (int)RGB_RED(c2));
ret += std::abs((int)RGB_GREEN(c1) - (int)RGB_GREEN(c2));
ret += std::abs((int)RGB_BLUE(c1) - (int)RGB_BLUE(c2));
return (u32)ret;
}
double channel_intensity(SBitmap* bmp, u32 ch, int x, int y) {
u32 v = 0;
switch (ch) {
case CHANNEL_RED:
v = bmp->get_red(x, y);
break;
case CHANNEL_GREEN:
v = bmp->get_green(x, y);
break;
case CHANNEL_BLUE:
v = bmp->get_blue(x, y);
break;
case CHANNEL_ALPHA:
v = bmp->get_alpha(x, y);
break;
}
return double(v) / 255.0;
}
double gray_intensity(SBitmap* bmp, int x, int y) {
double intsy;
intsy = channel_intensity(bmp, CHANNEL_RED, x, y);
intsy += channel_intensity(bmp, CHANNEL_GREEN, x, y);
intsy += channel_intensity(bmp, CHANNEL_BLUE, x, y);
intsy /= 3.0;
return intsy;
}
bool file_is_text(const char* pathname) {
unsigned char buf[128];
if (!FileExists(pathname))
return false;
u32 fl = filelen(pathname);
if (fl == 0)
return false;
/* Check the first 128 bytes of the file; if there aren't any strange (non-whitespace) control characters, call it good. */
fl = std::min((unsigned long)fl, 128UL);
FILE* f = fopen(pathname, "rb");
fread(buf, 1, fl, f);
fclose(f);
for (u32 i = 0; i < fl; ++i) {
if (buf[i] < ' ' && !isspace(buf[i]))
return false;
}
return true;
}
const char* timepr(u64 mills) {
static char st[4][32];
static u32 idx = 0;
char* ret;
int min = mills / 60000;
int sec = mills / 1000;
int mil = int(mills - sec * 1000);
sec -= min * 60;
ret = st[idx++];
if (idx > 3)
idx = 0;
sprintf(ret, "%02d:%02d.%03d", min, sec, mil);
return ret;
}
static genann* gn_read_from_file(const char* fname) {
FILE* f = fopen(fname, "r");
genann* ret = genann_read(f);
fclose(f);
return ret;
}
static void gn_out_to_file(genann* nnet, const char* fname) {
FILE* f = fopen(fname, "w");
genann_write(nnet, f);
fclose(f);
}
/*** genann and kann ramfile I/O ***/
static genann* gn_read_from_ramfile(RamFile* rf) {
/* Perform a genann read from a RamFile (which can be compressed.) */
i32 inputs, hidden_layers, hidden, outputs;
inputs = rf->get32();
hidden_layers = rf->get32();
hidden = rf->get32();
outputs = rf->get32();
genann* ann = genann_init(inputs, hidden_layers, hidden, outputs);
NOT_NULL_OR_RETURN(ann, ann);
for (int i = 0; i < ann->total_weights; ++i) {
ann->weight[i] = rf->getdouble();
}
return ann;
}
static void gn_out_to_ramfile(RamFile* rf, genann* nnet) {
/* Perform a genann write to a RamFile (which can and will be compressed.) */
rf->put32(nnet->inputs);
rf->put32(nnet->hidden_layers);
rf->put32(nnet->hidden);
rf->put32(nnet->outputs);
for (int i = 0; i < nnet->total_weights; ++i) {
rf->putdouble(nnet->weight[i]);
}
}
static void kad1_out_to_ramfile(RamFile* rf, const kad_node_t* p) {
rf->put32(p->ext_label);
rf->putu32(p->ext_flag);
rf->putc(p->flag);
rf->put32(p->n_child);
if (p->n_child) {
i32 j, pre = p->pre? p->pre->tmp : -1;
rf->putu16(p->op);
for (j = 0; j < p->n_child; ++j)
rf->put32(p->child[j]->tmp);
rf->put32(pre);
rf->put32(p->ptr_size);
if (p->ptr_size > 0 && p->ptr)
rf->putmem((const char*)(p->ptr), p->ptr_size);
} else {
rf->putc(p->n_d);
for (int e = 0; e < p->n_d; ++e)
rf->put32(p->d[e]);
}
}
static void kad_out_to_ramfile(RamFile* rf, int n_node, kad_node_t **node) {
i32 i, k = n_node;
rf->put32(k);
for (i = 0; i < n_node; ++i)
node[i]->tmp = i;
for (i = 0; i < n_node; ++i)
kad1_out_to_ramfile(rf, node[i]);
for (i = 0; i < n_node; ++i)
node[i]->tmp = 0;
}
static void kann_out_to_ramfile(RamFile* rf, kann_t* nnet) {
kann_set_batch_size(nnet, 1);
kad_out_to_ramfile(rf, nnet->n, nnet->v);
rf->putmem((const char*)nnet->x, sizeof(float) * kann_size_var(nnet));
rf->putmem((const char*)nnet->c, sizeof(float) * kann_size_const(nnet));
}
static kad_node_t *kad1_from_ramfile(RamFile* rf, kad_node_t **node) {
kad_node_t *p;
p = (kad_node_t*)calloc(1, sizeof(kad_node_t));
p->ext_label = rf->get32();
p->ext_flag = rf->getu32();
p->flag = (u8)rf->getc();
p->n_child = rf->get32();
if (p->n_child) {
int32_t j, k;
p->child = (kad_node_t**)calloc(p->n_child, sizeof(kad_node_t*));
p->op = rf->getu16();
for (j = 0; j < p->n_child; ++j) {
k = rf->get32();
p->child[j] = node ? node[k] : 0;
}
k = rf->get32();
if (k >= 0)
p->pre = node[k];
p->ptr_size = rf->get32();
if (p->ptr_size > 0) {
p->ptr = malloc(p->ptr_size);
rf->getmem((u8*)p->ptr, p->ptr_size);
}
} else {
p->n_d = (u8)rf->getc();
if (p->n_d) {
for (int e = 0; e < p->n_d; ++e)
p->d[e] = rf->get32();
}
}
return p;
}
static kad_node_t **kad_read_from_ramfile(RamFile* rf, int *_n_node) {
i32 i, n_node;
kad_node_t **node;
n_node = rf->get32();
node = (kad_node_t**)malloc(n_node * sizeof(kad_node_t*));
NOT_NULL_OR_RETURN(node, node);
for (i = 0; i < n_node; ++i) {
kad_node_t *p;
p = node[i] = kad1_from_ramfile(rf, node);
if (p->n_child) {
kad_op_list[p->op](p, KAD_ALLOC);
kad_op_list[p->op](p, KAD_SYNC_DIM);
}
}
*_n_node = n_node;
kad_mark_back(n_node, node);
return node;
}
static kann_t *kann_read_from_ramfile(RamFile* rf) {
kann_t *ret;
int n_var, n_const;
ret = (kann_t*)calloc(1, sizeof(kann_t));
NOT_NULL_OR_RETURN(ret, ret);
ret->v = kad_read_from_ramfile(rf, &ret->n);
n_var = kad_size_var(ret->n, ret->v);
n_const = kad_size_const(ret->n, ret->v);
ret->x = (float*)malloc(n_var * sizeof(float));
ret->g = (float*)calloc(n_var, sizeof(float));
ret->c = (float*)malloc(n_const * sizeof(float));
rf->getmem((u8*)ret->x, sizeof(float) * n_var);
rf->getmem((u8*)ret->c, sizeof(float) * n_const);
kad_ext_sync(ret->n, ret->v, ret->x, ret->g, ret->c);
return ret;
}
const u32 FILENAME_INVALID = 0xfffffffful;
const u32 NNET_FORMAT_GENANN = 0;
const u32 NNET_FORMAT_KANN = 1;
static bool nearest_neighbor(SBitmap* bin, SBitmap* berase, int x, int y, RGBColor& c_out) {
RGBColor n[8], avg;
u32 cn = 0, bs, dm;
int dx, dy;
int r = 0, g = 0, b = 0;
for (dy = -1; dy <= 1; ++dy) {
for (dx = -1; dx <= 1; ++dx) {
if (dx == 0 && dy == 0)
continue;
if (!pixel_ok(berase, x + dx, y + dy))
continue;
if (berase->get_red(x + dx, y + dy) != 0)
continue;
n[cn] = bin->get_pixel(x + dx, y + dy);
r += RGB_RED(n[cn]);
g += RGB_GREEN(n[cn]);
b += RGB_BLUE(n[cn]);
++cn;
}
}
if (0 == cn)
return false;
c_out = n[0];
if (1 == cn)
return true;
r /= cn;
g /= cn;
b /= cn;
avg = MAKE_RGB(r, g, b);
bs = color_distance(c_out, avg);
for (dx = 1; dx < cn; ++dx) {
dm = color_distance(n[dx], avg);
if (dm < bs) {
bs = dm;
c_out = n[dx];
}
}
return true;
}
/* Compare against replacing missing pixels with the best average pixel (or last valid, that failing). */
static double error_bmp_best_neighbor_pixel(SBitmap* o, SBitmap* e) {
RGBColor last = RGB_GRAY(127);
u64 ret = 0;
u32 c = 0;
for (int y = 0; y < o->height(); ++y) {
for (int x = 0; x < o->width(); ++x) {
RGBColor c1, cn;
c1 = o->get_pixel(x, y);
if (e->get_red(x, y) > 0) {
if (nearest_neighbor(o, e, x, y, cn))
ret += color_distance(c1, cn);
else
ret += color_distance(c1, last);
c += 3;
} else {
last = c1;
}
}
}
return double(ret) / double(c);
}
/* Compare against replacing missing pixels with the last valid pixel. */
static double error_bmp_last_pixel(SBitmap* o, SBitmap* e) {
RGBColor last = RGB_GRAY(127);
u64 ret = 0;
u32 c = 0;
for (int y = 0; y < o->height(); ++y) {
for (int x = 0; x < o->width(); ++x) {
RGBColor c1;
c1 = o->get_pixel(x, y);
if (e->get_red(x, y) > 0) {
ret += color_distance(c1, last);
c += 3;
} else {
last = c1;
}
}
}
return double(ret) / double(c);
}
/* Compare against the average color of erased pixels. */
static double error_bmp_avg(SBitmap* o, SBitmap* e) {
u64 ret = 0;
u64 r = 0, g = 0, b = 0;
u32 ce = 0;
for (int y = 0; y < o->height(); ++y) {
for (int x = 0; x < o->width(); ++x) {
RGBColor c1;
c1 = o->get_pixel(x, y);
if (e->get_red(x, y) > 0) {
++ce;
r += RGB_RED(c1);
g += RGB_GREEN(c1);
b += RGB_BLUE(c1);
}
}
}
if (0 == ce)
return 0ULL;
r /= ce;
g /= ce;
b /= ce;
RGBColor ca = RGB_NO_CHECK(r, g, b);
for (int y = 0; y < o->height(); ++y) {
for (int x = 0; x < o->width(); ++x) {
if (e->get_red(x, y) > 0) {
RGBColor c1;
c1 = o->get_pixel(x, y);
ret += color_distance(c1, ca);
}
}
}
return double(ret) / double(ce * 3);
}
static double error_bmp(SBitmap* b1, SBitmap* b2, SBitmap* e) {
u64 ret = 0;
u32 ce = 0;
for (int y = 0; y < b1->height(); ++y) {
for (int x = 0; x < b1->width(); ++x) {
RGBColor c1, c2;
if (e->get_red(x, y) > 0)
ce += 3;
c1 = b1->get_pixel(x, y);
c2 = b2->get_pixel(x, y);
ret += color_distance(c1, c2);
}
}
return double(ret) / double(ce);
}
RGBOut RGBOut::operator+=(const RGBOut& rhs) {
r += rhs.r;
g += rhs.g;
b += rhs.b;
return *this;
}
RGBOut RGBOut::operator+(const RGBOut& rhs) {
RGBOut ret;
ret.r = r + rhs.r;
ret.g = g + rhs.g;
ret.b = b + rhs.b;
return ret;
}
RGBOut RGBOut::operator*(double rhs) {
RGBOut ret;
ret.r = r * rhs;
ret.g = g * rhs;
ret.b = b * rhs;
return ret;
}
/*** Operator implementations for the VerboseStream. ***/
#define VSOP(__TYPE__) \
VerboseStream& VerboseStream::operator<<(const __TYPE__ i) { \
if (is_quiet()) return *this; \
*o << i; \
return *this; \
}
VSOP(std::string&);
VSOP(char*);
VSOP(int);
VSOP(unsigned int);
VSOP(int64_t);
VSOP(uint64_t);
VSOP(float);
VSOP(double);
#ifdef __GNUC__
VSOP(long double);
#endif
VSOP(unsigned char);
VSOP(signed char);
VSOP(int16_t);
VSOP(uint16_t);
VSOP(void * const);
#undef VSOP
VerboseStream& VerboseStream::operator<<(const bool b) {
if (is_quiet())
return *this;
*o << (b ? "true" : "false");
return *this;
}
void PredictAccum::add_prediction(int x, int y, RGBOut& predict) {
auto pr = std::make_pair(x, y);
if (predictions.find(pr) == predictions.end()) {
predictions[pr] = std::make_pair(predict, 1L);
return;
}
auto p = predictions[pr];
p.first += predict;
p.second++;
predictions[pr] = p;
}
void PredictAccum::add_prediction(int x, int y, RGBOut& predict, int weight) {
auto pr = std::make_pair(x, y);
if (predictions.find(pr) == predictions.end()) {
predictions[pr] = std::make_pair(predict, weight);
return;
}
auto p = predictions[pr];
p.first += (predict * double(weight));
p.second += weight;
if (p.second > (1 << 26)) {
p.first = p.first * (1.0 / 1024.0);
p.second /= 1024;
}
predictions[pr] = p;
}
void PredictAccum::get_avg_prediction(int x, int y, RGBOut& p) {
u32 c = get_num_predictions(x, y);
if (0 == c) {
p.r = 0.;
p.g = 0.;
p.b = 0.;
return;
}
get_total_prediction(x, y, p);
p.r /= (double)c;
p.g /= (double)c;
p.b /= (double)c;
p.r = CLAMP(p.r, 0.0, 1.0);
p.g = CLAMP(p.g, 0.0, 1.0);
p.b = CLAMP(p.b, 0.0, 1.0);
}
void PredictAccum::get_total_prediction(int x, int y, RGBOut& p) {
auto pr = std::make_pair(x, y);
if (predictions.find(pr) == predictions.end()) {
p.r = 0.;
p.g = 0.;
p.b = 0.;
return;
}
p = predictions[pr].first;
return;
}
u32 PredictAccum::get_num_predictions(int x, int y) {
auto pr = std::make_pair(x, y);
if (predictions.find(pr) == predictions.end())
return 0;
return predictions[pr].second;
}
void PredictAccum::reset() {
predictions.clear();
}
void PredictAccum::fold_in(PredictAccum& pa) {
for (auto& e : pa.predictions) {
auto& pt = e.first;
auto& pred_pr = e.second;
if (predictions.find(pt) == predictions.end()) {
predictions[pt] = pred_pr;
} else {
auto p = predictions[pt];
p.first += pred_pr.first;
p.second += pred_pr.second;
predictions[pt] = p;
}
}
}
/* Initialize an empty ImgNNet. */
ImgNNet::ImgNNet() {
vs = VerboseStream(true);
set_default_parameters();
nnet = nullptr;
nnet_best = nullptr;
in = nullptr;
out = nullptr;
pw = nullptr;
}
/* Initialize a fresh image neural network with the specified radius. */
ImgNNet::ImgNNet(bool verbose, u32 radius, u32 hidden_layers) {
vs = VerboseStream(verbose);
set_default_parameters();
ImgNNet::inout_from_radius(radius, 0, ni, no);
d = radius;
nnet = nnet_init(ni, hidden_layers, neurons, no);
nnet_best = nnet;
in = new double [ni];
out = new double [no];
fin = new float [ni];
fout = new float [no];
pw = nullptr;
vs << "Inputs: " << ni << ", outputs: " << no << ", hidden layers: " << hidden_layers << "\n";
}
/* As above, but allows setting of neurons as well. */
ImgNNet::ImgNNet(bool verbose, u32 radius, u32 nneurons, u32 hidden_layers) {
vs = VerboseStream(verbose);
set_default_parameters();
neurons = nneurons;
ImgNNet::inout_from_radius(radius, 0, ni, no);
d = radius;
nnet = nnet_init(ni, hidden_layers, neurons, no);
nnet_best = nnet;
in = new double [ni];
out = new double [no];
fin = new float [ni];
fout = new float [no];
pw = nullptr;
vs << "Inputs: " << ni << ", outputs: " << no << ", hidden layers: " << hidden_layers << "\n";
}
/* As above, but allows setting the library used (genann or kann) and identity training flag. */
ImgNNet::ImgNNet(bool verbose, u32 radius, u32 nneurons, u32 hidden_layers, bool idtrain, u32 library) {
vs = VerboseStream(verbose);
set_default_parameters();
neurons = nneurons;
ImgNNet::inout_from_radius(radius, 0, ni, no);
d = radius;
if (library > NNET_FORMAT_KANN) {
vs << "Error: maximum library format permissable is " << NNET_FORMAT_KANN << ".\n";
return;
}
nnet_ver = library;
identity = idtrain;
nnet = nnet_init(ni, hidden_layers, neurons, no);
nnet_best = nnet;
in = new double [ni];
out = new double [no];
fin = new float [ni];
fout = new float [no];
pw = nullptr;
vs << "Inputs: " << ni << ", outputs: " << no << ", hidden layers: " << hidden_layers << "\n";
}
/* Create a colorization neural network. */
ImgNNet::ImgNNet(bool verbose, u32 rad, u32 r2, u32 nneurons, u32 hidden_layers, bool idtrain, u32 library) {
vs = VerboseStream(verbose);
set_default_parameters();
colorize = true;
neurons = nneurons;
assert(r2 > 0 && r2 <= rad);
ImgNNet::inout_from_radius(rad, r2, ni, no);
d = rad;
d2 = r2;
if (library > NNET_FORMAT_KANN) {
vs << "Error: maximum library format permissable is " << NNET_FORMAT_KANN << ".\n";
return;
}
nnet_ver = library;
identity = idtrain;
nnet = nnet_init(ni, hidden_layers, neurons, no);
nnet_best = nnet;
in = new double [ni];
out = new double [no];
fin = new float [ni];
fout = new float [no];
pw = nullptr;
vs << "Inputs: " << ni << ", outputs: " << no << ", hidden layers: " << hidden_layers << "\n";
}
/* Load an existing neural network from file. */
ImgNNet::ImgNNet(bool verbose, const char* pathname) {
vs = VerboseStream(verbose);
pw = nullptr;
read_from_file(pathname);
}
ImgNNet::ImgNNet(bool verbose, const char* pathname, u32 radius, u32 hidden_layers) {
vs = VerboseStream(verbose);
vs << "Loading the neural network...\n";
pw = nullptr;
if (FileExists(pathname)) {
read_from_file(pathname);
} else {
vs << "(Neural net doesn't exist, creating.)\n";
set_default_parameters();
ImgNNet::inout_from_radius(radius, 0, ni, no);
d = radius;
nnet = nnet_init(ni, hidden_layers, neurons, no);
nnet_best = nnet;
pw = nullptr;
in = new double [ni];
out = new double [no];
fin = new float [ni];
fout = new float [no];
vs << "Inputs: " << ni << ", outputs: " << no << ", hidden layers: " << hidden_layers << "\n";
}
}
const u32 BATCH_TRAIN_SIZE = 1000;
ImgNNet::~ImgNNet() {
if (!is_null(nnet))
nnet_free(nnet);
if (!is_null(nnet_best) && nnet_best != nnet)
nnet_free(nnet_best);
if (out != nullptr)
delete [] out;
if (in != nullptr)
delete [] in;
if (batch_in != nullptr) {
for (u32 e = 0; e < BATCH_TRAIN_SIZE; ++e) {
delete [] batch_in[e];
delete [] batch_out[e];
}
delete [] batch_in;
delete [] batch_out;
}
}
/* Save the neural network to file. */
void ImgNNet::out_to_file(const char* pathname) {
#ifdef USE_GENANN_SAVE_ONLY
gn_out_to_file(nnet_best, pathname);
#else
out_to_ramfile(pathname);
#endif
}
/* Outputs the neural network to disk, if there's a filename. */
void ImgNNet::update_on_disk() {
if (nn_fname.empty()) {
vs << "Neural net filename empty, not updating on disk.\n";
return;
}
out_to_file(nn_fname.c_str());
vs << "Neural network update successful.\n";
}
const i32 IMGNNET_MAGIC = 10891234;
const u32 VERSION_MIN = 1000000;
void ImgNNet::out_to_ramfile(const char* pathname) {
if (FileExists(pathname)) {
remove(pathname);
}
RamFile rf;
if (rf.open(pathname, RAMFILE_COMPRESS | RAMFILE_CREATE_IF_MISSING)) {
vs << "Unable to open " << pathname << "!\n";
return;
}
rf.put32(IMGNNET_MAGIC);
rf.putu32(d);
rf.putu32(ni);
rf.putu32(no);
rf.putu32(neurons);
rf.put32((i32)space);
rf.putdouble(lrate);
rf.putbool(use_neighbors);
rf.putu32(max_neighbors);
rf.putu32(max_neighbor_pass);
rf.putbool(vs.is_verbose());
rf.putbool(flip);
rf.putu32(max_size);
rf.putu32(max_iter);
rf.putu32(max_retry);
rf.putu32(mp);
rf.putbool(out_erased);
rf.putbool(out_neighb);
// *** We used to just call gn_out_to_ramfile(), but now we output an entire version data block to support
// more formats for both neural nets and TrainData, as well as colorization neural networks. ***
rf.putu32(nnet_ver + VERSION_MIN);
nnet_out_to_ramfile(&rf);
rf.putbool(colorize);
rf.putbool(identity);
if (colorize)
rf.putc((u8)d2);
for (int e = 0; e < 64; ++e)
rf.putc(0);
// *** Version block ends. ***
st.persist(&rf);
traindata_to_ramfile(&rf);
vsd.out_to_ramfile(&rf);
// This final u32 is essentially a version number, for easier format extensibility.
rf.putu32(0);
rf.close();
}
/* Load the neural network from file. */
void ImgNNet::read_from_file(const char* pathname) {
if (file_is_text(pathname))
read_from_genann_file(pathname);
else
read_ramfile_format(pathname);
}
void ImgNNet::read_from_genann_file(const char* pathname) {
nnet = gn_read_from_file(pathname);
no = ((genann *)nnet)->outputs;
ni = ((genann *)nnet)->inputs;
u32 x = 0;
radius_from_inout(this->d, x, false);
if (0 == d) {
vs << "Unknown neural network structure.\n";
return;
} else {
vs << "Loaded neural network with window radius " << d << ", " << ni << " inputs, " << no << " outputs.\n";
}
nnet_best = nnet;
in = new double [ni];
out = new double [no];
fin = new float [ni];
fout = new float [no];
/* Other parameters to defaults. */
set_default_parameters();
nn_fname = pathname;
vsd.rad = d;
}
void ImgNNet::read_ramfile_format(const char* pathname) {
RamFile rf;
u32 i, o;
if (rf.open(pathname, RAMFILE_READONLY)) {
vs << "Unable to open " << pathname << "!\n";
return;
}