-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtschybrid.cpp
2531 lines (2151 loc) · 82.5 KB
/
tschybrid.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
#include "tschybrid.h"
#include "experimentalData.h"
#include "GraphSegmentation/ColoredSegments/coloredSegments.h"
#include "VPC_toolkit/VPC.h"
#include "VPC_toolkit/VPC.h"
int vpc_label = 0;
TSCHybrid::TSCHybrid(QCustomPlot* tsc_plot,
QCustomPlot* ssg_plot,
QCustomPlot* place_map,
QCustomPlot* tsc_avg_plot,
Parameters* params,
Dataset* dataset)
{
this->tsc_plot = tsc_plot;
this->ssg_plot = ssg_plot;
this->tsc_avg_plot = tsc_avg_plot;
this->params = params;
this->dataset = dataset;
///////////////////
// Plot settings //
///////////////////
QPen pen1, pen2, pen3, pen4;
pen1.setWidth(PEN_WIDTH1);
pen1.setColor(Qt::red);
pen2.setWidth(PEN_WIDTH2);
pen2.setColor(Qt::black);
pen3.setWidth(PEN_WIDTH2);
pen3.setColor(Qt::red);
pen4.setWidth(PEN_WIDTH3);
pen4.setColor(Qt::green);
QMargins plot_margin(COH_PLOT_MARGIN,0,COH_PLOT_MARGIN,0);
//Settings for ssg plot
for(int i = 0; i <= PLOT_PLACES_IDX; i++)
this->ssg_plot->addGraph();
this->ssg_plot->graph(PLOT_TRACK_IDX)->setPen(pen4);
this->ssg_plot->graph(PLOT_TRACK_IDX)->setLineStyle(QCPGraph::lsNone);
this->ssg_plot->graph(PLOT_TRACK_IDX)->setScatterStyle(QCPScatterStyle::ssDisc);
this->ssg_plot->graph(PLOT_THRES_IDX)->setPen(pen1);
this->ssg_plot->graph(PLOT_SCORES_IDX)->setPen(pen2);
this->ssg_plot->setMaximumWidth(COH_PLOT_W);
this->ssg_plot->setMinimumWidth(COH_PLOT_W);
this->ssg_plot->setMinimumHeight(COH_PLOT_H);
this->ssg_plot->setMaximumHeight(COH_PLOT_H);
this->ssg_plot->yAxis->setTickLabels(false);
this->ssg_plot->plotLayout()->setAutoMargins(QCP::msNone);
this->ssg_plot->plotLayout()->setMargins(plot_margin);
this->ssg_plot->graph(PLOT_VPC_IDX)->setPen(pen2);
this->ssg_plot->graph(PLOT_VPC_IDX)->setLineStyle(QCPGraph::lsNone);
this->ssg_plot->graph(PLOT_VPC_IDX)->setScatterStyle(QCPScatterStyle::ssCircle);
this->ssg_plot->graph(PLOT_VPC_IDX+1)->setPen(pen2);
this->ssg_plot->graph(PLOT_VPC_IDX+1)->setLineStyle(QCPGraph::lsNone);
this->ssg_plot->graph(PLOT_VPC_IDX+1)->setScatterStyle(QCPScatterStyle::ssCircle);
//Settings for tsc plot
for(int i = 0; i <= PLOT_PLACES_IDX; i++)
this->tsc_plot->addGraph();
this->tsc_plot->graph(PLOT_THRES_IDX)->setPen(pen1);
this->tsc_plot->graph(PLOT_SCORES_IDX)->setPen(pen2);
this->tsc_plot->setMaximumWidth(COH_PLOT_W);
this->tsc_plot->setMinimumWidth(COH_PLOT_W);
this->tsc_plot->setMinimumHeight(COH_PLOT_H);
this->tsc_plot->setMaximumHeight(COH_PLOT_H);
this->tsc_plot->yAxis->setTickLabels(false);
this->tsc_plot->plotLayout()->setAutoMargins(QCP::msNone);
this->tsc_plot->plotLayout()->setMargins(plot_margin);
this->tsc_plot->graph(PLOT_UNINFORMATIVE_IDX)->setPen(pen2);
this->tsc_plot->graph(PLOT_UNINFORMATIVE_IDX)->setLineStyle(QCPGraph::lsNone);
this->tsc_plot->graph(PLOT_UNINFORMATIVE_IDX)->setScatterStyle(QCPScatterStyle::ssTriangle);
this->tsc_plot->graph(PLOT_INCOHERENT_IDX)->setPen(pen2);
this->tsc_plot->graph(PLOT_INCOHERENT_IDX)->setLineStyle(QCPGraph::lsNone);
this->tsc_plot->graph(PLOT_INCOHERENT_IDX)->setScatterStyle(QCPScatterStyle::ssCircle);
//Settings for tsc avg plot
for(int i = 0; i <= PLOT_PLACES_IDX; i++)
this->tsc_avg_plot->addGraph();
this->tsc_avg_plot->graph(PLOT_INCOHERENT_IDX+2)->setPen(pen2);
this->tsc_avg_plot->graph(PLOT_INCOHERENT_IDX+2)->setLineStyle(QCPGraph::lsNone);
this->tsc_avg_plot->graph(PLOT_INCOHERENT_IDX+2)->setScatterStyle(QCPScatterStyle::ssDot);
this->tsc_avg_plot->graph(PLOT_INCOHERENT_IDX+3)->setPen(pen3);
this->tsc_avg_plot->graph(PLOT_INCOHERENT_IDX+3)->setLineStyle(QCPGraph::lsNone);
this->tsc_avg_plot->graph(PLOT_INCOHERENT_IDX+3)->setScatterStyle(QCPScatterStyle::ssCircle);
this->tsc_avg_plot->graph(PLOT_SCORES_IDX)->setPen(pen1);
this->tsc_avg_plot->setMaximumWidth(COH_PLOT_W);
this->tsc_avg_plot->setMinimumWidth(COH_PLOT_W);
this->tsc_avg_plot->setMinimumHeight(COH_PLOT_H);
this->tsc_avg_plot->setMaximumHeight(COH_PLOT_H);
this->tsc_avg_plot->yAxis->setTickLabels(false);
this->tsc_avg_plot->plotLayout()->setAutoMargins(QCP::msNone);
this->tsc_avg_plot->plotLayout()->setMargins(plot_margin);
//Traveled places plot initialization
this->place_map = place_map;
// for(int i = 0; i <= PLOT_PLACES_IDX; i++)
// this->place_map->addGraph();
// this->place_map->axisRect()->setAutoMargins(QCP::msNone);
// this->place_map->axisRect()->setMargins(QMargins(0,0,0,0));
// this->place_map->setMaximumWidth(COLD_MAP_W);
// this->place_map->setMinimumWidth(COLD_MAP_W);
// this->place_map->setMinimumHeight(COLD_MAP_H);
// this->place_map->setMaximumHeight(COLD_MAP_H);
// this->place_map->xAxis->grid()->setVisible(false);
// this->place_map->yAxis->grid()->setVisible(false);
// this->place_map->xAxis->setTicks(false);
// this->place_map->yAxis->setTicks(false);
// this->place_map->xAxis->setVisible(false);
// this->place_map->yAxis->setVisible(false);
// this->place_map->xAxis->setRange(COLD_MAP_L, COLD_MAP_R);
// this->place_map->yAxis->setRange(COLD_MAP_T, COLD_MAP_B);
// //Plot dataset map
// QCPItemPixmap *plot_bg_img = new QCPItemPixmap(this->place_map);
// string overlay_img = string(OUTPUT_FOLDER)+"cold.png";
// plot_bg_img->setPixmap(QPixmap(overlay_img.c_str()));
// plot_bg_img->topLeft->setType(QCPItemPosition::ptViewportRatio);
// plot_bg_img->topLeft->setCoords(0,0);
// this->place_map->addLayer("imageLayer");
// this->place_map->addItem(plot_bg_img);
// this->place_map->addLayer("plotLayer");
// this->place_map->setCurrentLayer("plotLayer");
seg_track = new SegmentTrack(params,dataset);
recognition = new Recognition (params,
dataset,
seg_track->gm,
seg_track->seg);
is_processing = false;
stop_processing = false;
next_frame = true;
perform_recognition = false;
save2database = false;
//If you're running TSC model, erase comments
//tsc = new TSC(dataset);
//If you're not running TSC model
//Filters init
//string filters_dir = OUTPUT_FOLDER+string("visual_filters");
//ImageProcess::readFilter(QString(filters_dir.c_str()).append("/filtre0.txt"),29,false,false,false);
//ImageProcess::readFilter(QString(filters_dir.c_str()).append("/filtre6.txt"),29,false,false,false);
//ImageProcess::readFilter(QString(filters_dir.c_str()).append("/filtre12.txt"),29,false,false,false);
//ImageProcess::readFilter(QString(filters_dir.c_str()).append("/filtre18.txt"),29,false,false,false);
//ImageProcess::readFilter(QString(filters_dir.c_str()).append("/filtre36.txt"),29,false,false,false);
//Bubble process init
//bubbleProcess::calculateImagePanAngles(FOCAL_LENGHT_PIXELS, params->ssg_params.img_width, params->ssg_params.img_height);
//bubbleProcess::calculateImageTiltAngles(FOCAL_LENGHT_PIXELS, params->ssg_params.img_width, params->ssg_params.img_height);
}
TSCHybrid::~TSCHybrid()
{
delete recognition;
delete seg_track;
}
void TSCHybrid::readFromDB()
{
//remove comments on places you like to load from DB
vector<int> places;
places.push_back(SITE_FR1);
//places.push_back(SITE_SA1);
//places.push_back(SITE_LJ1);
//places.push_back(SITE_NC1);
places.push_back(SITE_FR2);
//places.push_back(SITE_SA2);
//places.push_back(SITE_LJ2);
// places.push_back(SITE_NC2);
//places.push_back(SITE_CV);
//places.push_back(SITE_JM);
//places.push_back(SITE_JM2
for(int i = 0; i < places.size(); i++)
{
vector<SSG> readSSG;
DatabaseHandler db;
db.setConnName("conn"+QString::number(places[i]).toStdString());
db.openDB(OUTPUT_FOLDER+string("dataset_")+QString::number(places[i]).toStdString()+string("_places.db"));
readSSG = db.getAllSSGsNew();
db.closeDB();
SSGs.insert(SSGs.end(), readSSG.begin(), readSSG.end());
readSSG.clear();
}
//remove comments on places you like to load from DB
vector<int> places_second_visit;
//places_second_visit.push_back(SITE_FR2);
//places_second_visit.push_back(SITE_SA2);
//places_second_visit.push_back(SITE_LJ2);
//places_second_visit.push_back(SITE_NC2);
for(int i = 0; i < places_second_visit.size(); i++)
{
vector<SSG> readSSG;
DatabaseHandler db;
db.setConnName("conn"+QString::number(places_second_visit[i]).toStdString());
db.openDB(OUTPUT_FOLDER+string("dataset_")+QString::number(places_second_visit[i]).toStdString()+string("_places.db"));
readSSG = db.getAllSSGsNew();
db.closeDB();
SSGs_second_visit.insert(SSGs_second_visit.end(), readSSG.begin(), readSSG.end());
readSSG.clear();
}
// DatabaseHandler db2;
// db2.setConnName("conn2");
// db2.openDB(OUTPUT_FOLDER+string("dataset_1.db"));
// db2.createTables();
// for(int i = 0; i < allSSG1.size(); i++)
// db2.insertSSG(allSSG1[i]);
// db2.closeDB();
}
void TSCHybrid::clearPastData()
{
SSGs.clear();
img_files.clear();
seg_track->getM().release();
seg_track->getM_ns().clear();
coords.clear();
for(int i = 0; i < tsc_plot->graphCount(); i++)
tsc_plot->graph(i)->clearData();
for(int i = 0; i < ssg_plot->graphCount(); i++)
ssg_plot->graph(i)->clearData();
for(int i = 0; i < place_map->graphCount(); i++)
place_map->graph(i)->clearData();
for(int i = 0; i < tsc_avg_plot->graphCount(); i++)
tsc_avg_plot->graph(i)->clearData();
}
void TSCHybrid::stopProcessing()
{
stop_processing = true;
}
void compareTransitions(VPC_Input& vpc, vector<int>& ssg)
{
int home = vpc_label;
cout << "Total image sizes:" << vpc.labels[home].size() << " " << ssg.size() << endl;
int true_pos = 0;
int false_pos = 0;
int trans_count = 0;
int trans_flag = 0;
int true_pos_flag = 0;
int region_count = 0;
for(int i = 0; i < ssg.size(); i++)
{
if(vpc.labels[home].size() < ssg.size())
break;
if(trans_flag > 0 && vpc.labels[home][i] != 0)
{
cout << "Results for region " << ++region_count << " " << (float)true_pos_flag/trans_flag << endl;
trans_flag = 0;
true_pos_flag = 0;
}
if(vpc.labels[home][i] == 0)
{
trans_count++;
trans_flag++;
}
if(vpc.labels[home][i] == 0 && ssg[i] < 0)
{
true_pos++;
true_pos_flag++;
}
}
if(trans_count > 0)
cout << "Total score is: " << (float)true_pos/trans_count << endl;
else
cout << "No transition in dataset" << endl;
}
void TSCHybrid::processImagesHierarchicalVPC(const string folder, const int start_idx, const int end_idx, int dataset_id)
{
VPC_Input vpc_input;
VPC_ReadLabelFile(3,vpc_input);
cout << "Total image sizes:" << vpc_input.labels[vpc_label].size() << endl;
is_processing = true;
//Read dataset image files
img_files = getFiles(folder);
Mat img_org, img;
qint64 last_time;
//SSG related variables
static vector<vector<NodeSig> > ns_vec; //Stores last tau_w node signatures
static vector<float> coherency_scores_ssg; //Stores all coherency scores
static vector<int> detected_places_unfiltered;
static vector<int> detected_places; //Stores all detected place ids
static SSG temp_SSG(0); temp_SSG.setStartFrame(0);
static TreeNode* hierarchy_tree;
static vector<PlaceSSG> places;
static int frame_count = 0;
last_time = QDateTime::currentMSecsSinceEpoch();
static float ssg_best_coherency_score = 0;
static queue<Mat> img_history;
static queue<Mat> img_resized_history;
int delay = params->seg_track_params.tau_w/2 + params->ssg_params.tau_n;
static queue<int> hist;
//Process all images
for(int frame_no = start_idx; frame_no < end_idx-1; frame_no++)
{
qint64 time = QDateTime::currentMSecsSinceEpoch();
img_org = imread(folder + img_files[frame_no]);
resize(img_org, img, cv::Size(params->ssg_params.img_width, params->ssg_params.img_height));
//Keep last tau_w/2+tau_n images.
img_history.push(img_org);
img_resized_history.push(img);
hist.push(frame_count);
if(img_history.size() > delay)
{
img_history.pop();
img_resized_history.pop(); hist.pop();
}
emit showImgOrg(mat2QImage(img_resized_history.front()));
///////////////
//Process SSG//
///////////////
seg_track->processImage(img, ns_vec);
//Calculate coherency based on existence map
calcCohScore(seg_track, coherency_scores_ssg);
//Show connectivity map
showMap(seg_track->getM());
//Decide last frame is whether transition or place
//Results are written into detected places
int detection_result = detectPlace(coherency_scores_ssg,detected_places_unfiltered,detected_places);
//Plot transition and place regions
plotScoresSSG(coherency_scores_ssg, detected_places, vpc_input.labels[vpc_label]);
//If started for new place
//Create new SSG
if(detection_result == DETECTION_PLACE_STARTED)
{
//Clear SSG
temp_SSG.nodes.clear();
temp_SSG.mean_invariant.release();
temp_SSG.member_invariants.release();
temp_SSG.setId(temp_SSG.getId()+1);
temp_SSG.setStartFrame(frame_no);
Mat map = seg_track->getM();
Mat map_col = map.col(map.size().width - 1 - delay);
vector<NodeSig> ns = ns_vec[ns_vec.size() - 1 - delay];
SSGProc::updateSSG(temp_SSG, ns, map_col);
SSGProc::updateSSGInvariants(temp_SSG, img_history.front(), params);
//Reset coherency score
ssg_best_coherency_score = coherency_scores_ssg.back();
}
else if(detection_result == DETECTION_PLACE_ENDED)
{
temp_SSG.setEndFrame(frame_no);
SSGs.push_back(temp_SSG);
if(temp_SSG.member_invariants.empty() == false)
{
SSGs.push_back(temp_SSG);
}
//qDebug() << "Place detected" << SSGs.size();
}
else if(detection_result == DETECTION_IN_PLACE)
{
temp_SSG.basepoints.push_back(ns_vec.back());
Mat map = seg_track->getM();
Mat map_col = map.col(map.size().width - 1 - delay);
vector<NodeSig> ns = ns_vec[ns_vec.size() - 1 - delay];
SSGProc::updateSSG(temp_SSG, ns, map_col);
//SSGProc::updateSSGInvariants(temp_SSG, img_history.front(), params);
//If current frame is more coherent, set this frame as sample frame of SSG
if(ssg_best_coherency_score < coherency_scores_ssg.back())
{
temp_SSG.setSampleFrame(folder + img_files[frame_no]);
temp_SSG.setColor(dataset_id);
ssg_best_coherency_score = coherency_scores_ssg.back();
}
}
frame_count++;
//Free variables
img.release();
img_org.release();
//Wait a little for GUI processing
waitKey(1);
if(detected_places.size() > 0)
writeDetectedPlace(detected_places.back());
else
writeDetectedPlace(0);
}
compareTransitions(vpc_input, detected_places);
}
void TSCHybrid::processImagesHierarchical(const string folder, const int start_idx, const int end_idx, int dataset_id)
{
VPC_Input vpc_input;
VPC_ReadLabelFile(1,vpc_input);
is_processing = true;
//Read dataset image files
img_files = getFiles(folder);
qDebug() << "dadsa";
Mat img_org, img;
qint64 last_time;
//SSG related variables
static vector<vector<NodeSig> > ns_vec; //Stores last tau_w node signatures
static vector<float> coherency_scores_ssg; //Stores all coherency scores
static vector<int> detected_places_unfiltered;
static vector<int> detected_places; //Stores all detected place ids
static SSG temp_SSG(0); temp_SSG.setStartFrame(0);
static TreeNode* hierarchy_tree;
static vector<PlaceSSG> places;
static int frame_count = 0;
last_time = QDateTime::currentMSecsSinceEpoch();
static float ssg_best_coherency_score = 0;
static queue<Mat> img_history;
static queue<Mat> img_resized_history;
int delay = params->seg_track_params.tau_w/2 + params->ssg_params.tau_n;
static queue<int> hist;
//Create database
DatabaseHandler db;
if(save2database)
{
stringstream ss_db;
ss_db << "conn_db_" << dataset_id;
db.setConnName(ss_db.str());
stringstream ss;
ss << OUTPUT_FOLDER << "dataset_" << dataset_id << "_places.db";
db.openDB(ss.str());
db.createTables();
}
//Process all images
for(int frame_no = start_idx; frame_no < end_idx-1; frame_no++)
{
qint64 time = QDateTime::currentMSecsSinceEpoch();
if(stop_processing)
{
clearPastData();
break;
}
while(next_frame == false)
{
waitKey(1);
}
img_org = imread(folder + img_files[frame_no]);
resize(img_org, img, cv::Size(params->ssg_params.img_width, params->ssg_params.img_height));
//Remove comments if you want to use
//Gokce's segmentation results
//img = segmentImageGokce(img);
//Keep last tau_w/2+tau_n images.
img_history.push(img_org);
img_resized_history.push(img);
hist.push(frame_count);
if(img_history.size() > delay)
{
img_history.pop();
img_resized_history.pop(); hist.pop();
}
emit showImgOrg(mat2QImage(img_resized_history.front()));
///////////////
//Process SSG//
///////////////
seg_track->processImage(img, ns_vec);
//Calculate coherency based on existence map
calcCohScore(seg_track, coherency_scores_ssg);
//Show connectivity map
showMap(seg_track->getM());
//Decide last frame is whether transition or place
//Results are written into detected places
int detection_result = detectPlace(coherency_scores_ssg,detected_places_unfiltered,detected_places);
//cv::Point2f coord = getCoordCold(img_files[dataset->start_idx+detected_places.size()]);
//coords.push_back(coord);
//Plot transition and place regions
//plotScoresSSG(coherency_scores_ssg, detected_places);
//If started for new place
//Create new SSG
if(detection_result == DETECTION_PLACE_STARTED)
{
//Clear SSG
temp_SSG.nodes.clear();
temp_SSG.mean_invariant.release();
temp_SSG.member_invariants.release();
temp_SSG.setId(temp_SSG.getId()+1);
temp_SSG.setStartFrame(frame_no);
Mat map = seg_track->getM();
Mat map_col = map.col(map.size().width - 1 - delay);
vector<NodeSig> ns = ns_vec[ns_vec.size() - 1 - delay];
SSGProc::updateSSG(temp_SSG, ns, map_col);
SSGProc::updateSSGInvariants(temp_SSG, img_history.front(), params);
//Reset coherency score
ssg_best_coherency_score = coherency_scores_ssg.back();
}
else if(detection_result == DETECTION_PLACE_ENDED)
{
temp_SSG.setEndFrame(frame_no);
SSGs.push_back(temp_SSG);
// if(save2database)
// {
// db.insertSSG(temp_SSG);
// }
if(temp_SSG.member_invariants.empty() == false)
{
qint64 timex1 = QDateTime::currentMSecsSinceEpoch();
SSGs.push_back(temp_SSG);
qint64 timex2 = QDateTime::currentMSecsSinceEpoch();
if(save2database)
{
db.insertSSG(temp_SSG);
}
qint64 timex3 = QDateTime::currentMSecsSinceEpoch();
qDebug() << "Place recognized time SSG:" << timex2-timex1 << "DB: " << timex3-timex2;
}
qDebug() << "Place detected" << SSGs.size();
if(perform_recognition)
{
SSGProc::filterSummarySegments(temp_SSG, params->ssg_params.tau_p);
emit showSSG(mat2QImage(SSGProc::drawSSG(temp_SSG, img)));
PlaceSSG new_place(temp_SSG.getId(), temp_SSG);
qint64 last_time = QDateTime::currentMSecsSinceEpoch();
recognition->performRecognition(places, new_place, &hierarchy_tree);
qint64 last_time2 = QDateTime::currentMSecsSinceEpoch();
qDebug() << "Rec time:" << places.size() << (last_time2-last_time)/1000.0;
}
}
else if(detection_result == DETECTION_IN_PLACE)
{
temp_SSG.basepoints.push_back(ns_vec.back());
Mat map = seg_track->getM();
Mat map_col = map.col(map.size().width - 1 - delay);
vector<NodeSig> ns = ns_vec[ns_vec.size() - 1 - delay];
SSGProc::updateSSG(temp_SSG, ns, map_col);
SSGProc::updateSSGInvariants(temp_SSG, img_history.front(), params);
//If current frame is more coherent, set this frame as sample frame of SSG
if(ssg_best_coherency_score < coherency_scores_ssg.back())
{
temp_SSG.setSampleFrame(folder + img_files[frame_no]);
temp_SSG.setColor(dataset_id);
ssg_best_coherency_score = coherency_scores_ssg.back();
}
}
frame_count++;
//Free variables
img.release();
img_org.release();
//Wait a little for GUI processing
waitKey(1);
qint64 time2 = QDateTime::currentMSecsSinceEpoch();
writeFrameSec(time2-time);
if(detected_places.size() > 0)
writeDetectedPlace(detected_places.back());
else
writeDetectedPlace(0);
//qDebug() << frame_no;
//next_frame = false;
}
if(save2database)
{
qDebug() << "Finished creating" << dataset_id << "th" << "dataset in " << (QDateTime::currentMSecsSinceEpoch()-last_time)/1000.0 << "seconds";
db.closeDB();
}
is_processing = false;
stop_processing = false;
compareTransitions(vpc_input, detected_places);
}
void TSCHybrid::TSCPlaces2SSGPlaces(vector<Place>& TSC_places, vector<SSG>& SSG_places)
{
for(int i = 0; i < TSC_places.size(); i++)
{
SSG new_ssg(i);
new_ssg.member_invariants = TSC_places[i].memberInvariants.clone();
new_ssg.mean_invariant = TSC_places[i].meanInvariant.clone();
new_ssg.setStartFrame((int)TSC_places[i].members[0].id);
new_ssg.setEndFrame((int)TSC_places[i].members.back().id);
new_ssg.setColor(TSC_places[i].color);
SSG_places.push_back(new_ssg);
}
}
void TSCHybrid::processImagesHierarchicalTSC(const string folder, const int start_idx, const int end_idx, int dataset_id)
{
is_processing = true;
//Read dataset image files
img_files = getFiles(folder);
Mat img_org, img;
qint64 last_time;
//SSG related variables
static vector<vector<NodeSig> > ns_vec; //Stores last tau_w node signatures
static vector<float> coherency_scores_ssg; //Stores all coherency scores
static vector<int> detected_places_unfiltered;
static vector<int> detected_places; //Stores all detected place ids
static SSG temp_SSG(0); temp_SSG.setStartFrame(0);
static TreeNode* hierarchy_tree = NULL;
static vector<PlaceSSG> places;
//TSC related variables
static vector<float> scores_tsc;
static int frame_count = 0;
last_time = QDateTime::currentMSecsSinceEpoch();
//Process all images
for(int frame_no = start_idx; frame_no < end_idx-1; frame_no++)
{
if(stop_processing)
{
//clearPastData();
//break;
}
while(next_frame == false)
{
waitKey(1);
}
img_org = imread(folder + img_files[frame_no]);
//resize(img_org, img, cv::Size(0,0), IMG_RESCALE_RAT, IMG_RESCALE_RAT);
resize(img_org, img, cv::Size(params->ssg_params.img_width, params->ssg_params.img_height));
//emit showImgOrg(mat2QImage(img));
///////////////
//Process TSC//
///////////////
//Process image
bool isLastImage = frame_no == end_idx-2;
float score = tsc->processImage(img_org, false);
if(isLastImage)
{
if(tsc->detector.currentPlace && tsc->detector.currentPlace->id > 0 && tsc->detector.currentPlace->members.size() > 0)
{
tsc->detector.currentPlace->calculateMeanInvariant();
if(tsc->detector.currentPlace->memberIds.rows >= tsc->detector.tau_p)
{
tsc->detector.detectedPlaces.push_back(*tsc->detector.currentPlace);
tsc->detector.placeID++;
}
}
}
if(tsc->detector.detectedPlaces.size() > 0 && tsc->detector.detectedPlaces.back().color == 0)
{
tsc->detector.detectedPlaces.back().color = dataset_id;
}
scores_tsc.push_back(score);
//Plot TSC scores
if(!isLastImage)
plotScoresTSC_(scores_tsc, tsc->detector.currentPlace, tsc->detector.currentBasePoint, tsc->detector.detectedPlaces);
frame_count++;
if(frame_count%100 == 0)
{
qDebug() << "Time elapsed in 100 frames: " << frame_count << (QDateTime::currentMSecsSinceEpoch() - last_time)/1000.0;
last_time = QDateTime::currentMSecsSinceEpoch();
}
//Free variables
img.release();
img_org.release();
//Wait a little for GUI processing
waitKey(1);
//next_frame = false;
}
//Create database
DatabaseHandler db;
if(save2database)
{
stringstream ss_db;
ss_db << "conn_db_" << dataset_id;
db.setConnName(ss_db.str());
stringstream ss;
ss << OUTPUT_FOLDER << "dataset_bd_" << dataset_id << "_places.db";
db.openDB(ss.str());
db.createTables();
}
vector<SSG> SSGs_fromTSC;
TSCPlaces2SSGPlaces(tsc->detector.detectedPlaces, SSGs_fromTSC);
for(int i = 0; i < SSGs_fromTSC.size(); i++)
{
db.insertSSG(SSGs_fromTSC[i]);
}
db.closeDB();
is_processing = false;
stop_processing = false;
}
void TSCHybrid::reRecognizeInOrderTSCMethod(int method)
{
TreeNode* hierarchy_tree;
vector<PlaceSSG> places;
//TSC places to SSG places conversion
SSGs_fromTSC.clear();
TSCPlaces2SSGPlaces(tsc->detector.detectedPlaces, SSGs_fromTSC);
vector<SSG> SSGs = this->SSGs_fromTSC;
vector<string> image_files = getFiles(dataset->location);
plotDetectedPlaces(SSGs, image_files, dataset);
recognition->setRecognitionMethod(method);
for(int i = 0; i < SSGs.size(); i++)
{
PlaceSSG new_place(SSGs[i].getId(), SSGs[i]);
recognition->performRecognition(places, new_place, &hierarchy_tree);
}
}
void TSCHybrid::reRecognizeInOrder(int method)
{
TreeNode* hierarchy_tree;
vector<PlaceSSG> places;
recognition->setRecognitionMethod(method);
vector<vector<vector<pair<int,int> > > > familiarities;
vector<pair<pair<int,int>, pair<int,int> > > recognized_places;
for(int i = 0; i < SSGs.size(); i++)
{
qint64 last_time = QDateTime::currentMSecsSinceEpoch();
SSG ssg = SSGs[i];
SSGProc::filterSummarySegments(ssg, params->ssg_params.tau_p);
PlaceSSG new_place(SSGs[i].getId(), ssg);
recognition->performRecognitionHybrid(places, new_place, &hierarchy_tree, familiarities);
qint64 last_time2 = QDateTime::currentMSecsSinceEpoch();
qDebug() << last_time2 - last_time;
}
//qDebug() << "N2N Tree Distances:";
//recognition->calculateN2NDistanceMatrix(hierarchy_tree);
//recognition->calculateRecPerformance(hierarchy_tree);
//recognition->calculateFamiliarityPerformance(familiarities);
//recognition->calculateRecPerformance(recognized_places);
//recognition->calculateBDDistanceMatrix(hierarchy_tree);
//recognition->calculateSSGDistanceMatrix(hierarchy_tree);
}
void TSCHybrid::reRecognizeInOrderSecondVisits(int method)
{
TreeNode* hierarchy_tree;
vector<PlaceSSG> places;
recognition->setRecognitionMethod(method);
vector<vector<vector<pair<int,int> > > > familiarities;
vector<pair<pair<int,int>, pair<int,int> > > recognized_places;
for(int i = 0; i < SSGs.size(); i++)
{
SSG ssg = SSGs[i];
SSGProc::filterSummarySegments(ssg, params->ssg_params.tau_p);
PlaceSSG new_place(ssg.getId(), ssg);
places.push_back(new_place);
}
for(int i = 0; i < SSGs_second_visit.size(); i++)
{
SSG ssg = SSGs_second_visit[i];
SSGProc::filterSummarySegments(ssg, params->ssg_params.tau_p);
PlaceSSG new_place(SSGs_second_visit[i].getId(), ssg);
recognition->performRecognitionHybridNoRec(places, new_place, &hierarchy_tree, familiarities, recognized_places);
}
//qDebug() << "N2N Tree Distances:";
//recognition->calculateN2NDistanceMatrix(hierarchy_tree);
//recognition->calculateRecPerformance(hierarchy_tree);
//recognition->calculateFamiliarityPerformance(familiarities);
//recognition->calculateRecPerformance(recognized_places);
recognition->calculateRecPerformanceCombined(recognized_places);
}
void TSCHybrid::reRecognizeBatch(int method)
{
TreeNode* hierarchy_tree;
vector<PlaceSSG> places;
//Plot place in map
vector<string> image_files = getFiles("/home/isl-mahmut/Datasets/lj_seq1_cloudy2/std_cam/");
plotDetectedPlacesBD(SSGs, image_files, dataset);
// recognition->setRecognitionMethod(method);
// int i = 0;
// for(i = 0; i < SSGs.size()-1; i++)
// {
// SSG ssg = SSGs[i];
// SSGProc::filterSummarySegments(ssg, params->ssg_params.tau_p);
// PlaceSSG new_place(ssg.getId(), ssg);
// places.push_back(new_place);
// }
// SSG ssg = SSGs[i];
// SSGProc::filterSummarySegments(ssg, params->ssg_params.tau_p);
// PlaceSSG new_place(ssg.getId(), ssg);
// vector<vector<vector<pair<int,int> > > > familiarities;
// recognition->performRecognitionHybrid(places, new_place, &hierarchy_tree, familiarities);
// //recognition->calculateRecPerformance(places.size(), dist_matrix, hierarchy_tree);
// qDebug() << "N2N";
// recognition->calculateN2NTreeDistanceMatrix(hierarchy_tree);
// qDebug() << "BD";
// recognition->calculateBDDistanceMatrix(hierarchy_tree);
// qDebug() << "SSG";
// recognition->calculateSSGDistanceMatrix(hierarchy_tree);
}
float TSCHybrid::calcCohScore(SegmentTrack* seg_track, vector<float>& coh_scores)
{
Mat M = seg_track->getM();
vector<pair<NodeSig, int> > M_ns = seg_track->getM_ns();
float tau_w = params->seg_track_params.tau_w;
//Wait until at least tau_w frames
if(M.size().width < tau_w)
return 0.0;
//Fill first tau_w frames with zeros
else if(M.size().width == tau_w)
coh_scores.resize(tau_w/2, 0);
int active_nodes = 0;
float coh_score = 0;
float incoherency = 0.0;
float coherency = 0.0;
//Detect each appeared or disappeared node at the last tau_w frame
for(int i = 0; i < M.size().height; i++)
{
//Keeps how long node appeared through window
int nr_appear = 0;
for(int j = M.size().width-tau_w; j < M.size().width-1; j++)
{
//Incoherency: Disappeared node
if(M.at<int>(i, j) == 0 && M.at<int>(i, j+1) > 0)
{
if(M_ns[i].second > params->ssg_params.tau_f)
incoherency += params->ssg_params.coeff_node_disappear1;
else
incoherency += params->ssg_params.coeff_node_disappear2;
}
//Incoherency: Appeared node
if(M.at<int>(i, j) == 0 && M.at<int>(i, j+1) > 0)
{
incoherency += params->ssg_params.coeff_node_appear;
}
//Coherency: Stabile node
if(M.at<int>(i,j) > 0)
nr_appear++;
}
//Active nodes are only the ones that appeared at least one time through window
if(nr_appear > 0)
active_nodes++;