forked from AlexeyAB/darknet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdetector.c
2031 lines (1779 loc) · 74.5 KB
/
detector.c
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
#include <stdlib.h>
#include "darknet.h"
#include "network.h"
#include "region_layer.h"
#include "cost_layer.h"
#include "utils.h"
#include "parser.h"
#include "box.h"
#include "demo.h"
#include "option_list.h"
#ifndef __COMPAR_FN_T
#define __COMPAR_FN_T
typedef int (*__compar_fn_t)(const void*, const void*);
#ifdef __USE_GNU
typedef __compar_fn_t comparison_fn_t;
#endif
#endif
#include "http_stream.h"
int check_mistakes = 0;
static int coco_ids[] = { 1,2,3,4,5,6,7,8,9,10,11,13,14,15,16,17,18,19,20,21,22,23,24,25,27,28,31,32,33,34,35,36,37,38,39,40,41,42,43,44,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,67,70,72,73,74,75,76,77,78,79,80,81,82,84,85,86,87,88,89,90 };
void train_detector(char *datacfg, char *cfgfile, char *weightfile, int *gpus, int ngpus, int clear, int dont_show, int calc_map, int mjpeg_port, int show_imgs, int benchmark_layers, char* chart_path)
{
list *options = read_data_cfg(datacfg);
char *train_images = option_find_str(options, "train", "data/train.txt");
char *valid_images = option_find_str(options, "valid", train_images);
char *backup_directory = option_find_str(options, "backup", "/backup/");
network net_map;
if (calc_map) {
FILE* valid_file = fopen(valid_images, "r");
if (!valid_file) {
printf("\n Error: There is no %s file for mAP calculation!\n Don't use -map flag.\n Or set valid=%s in your %s file. \n", valid_images, train_images, datacfg);
getchar();
exit(-1);
}
else fclose(valid_file);
cuda_set_device(gpus[0]);
printf(" Prepare additional network for mAP calculation...\n");
net_map = parse_network_cfg_custom(cfgfile, 1, 1);
net_map.benchmark_layers = benchmark_layers;
const int net_classes = net_map.layers[net_map.n - 1].classes;
int k; // free memory unnecessary arrays
for (k = 0; k < net_map.n - 1; ++k) free_layer_custom(net_map.layers[k], 1);
char *name_list = option_find_str(options, "names", "data/names.list");
int names_size = 0;
char **names = get_labels_custom(name_list, &names_size);
if (net_classes != names_size) {
printf("\n Error: in the file %s number of names %d that isn't equal to classes=%d in the file %s \n",
name_list, names_size, net_classes, cfgfile);
if (net_classes > names_size) getchar();
}
free_ptrs((void**)names, net_map.layers[net_map.n - 1].classes);
}
srand(time(0));
char *base = basecfg(cfgfile);
printf("%s\n", base);
float avg_loss = -1;
float avg_contrastive_acc = 0;
network* nets = (network*)xcalloc(ngpus, sizeof(network));
srand(time(0));
int seed = rand();
int k;
for (k = 0; k < ngpus; ++k) {
srand(seed);
#ifdef GPU
cuda_set_device(gpus[k]);
#endif
nets[k] = parse_network_cfg(cfgfile);
nets[k].benchmark_layers = benchmark_layers;
if (weightfile) {
load_weights(&nets[k], weightfile);
}
if (clear) {
*nets[k].seen = 0;
*nets[k].cur_iteration = 0;
}
nets[k].learning_rate *= ngpus;
}
srand(time(0));
network net = nets[0];
const int actual_batch_size = net.batch * net.subdivisions;
if (actual_batch_size == 1) {
printf("\n Error: You set incorrect value batch=1 for Training! You should set batch=64 subdivision=64 \n");
getchar();
}
else if (actual_batch_size < 8) {
printf("\n Warning: You set batch=%d lower than 64! It is recommended to set batch=64 subdivision=64 \n", actual_batch_size);
}
int imgs = net.batch * net.subdivisions * ngpus;
printf("Learning Rate: %g, Momentum: %g, Decay: %g\n", net.learning_rate, net.momentum, net.decay);
data train, buffer;
layer l = net.layers[net.n - 1];
for (k = 0; k < net.n; ++k) {
layer lk = net.layers[k];
if (lk.type == YOLO || lk.type == GAUSSIAN_YOLO || lk.type == REGION) {
l = lk;
printf(" Detection layer: %d - type = %d \n", k, l.type);
}
}
int classes = l.classes;
list *plist = get_paths(train_images);
int train_images_num = plist->size;
char **paths = (char **)list_to_array(plist);
const int init_w = net.w;
const int init_h = net.h;
const int init_b = net.batch;
int iter_save, iter_save_last, iter_map;
iter_save = get_current_iteration(net);
iter_save_last = get_current_iteration(net);
iter_map = get_current_iteration(net);
float mean_average_precision = -1;
float best_map = mean_average_precision;
load_args args = { 0 };
args.w = net.w;
args.h = net.h;
args.c = net.c;
args.paths = paths;
args.n = imgs;
args.m = plist->size;
args.classes = classes;
args.flip = net.flip;
args.jitter = l.jitter;
args.resize = l.resize;
args.num_boxes = l.max_boxes;
args.truth_size = l.truth_size;
net.num_boxes = args.num_boxes;
net.train_images_num = train_images_num;
args.d = &buffer;
args.type = DETECTION_DATA;
args.threads = 64; // 16 or 64
args.angle = net.angle;
args.gaussian_noise = net.gaussian_noise;
args.blur = net.blur;
args.mixup = net.mixup;
args.exposure = net.exposure;
args.saturation = net.saturation;
args.hue = net.hue;
args.letter_box = net.letter_box;
args.mosaic_bound = net.mosaic_bound;
args.contrastive = net.contrastive;
args.contrastive_jit_flip = net.contrastive_jit_flip;
if (dont_show && show_imgs) show_imgs = 2;
args.show_imgs = show_imgs;
#ifdef OPENCV
//int num_threads = get_num_threads();
//if(num_threads > 2) args.threads = get_num_threads() - 2;
args.threads = 6 * ngpus; // 3 for - Amazon EC2 Tesla V100: p3.2xlarge (8 logical cores) - p3.16xlarge
//args.threads = 12 * ngpus; // Ryzen 7 2700X (16 logical cores)
mat_cv* img = NULL;
float max_img_loss = net.max_chart_loss;
int number_of_lines = 100;
int img_size = 1000;
char windows_name[100];
sprintf(windows_name, "chart_%s.png", base);
img = draw_train_chart(windows_name, max_img_loss, net.max_batches, number_of_lines, img_size, dont_show, chart_path);
#endif //OPENCV
if (net.contrastive && args.threads > net.batch/2) args.threads = net.batch / 2;
if (net.track) {
args.track = net.track;
args.augment_speed = net.augment_speed;
if (net.sequential_subdivisions) args.threads = net.sequential_subdivisions * ngpus;
else args.threads = net.subdivisions * ngpus;
args.mini_batch = net.batch / net.time_steps;
printf("\n Tracking! batch = %d, subdiv = %d, time_steps = %d, mini_batch = %d \n", net.batch, net.subdivisions, net.time_steps, args.mini_batch);
}
//printf(" imgs = %d \n", imgs);
pthread_t load_thread = load_data(args);
int count = 0;
double time_remaining, avg_time = -1, alpha_time = 0.01;
//while(i*imgs < N*120){
while (get_current_iteration(net) < net.max_batches) {
if (l.random && count++ % 10 == 0) {
float rand_coef = 1.4;
if (l.random != 1.0) rand_coef = l.random;
printf("Resizing, random_coef = %.2f \n", rand_coef);
float random_val = rand_scale(rand_coef); // *x or /x
int dim_w = roundl(random_val*init_w / net.resize_step + 1) * net.resize_step;
int dim_h = roundl(random_val*init_h / net.resize_step + 1) * net.resize_step;
if (random_val < 1 && (dim_w > init_w || dim_h > init_h)) dim_w = init_w, dim_h = init_h;
int max_dim_w = roundl(rand_coef*init_w / net.resize_step + 1) * net.resize_step;
int max_dim_h = roundl(rand_coef*init_h / net.resize_step + 1) * net.resize_step;
// at the beginning (check if enough memory) and at the end (calc rolling mean/variance)
if (avg_loss < 0 || get_current_iteration(net) > net.max_batches - 100) {
dim_w = max_dim_w;
dim_h = max_dim_h;
}
if (dim_w < net.resize_step) dim_w = net.resize_step;
if (dim_h < net.resize_step) dim_h = net.resize_step;
int dim_b = (init_b * max_dim_w * max_dim_h) / (dim_w * dim_h);
int new_dim_b = (int)(dim_b * 0.8);
if (new_dim_b > init_b) dim_b = new_dim_b;
args.w = dim_w;
args.h = dim_h;
int k;
if (net.dynamic_minibatch) {
for (k = 0; k < ngpus; ++k) {
(*nets[k].seen) = init_b * net.subdivisions * get_current_iteration(net); // remove this line, when you will save to weights-file both: seen & cur_iteration
nets[k].batch = dim_b;
int j;
for (j = 0; j < nets[k].n; ++j)
nets[k].layers[j].batch = dim_b;
}
net.batch = dim_b;
imgs = net.batch * net.subdivisions * ngpus;
args.n = imgs;
printf("\n %d x %d (batch = %d) \n", dim_w, dim_h, net.batch);
}
else
printf("\n %d x %d \n", dim_w, dim_h);
pthread_join(load_thread, 0);
train = buffer;
free_data(train);
load_thread = load_data(args);
for (k = 0; k < ngpus; ++k) {
resize_network(nets + k, dim_w, dim_h);
}
net = nets[0];
}
double time = what_time_is_it_now();
pthread_join(load_thread, 0);
train = buffer;
if (net.track) {
net.sequential_subdivisions = get_current_seq_subdivisions(net);
args.threads = net.sequential_subdivisions * ngpus;
printf(" sequential_subdivisions = %d, sequence = %d \n", net.sequential_subdivisions, get_sequence_value(net));
}
load_thread = load_data(args);
//wait_key_cv(500);
/*
int k;
for(k = 0; k < l.max_boxes; ++k){
box b = float_to_box(train.y.vals[10] + 1 + k*5);
if(!b.x) break;
printf("loaded: %f %f %f %f\n", b.x, b.y, b.w, b.h);
}
image im = float_to_image(448, 448, 3, train.X.vals[10]);
int k;
for(k = 0; k < l.max_boxes; ++k){
box b = float_to_box(train.y.vals[10] + 1 + k*5);
printf("%d %d %d %d\n", truth.x, truth.y, truth.w, truth.h);
draw_bbox(im, b, 8, 1,0,0);
}
save_image(im, "truth11");
*/
const double load_time = (what_time_is_it_now() - time);
printf("Loaded: %lf seconds", load_time);
if (load_time > 0.1 && avg_loss > 0) printf(" - performance bottleneck on CPU or Disk HDD/SSD");
printf("\n");
time = what_time_is_it_now();
float loss = 0;
#ifdef GPU
if (ngpus == 1) {
int wait_key = (dont_show) ? 0 : 1;
loss = train_network_waitkey(net, train, wait_key);
}
else {
loss = train_networks(nets, ngpus, train, 4);
}
#else
loss = train_network(net, train);
#endif
if (avg_loss < 0 || avg_loss != avg_loss) avg_loss = loss; // if(-inf or nan)
avg_loss = avg_loss*.9 + loss*.1;
const int iteration = get_current_iteration(net);
//i = get_current_batch(net);
int calc_map_for_each = 4 * train_images_num / (net.batch * net.subdivisions); // calculate mAP for each 4 Epochs
calc_map_for_each = fmax(calc_map_for_each, 100);
int next_map_calc = iter_map + calc_map_for_each;
next_map_calc = fmax(next_map_calc, net.burn_in);
//next_map_calc = fmax(next_map_calc, 400);
if (calc_map) {
printf("\n (next mAP calculation at %d iterations) ", next_map_calc);
if (mean_average_precision > 0) printf("\n Last accuracy [email protected] = %2.2f %%, best = %2.2f %% ", mean_average_precision * 100, best_map * 100);
}
if (net.cudnn_half) {
if (iteration < net.burn_in * 3) fprintf(stderr, "\n Tensor Cores are disabled until the first %d iterations are reached.\n", 3 * net.burn_in);
else fprintf(stderr, "\n Tensor Cores are used.\n");
fflush(stderr);
}
printf("\n %d: %f, %f avg loss, %f rate, %lf seconds, %d images, %f hours left\n", iteration, loss, avg_loss, get_current_rate(net), (what_time_is_it_now() - time), iteration*imgs, avg_time);
fflush(stdout);
int draw_precision = 0;
if (calc_map && (iteration >= next_map_calc || iteration == net.max_batches)) {
if (l.random) {
printf("Resizing to initial size: %d x %d ", init_w, init_h);
args.w = init_w;
args.h = init_h;
int k;
if (net.dynamic_minibatch) {
for (k = 0; k < ngpus; ++k) {
for (k = 0; k < ngpus; ++k) {
nets[k].batch = init_b;
int j;
for (j = 0; j < nets[k].n; ++j)
nets[k].layers[j].batch = init_b;
}
}
net.batch = init_b;
imgs = init_b * net.subdivisions * ngpus;
args.n = imgs;
printf("\n %d x %d (batch = %d) \n", init_w, init_h, init_b);
}
pthread_join(load_thread, 0);
free_data(train);
train = buffer;
load_thread = load_data(args);
for (k = 0; k < ngpus; ++k) {
resize_network(nets + k, init_w, init_h);
}
net = nets[0];
}
copy_weights_net(net, &net_map);
// combine Training and Validation networks
//network net_combined = combine_train_valid_networks(net, net_map);
iter_map = iteration;
mean_average_precision = validate_detector_map(datacfg, cfgfile, weightfile, 0.25, 0.5, 0, net.letter_box, &net_map);// &net_combined);
printf("\n mean_average_precision ([email protected]) = %f \n", mean_average_precision);
if (mean_average_precision > best_map) {
best_map = mean_average_precision;
printf("New best mAP!\n");
char buff[256];
sprintf(buff, "%s/%s_best.weights", backup_directory, base);
save_weights(net, buff);
}
draw_precision = 1;
}
time_remaining = ((net.max_batches - iteration) / ngpus)*(what_time_is_it_now() - time + load_time) / 60 / 60;
// set initial value, even if resume training from 10000 iteration
if (avg_time < 0) avg_time = time_remaining;
else avg_time = alpha_time * time_remaining + (1 - alpha_time) * avg_time;
#ifdef OPENCV
if (net.contrastive) {
float cur_con_acc = -1;
for (k = 0; k < net.n; ++k)
if (net.layers[k].type == CONTRASTIVE) cur_con_acc = *net.layers[k].loss;
if (cur_con_acc >= 0) avg_contrastive_acc = avg_contrastive_acc*0.99 + cur_con_acc * 0.01;
printf(" avg_contrastive_acc = %f \n", avg_contrastive_acc);
}
draw_train_loss(windows_name, img, img_size, avg_loss, max_img_loss, iteration, net.max_batches, mean_average_precision, draw_precision, "mAP%", avg_contrastive_acc / 100, dont_show, mjpeg_port, avg_time);
#endif // OPENCV
//if (i % 1000 == 0 || (i < 1000 && i % 100 == 0)) {
//if (i % 100 == 0) {
if (iteration >= (iter_save + 1000) || iteration % 1000 == 0) {
iter_save = iteration;
#ifdef GPU
if (ngpus != 1) sync_nets(nets, ngpus, 0);
#endif
char buff[256];
sprintf(buff, "%s/%s_%d.weights", backup_directory, base, iteration);
save_weights(net, buff);
}
if (iteration >= (iter_save_last + 100) || (iteration % 100 == 0 && iteration > 1)) {
iter_save_last = iteration;
#ifdef GPU
if (ngpus != 1) sync_nets(nets, ngpus, 0);
#endif
char buff[256];
sprintf(buff, "%s/%s_last.weights", backup_directory, base);
save_weights(net, buff);
}
free_data(train);
}
#ifdef GPU
if (ngpus != 1) sync_nets(nets, ngpus, 0);
#endif
char buff[256];
sprintf(buff, "%s/%s_final.weights", backup_directory, base);
save_weights(net, buff);
printf("If you want to train from the beginning, then use flag in the end of training command: -clear \n");
#ifdef OPENCV
release_mat(&img);
destroy_all_windows_cv();
#endif
// free memory
pthread_join(load_thread, 0);
free_data(buffer);
free_load_threads(&args);
free(base);
free(paths);
free_list_contents(plist);
free_list(plist);
free_list_contents_kvp(options);
free_list(options);
for (k = 0; k < ngpus; ++k) free_network(nets[k]);
free(nets);
//free_network(net);
if (calc_map) {
net_map.n = 0;
free_network(net_map);
}
}
static int get_coco_image_id(char *filename)
{
char *p = strrchr(filename, '/');
char *c = strrchr(filename, '_');
if (c) p = c;
return atoi(p + 1);
}
static void print_cocos(FILE *fp, char *image_path, detection *dets, int num_boxes, int classes, int w, int h)
{
int i, j;
//int image_id = get_coco_image_id(image_path);
char *p = basecfg(image_path);
int image_id = atoi(p);
for (i = 0; i < num_boxes; ++i) {
float xmin = dets[i].bbox.x - dets[i].bbox.w / 2.;
float xmax = dets[i].bbox.x + dets[i].bbox.w / 2.;
float ymin = dets[i].bbox.y - dets[i].bbox.h / 2.;
float ymax = dets[i].bbox.y + dets[i].bbox.h / 2.;
if (xmin < 0) xmin = 0;
if (ymin < 0) ymin = 0;
if (xmax > w) xmax = w;
if (ymax > h) ymax = h;
float bx = xmin;
float by = ymin;
float bw = xmax - xmin;
float bh = ymax - ymin;
for (j = 0; j < classes; ++j) {
if (dets[i].prob[j] > 0) {
char buff[1024];
sprintf(buff, "{\"image_id\":%d, \"category_id\":%d, \"bbox\":[%f, %f, %f, %f], \"score\":%f},\n", image_id, coco_ids[j], bx, by, bw, bh, dets[i].prob[j]);
fprintf(fp, buff);
//printf("%s", buff);
}
}
}
}
void print_detector_detections(FILE **fps, char *id, detection *dets, int total, int classes, int w, int h)
{
int i, j;
for (i = 0; i < total; ++i) {
float xmin = dets[i].bbox.x - dets[i].bbox.w / 2. + 1;
float xmax = dets[i].bbox.x + dets[i].bbox.w / 2. + 1;
float ymin = dets[i].bbox.y - dets[i].bbox.h / 2. + 1;
float ymax = dets[i].bbox.y + dets[i].bbox.h / 2. + 1;
if (xmin < 1) xmin = 1;
if (ymin < 1) ymin = 1;
if (xmax > w) xmax = w;
if (ymax > h) ymax = h;
for (j = 0; j < classes; ++j) {
if (dets[i].prob[j]) fprintf(fps[j], "%s %f %f %f %f %f\n", id, dets[i].prob[j],
xmin, ymin, xmax, ymax);
}
}
}
void print_imagenet_detections(FILE *fp, int id, detection *dets, int total, int classes, int w, int h)
{
int i, j;
for (i = 0; i < total; ++i) {
float xmin = dets[i].bbox.x - dets[i].bbox.w / 2.;
float xmax = dets[i].bbox.x + dets[i].bbox.w / 2.;
float ymin = dets[i].bbox.y - dets[i].bbox.h / 2.;
float ymax = dets[i].bbox.y + dets[i].bbox.h / 2.;
if (xmin < 0) xmin = 0;
if (ymin < 0) ymin = 0;
if (xmax > w) xmax = w;
if (ymax > h) ymax = h;
for (j = 0; j < classes; ++j) {
int myclass = j;
if (dets[i].prob[myclass] > 0) fprintf(fp, "%d %d %f %f %f %f %f\n", id, j + 1, dets[i].prob[myclass],
xmin, ymin, xmax, ymax);
}
}
}
static void print_kitti_detections(FILE **fps, char *id, detection *dets, int total, int classes, int w, int h, char *outfile, char *prefix)
{
char *kitti_ids[] = { "car", "pedestrian", "cyclist" };
FILE *fpd = 0;
char buffd[1024];
snprintf(buffd, 1024, "%s/%s/data/%s.txt", prefix, outfile, id);
fpd = fopen(buffd, "w");
int i, j;
for (i = 0; i < total; ++i)
{
float xmin = dets[i].bbox.x - dets[i].bbox.w / 2.;
float xmax = dets[i].bbox.x + dets[i].bbox.w / 2.;
float ymin = dets[i].bbox.y - dets[i].bbox.h / 2.;
float ymax = dets[i].bbox.y + dets[i].bbox.h / 2.;
if (xmin < 0) xmin = 0;
if (ymin < 0) ymin = 0;
if (xmax > w) xmax = w;
if (ymax > h) ymax = h;
for (j = 0; j < classes; ++j)
{
//if (dets[i].prob[j]) fprintf(fpd, "%s 0 0 0 %f %f %f %f -1 -1 -1 -1 0 0 0 %f\n", kitti_ids[j], xmin, ymin, xmax, ymax, dets[i].prob[j]);
if (dets[i].prob[j]) fprintf(fpd, "%s -1 -1 -10 %f %f %f %f -1 -1 -1 -1000 -1000 -1000 -10 %f\n", kitti_ids[j], xmin, ymin, xmax, ymax, dets[i].prob[j]);
}
}
fclose(fpd);
}
static void eliminate_bdd(char *buf, char *a)
{
int n = 0;
int i, k;
for (i = 0; buf[i] != '\0'; i++)
{
if (buf[i] == a[n])
{
k = i;
while (buf[i] == a[n])
{
if (a[++n] == '\0')
{
for (k; buf[k + n] != '\0'; k++)
{
buf[k] = buf[k + n];
}
buf[k] = '\0';
break;
}
i++;
}
n = 0; i--;
}
}
}
static void get_bdd_image_id(char *filename)
{
char *p = strrchr(filename, '/');
eliminate_bdd(p, ".jpg");
eliminate_bdd(p, "/");
strcpy(filename, p);
}
static void print_bdd_detections(FILE *fp, char *image_path, detection *dets, int num_boxes, int classes, int w, int h)
{
char *bdd_ids[] = { "bike" , "bus" , "car" , "motor" ,"person", "rider", "traffic light", "traffic sign", "train", "truck" };
get_bdd_image_id(image_path);
int i, j;
for (i = 0; i < num_boxes; ++i)
{
float xmin = dets[i].bbox.x - dets[i].bbox.w / 2.;
float xmax = dets[i].bbox.x + dets[i].bbox.w / 2.;
float ymin = dets[i].bbox.y - dets[i].bbox.h / 2.;
float ymax = dets[i].bbox.y + dets[i].bbox.h / 2.;
if (xmin < 0) xmin = 0;
if (ymin < 0) ymin = 0;
if (xmax > w) xmax = w;
if (ymax > h) ymax = h;
float bx1 = xmin;
float by1 = ymin;
float bx2 = xmax;
float by2 = ymax;
for (j = 0; j < classes; ++j)
{
if (dets[i].prob[j])
{
fprintf(fp, "\t{\n\t\t\"name\":\"%s\",\n\t\t\"category\":\"%s\",\n\t\t\"bbox\":[%f, %f, %f, %f],\n\t\t\"score\":%f\n\t},\n", image_path, bdd_ids[j], bx1, by1, bx2, by2, dets[i].prob[j]);
}
}
}
}
void validate_detector(char *datacfg, char *cfgfile, char *weightfile, char *outfile)
{
int j;
list *options = read_data_cfg(datacfg);
char *valid_images = option_find_str(options, "valid", "data/train.list");
char *name_list = option_find_str(options, "names", "data/names.list");
char *prefix = option_find_str(options, "results", "results");
char **names = get_labels(name_list);
char *mapf = option_find_str(options, "map", 0);
int *map = 0;
if (mapf) map = read_map(mapf);
network net = parse_network_cfg_custom(cfgfile, 1, 1); // set batch=1
if (weightfile) {
load_weights(&net, weightfile);
}
//set_batch_network(&net, 1);
fuse_conv_batchnorm(net);
calculate_binary_weights(net);
fprintf(stderr, "Learning Rate: %g, Momentum: %g, Decay: %g\n", net.learning_rate, net.momentum, net.decay);
srand(time(0));
list *plist = get_paths(valid_images);
char **paths = (char **)list_to_array(plist);
layer l = net.layers[net.n - 1];
int k;
for (k = 0; k < net.n; ++k) {
layer lk = net.layers[k];
if (lk.type == YOLO || lk.type == GAUSSIAN_YOLO || lk.type == REGION) {
l = lk;
printf(" Detection layer: %d - type = %d \n", k, l.type);
}
}
int classes = l.classes;
char buff[1024];
char *type = option_find_str(options, "eval", "voc");
FILE *fp = 0;
FILE **fps = 0;
int coco = 0;
int imagenet = 0;
int bdd = 0;
int kitti = 0;
if (0 == strcmp(type, "coco")) {
if (!outfile) outfile = "coco_results";
snprintf(buff, 1024, "%s/%s.json", prefix, outfile);
fp = fopen(buff, "w");
fprintf(fp, "[\n");
coco = 1;
}
else if (0 == strcmp(type, "bdd")) {
if (!outfile) outfile = "bdd_results";
snprintf(buff, 1024, "%s/%s.json", prefix, outfile);
fp = fopen(buff, "w");
fprintf(fp, "[\n");
bdd = 1;
}
else if (0 == strcmp(type, "kitti")) {
char buff2[1024];
if (!outfile) outfile = "kitti_results";
printf("%s\n", outfile);
snprintf(buff, 1024, "%s/%s", prefix, outfile);
int mkd = make_directory(buff, 0777);
snprintf(buff2, 1024, "%s/%s/data", prefix, outfile);
int mkd2 = make_directory(buff2, 0777);
kitti = 1;
}
else if (0 == strcmp(type, "imagenet")) {
if (!outfile) outfile = "imagenet-detection";
snprintf(buff, 1024, "%s/%s.txt", prefix, outfile);
fp = fopen(buff, "w");
imagenet = 1;
classes = 200;
}
else {
if (!outfile) outfile = "comp4_det_test_";
fps = (FILE**) xcalloc(classes, sizeof(FILE *));
for (j = 0; j < classes; ++j) {
snprintf(buff, 1024, "%s/%s%s.txt", prefix, outfile, names[j]);
fps[j] = fopen(buff, "w");
}
}
int m = plist->size;
int i = 0;
int t;
float thresh = .001;
float nms = .45;
int nthreads = 4;
if (m < 4) nthreads = m;
image* val = (image*)xcalloc(nthreads, sizeof(image));
image* val_resized = (image*)xcalloc(nthreads, sizeof(image));
image* buf = (image*)xcalloc(nthreads, sizeof(image));
image* buf_resized = (image*)xcalloc(nthreads, sizeof(image));
pthread_t* thr = (pthread_t*)xcalloc(nthreads, sizeof(pthread_t));
load_args args = { 0 };
args.w = net.w;
args.h = net.h;
args.c = net.c;
args.type = IMAGE_DATA;
const int letter_box = net.letter_box;
if (letter_box) args.type = LETTERBOX_DATA;
for (t = 0; t < nthreads; ++t) {
args.path = paths[i + t];
args.im = &buf[t];
args.resized = &buf_resized[t];
thr[t] = load_data_in_thread(args);
}
time_t start = time(0);
for (i = nthreads; i < m + nthreads; i += nthreads) {
fprintf(stderr, "%d\n", i);
for (t = 0; t < nthreads && i + t - nthreads < m; ++t) {
pthread_join(thr[t], 0);
val[t] = buf[t];
val_resized[t] = buf_resized[t];
}
for (t = 0; t < nthreads && i + t < m; ++t) {
args.path = paths[i + t];
args.im = &buf[t];
args.resized = &buf_resized[t];
thr[t] = load_data_in_thread(args);
}
for (t = 0; t < nthreads && i + t - nthreads < m; ++t) {
char *path = paths[i + t - nthreads];
char *id = basecfg(path);
float *X = val_resized[t].data;
network_predict(net, X);
int w = val[t].w;
int h = val[t].h;
int nboxes = 0;
detection *dets = get_network_boxes(&net, w, h, thresh, .5, map, 0, &nboxes, letter_box);
if (nms) {
if (l.nms_kind == DEFAULT_NMS) do_nms_sort(dets, nboxes, l.classes, nms);
else diounms_sort(dets, nboxes, l.classes, nms, l.nms_kind, l.beta_nms);
}
if (coco) {
print_cocos(fp, path, dets, nboxes, classes, w, h);
}
else if (imagenet) {
print_imagenet_detections(fp, i + t - nthreads + 1, dets, nboxes, classes, w, h);
}
else if (bdd) {
print_bdd_detections(fp, path, dets, nboxes, classes, w, h);
}
else if (kitti) {
print_kitti_detections(fps, id, dets, nboxes, classes, w, h, outfile, prefix);
}
else {
print_detector_detections(fps, id, dets, nboxes, classes, w, h);
}
free_detections(dets, nboxes);
free(id);
free_image(val[t]);
free_image(val_resized[t]);
}
}
if (fps) {
for (j = 0; j < classes; ++j) {
fclose(fps[j]);
}
free(fps);
}
if (coco) {
#ifdef WIN32
fseek(fp, -3, SEEK_CUR);
#else
fseek(fp, -2, SEEK_CUR);
#endif
fprintf(fp, "\n]\n");
}
if (bdd) {
#ifdef WIN32
fseek(fp, -3, SEEK_CUR);
#else
fseek(fp, -2, SEEK_CUR);
#endif
fprintf(fp, "\n]\n");
fclose(fp);
}
if (fp) fclose(fp);
if (val) free(val);
if (val_resized) free(val_resized);
if (thr) free(thr);
if (buf) free(buf);
if (buf_resized) free(buf_resized);
fprintf(stderr, "Total Detection Time: %f Seconds\n", (double)time(0) - start);
}
void validate_detector_recall(char *datacfg, char *cfgfile, char *weightfile)
{
network net = parse_network_cfg_custom(cfgfile, 1, 1); // set batch=1
if (weightfile) {
load_weights(&net, weightfile);
}
//set_batch_network(&net, 1);
fuse_conv_batchnorm(net);
srand(time(0));
//list *plist = get_paths("data/coco_val_5k.list");
list *options = read_data_cfg(datacfg);
char *valid_images = option_find_str(options, "valid", "data/train.txt");
list *plist = get_paths(valid_images);
char **paths = (char **)list_to_array(plist);
//layer l = net.layers[net.n - 1];
int j, k;
int m = plist->size;
int i = 0;
float thresh = .001;
float iou_thresh = .5;
float nms = .4;
int total = 0;
int correct = 0;
int proposals = 0;
float avg_iou = 0;
for (i = 0; i < m; ++i) {
char *path = paths[i];
image orig = load_image(path, 0, 0, net.c);
image sized = resize_image(orig, net.w, net.h);
char *id = basecfg(path);
network_predict(net, sized.data);
int nboxes = 0;
int letterbox = 0;
detection *dets = get_network_boxes(&net, sized.w, sized.h, thresh, .5, 0, 1, &nboxes, letterbox);
if (nms) do_nms_obj(dets, nboxes, 1, nms);
char labelpath[4096];
replace_image_to_label(path, labelpath);
int num_labels = 0;
box_label *truth = read_boxes(labelpath, &num_labels);
for (k = 0; k < nboxes; ++k) {
if (dets[k].objectness > thresh) {
++proposals;
}
}
for (j = 0; j < num_labels; ++j) {
++total;
box t = { truth[j].x, truth[j].y, truth[j].w, truth[j].h };
float best_iou = 0;
for (k = 0; k < nboxes; ++k) {
float iou = box_iou(dets[k].bbox, t);
if (dets[k].objectness > thresh && iou > best_iou) {
best_iou = iou;
}
}
avg_iou += best_iou;
if (best_iou > iou_thresh) {
++correct;
}
}
//fprintf(stderr, " %s - %s - ", paths[i], labelpath);
fprintf(stderr, "%5d %5d %5d\tRPs/Img: %.2f\tIOU: %.2f%%\tRecall:%.2f%%\n", i, correct, total, (float)proposals / (i + 1), avg_iou * 100 / total, 100.*correct / total);
free(id);
free_image(orig);
free_image(sized);
}
}
typedef struct {
box b;
float p;
int class_id;
int image_index;
int truth_flag;
int unique_truth_index;
} box_prob;
int detections_comparator(const void *pa, const void *pb)
{
box_prob a = *(const box_prob *)pa;
box_prob b = *(const box_prob *)pb;
float diff = a.p - b.p;
if (diff < 0) return 1;
else if (diff > 0) return -1;
return 0;
}
float validate_detector_map(char *datacfg, char *cfgfile, char *weightfile, float thresh_calc_avg_iou, const float iou_thresh, const int map_points, int letter_box, network *existing_net)
{
int j;
list *options = read_data_cfg(datacfg);
char *valid_images = option_find_str(options, "valid", "data/train.txt");
char *difficult_valid_images = option_find_str(options, "difficult", NULL);
char *name_list = option_find_str(options, "names", "data/names.list");
int names_size = 0;
char **names = get_labels_custom(name_list, &names_size); //get_labels(name_list);
//char *mapf = option_find_str(options, "map", 0);
//int *map = 0;
//if (mapf) map = read_map(mapf);
FILE* reinforcement_fd = NULL;
network net;
//int initial_batch;
if (existing_net) {
char *train_images = option_find_str(options, "train", "data/train.txt");
valid_images = option_find_str(options, "valid", train_images);
net = *existing_net;
remember_network_recurrent_state(*existing_net);
free_network_recurrent_state(*existing_net);
}
else {
net = parse_network_cfg_custom(cfgfile, 1, 1); // set batch=1
if (weightfile) {
load_weights(&net, weightfile);
}
//set_batch_network(&net, 1);
fuse_conv_batchnorm(net);
calculate_binary_weights(net);
}
if (net.layers[net.n - 1].classes != names_size) {
printf("\n Error: in the file %s number of names %d that isn't equal to classes=%d in the file %s \n",
name_list, names_size, net.layers[net.n - 1].classes, cfgfile);
getchar();
}
srand(time(0));
printf("\n calculation mAP (mean average precision)...\n");
list *plist = get_paths(valid_images);
char **paths = (char **)list_to_array(plist);
char **paths_dif = NULL;
if (difficult_valid_images) {
list *plist_dif = get_paths(difficult_valid_images);
paths_dif = (char **)list_to_array(plist_dif);
}
layer l = net.layers[net.n - 1];
int k;
for (k = 0; k < net.n; ++k) {
layer lk = net.layers[k];
if (lk.type == YOLO || lk.type == GAUSSIAN_YOLO || lk.type == REGION) {
l = lk;
printf(" Detection layer: %d - type = %d \n", k, l.type);
}
}
int classes = l.classes;
int m = plist->size;
int i = 0;
int t;
const float thresh = .005;
const float nms = .45;
//const float iou_thresh = 0.5;
int nthreads = 4;
if (m < 4) nthreads = m;
image* val = (image*)xcalloc(nthreads, sizeof(image));
image* val_resized = (image*)xcalloc(nthreads, sizeof(image));
image* buf = (image*)xcalloc(nthreads, sizeof(image));
image* buf_resized = (image*)xcalloc(nthreads, sizeof(image));
pthread_t* thr = (pthread_t*)xcalloc(nthreads, sizeof(pthread_t));
load_args args = { 0 };
args.w = net.w;
args.h = net.h;