/
recognition.cpp
1640 lines (1324 loc) · 53.1 KB
/
recognition.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 "recognition.h"
#include "utils.h"
#include "utilTypes.h"
#include "segmentation.h"
#include "experimentalData.h"
Recognition::Recognition(Parameters* params,
Dataset* dataset,
GraphMatch* gm,
Segmentation* seg)
{
this->params = params;
this->dataset = dataset;
plot_offset = 150;
//Initialize new graph match and segmentation object
this->gm = gm;
this->seg = seg;
rec_method = REC_TYPE_SSG_NORMAL;
showPlaceAsCircle = true;
showInnerSSGs = false;
}
Recognition::~Recognition()
{
delete seg;
delete gm;
}
void Recognition::setRecognitionMethod(int method)
{
this->rec_method = method;
}
void Recognition::setPlaceDisplayType(int isCircle)
{
this->showPlaceAsCircle = isCircle;
}
void Recognition::setInnerSSGDisplayType(int isShowInnerSSG)
{
this->showInnerSSGs = isShowInnerSSG;
}
//Draws SSGs at terminal nodes
void Recognition::drawSSG(Mat& img, SSG ssg, Point coord)
{
if(coord.y + params->rec_params.ssg_h > img.size().height)
{
copyMakeBorder(img, img, 0, params->rec_params.ssg_h, 0, 0, BORDER_CONSTANT, Scalar(255,255,255));
}
if(showPlaceAsCircle)
{
circle(img,coord,25, getPlaceColor(ssg.getColor()), -1);
//Draw Place ids
stringstream ss;
ss.str("");
ss << ssg.getId();
if(ssg.getId() < 10)
{
Point str_coord(coord.x-10, coord.y+8);
putText(img, ss.str(), str_coord, FONT_HERSHEY_SIMPLEX, 1, Scalar(255,255,255),2);
}
else
{
Point str_coord(coord.x-17, coord.y+8);
putText(img, ss.str(), str_coord, FONT_HERSHEY_SIMPLEX, 1, Scalar(255,255,255),2);
}
// Scalar cat_color = getCategoryColor(getPlaceCategory(ssg.getColor(),ssg.getId()));
// //Draw place cats
// rectangle(img, Point(coord.x-20,40+coord.y-10), Point(coord.x+20,40+coord.y+20),cat_color, CV_FILLED);
// ss.str("");
// ss << getPlaceCategory(ssg.getColor(),ssg.getId());
// Point str_coord(coord.x-10, 40+coord.y+15);
// putText(img, ss.str(), str_coord, FONT_HERSHEY_SIMPLEX, 1, Scalar(255,255,255),2);
}
else
{
Mat img_real = imread(ssg.getSampleFrame());
Mat img_ssg(params->ssg_params.img_height, params->ssg_params.img_width, CV_8UC3, Scalar(255,255,255));
for(int i = 0; i < ssg.nodes.size(); i++)
{
Point p = ssg.nodes[i].first.center;
double r = sqrt(ssg.nodes[i].first.area)/4.0;
r = max(r,1.0);
circle(img_ssg,p,r,Scalar(ssg.nodes[i].first.colorB, ssg.nodes[i].first.colorG, ssg.nodes[i].first.colorR), -1);
}
//Predefined size
resize(img_real, img_real, cv::Size(params->rec_params.ssg_w,params->rec_params.ssg_h));
resize(img_ssg, img_ssg, cv::Size(params->rec_params.ssg_w,params->rec_params.ssg_h));
rectangle(img_real, Rect(0,0,img_real.size().width-1, img_real.size().height-1),Scalar(0,0,0));
rectangle(img_ssg, Rect(0,0,img_ssg.size().width-1, img_ssg.size().height-1),Scalar(0,0,0));
Rect roi = Rect(coord.x-img_real.size().width, coord.y, img_real.size().width, img_real.size().height);
Mat image_roi = img(roi);
img_real.copyTo(image_roi);
Rect roi2 = Rect(coord.x, coord.y, img_ssg.size().width, img_ssg.size().height);
Mat image_roi2 = img(roi2);
img_ssg.copyTo(image_roi2);
stringstream ss;
ss.str("");
ss << ssg.getId();
Point str_coord(coord.x+params->rec_params.ssg_w, coord.y+params->rec_params.ssg_h/2.0);
putText(img, ss.str(), str_coord, FONT_HERSHEY_SIMPLEX, 1, getPlaceColor(ssg.getColor()),2);
circle(img,coord,10, getPlaceColor(ssg.getColor()), -1);
}
}
//Draws SSGs at inner nodes
void Recognition::drawInnerSSG(Mat& img, SSG ssg, Point coord)
{
Mat img_ssg(params->ssg_params.img_height, params->ssg_params.img_width, CV_8UC3, Scalar(255,255,255));
for(int i = 0; i < ssg.nodes.size(); i++)
{
Point p = ssg.nodes[i].first.center;
double r = sqrt(ssg.nodes[i].first.area)/4.0;
r = max(r,1.0);
circle(img_ssg,p,r,Scalar(ssg.nodes[i].first.colorB, ssg.nodes[i].first.colorG, ssg.nodes[i].first.colorR), -1);
}
stringstream ss;
ss.str("");
ss << ssg.getId();
Point str_coord(coord.x+params->rec_params.ssg_w/2, coord.y-3);
putText(img, ss.str(), str_coord, FONT_HERSHEY_SIMPLEX, 1, getPlaceColor(ssg.getColor()),2);
//Predefined size
resize(img_ssg, img_ssg, cv::Size(params->rec_params.ssg_w,params->rec_params.ssg_h));
rectangle(img_ssg, Rect(0,0,img_ssg.size().width-1, img_ssg.size().height-1),Scalar(0,0,0));
Rect roi = Rect(coord.x-img_ssg.size().width/2, coord.y-img_ssg.size().height/2, img_ssg.size().width, img_ssg.size().height);
Mat image_roi = img(roi);
img_ssg.copyTo(image_roi);
}
//Draws SSG at terminal nodes with images
void Recognition::drawSSGWithImages(Mat& img, SSG ssg, Point coord)
{
if(coord.y + params->rec_params.ssg_h > img.size().height)
{
copyMakeBorder(img, img, 0, params->rec_params.ssg_h, 0, 0, BORDER_CONSTANT, Scalar(255,255,255));
}
if(params->rec_params.ssg_w < 10)
{
stringstream ss;
ss.str("");
ss << ssg.getId();
Point str_coord(coord.x-5, coord.y+25);
putText(img, ss.str(), str_coord, FONT_HERSHEY_SIMPLEX, 1, getPlaceColor(ssg.getColor()),2);
circle(img,coord,10, getPlaceColor(ssg.getColor()), -1);
}
else
{
string place_folder = getPlaceFolder(ssg.getColor());
vector<string> img_files = getFiles(place_folder);
int img_index = (ssg.getEndFrame()+ssg.getStartFrame())/2;
Mat img_real = imread(place_folder + img_files[img_index]);
Mat img_ssg(params->ssg_params.img_height, params->ssg_params.img_width, CV_8UC3, Scalar(255,255,255));
for(int i = 0; i < ssg.nodes.size(); i++)
{
Point p = ssg.nodes[i].first.center;
double r = sqrt(ssg.nodes[i].first.area)/4.0;
r = max(r,1.0);
circle(img_ssg,p,r,Scalar(ssg.nodes[i].first.colorB, ssg.nodes[i].first.colorG, ssg.nodes[i].first.colorR), -1);
}
//Predefined size
resize(img_real, img_real, cv::Size(params->rec_params.ssg_w,params->rec_params.ssg_h));
resize(img_ssg, img_ssg, cv::Size(params->rec_params.ssg_w,params->rec_params.ssg_h));
rectangle(img_real, Rect(0,0,img_real.size().width-1, img_real.size().height-1),Scalar(0,0,0));
rectangle(img_ssg, Rect(0,0,img_ssg.size().width-1, img_ssg.size().height-1),Scalar(0,0,0));
Rect roi = Rect(coord.x-img_real.size().width, coord.y, img_real.size().width, img_real.size().height);
Mat image_roi = img(roi);
img_real.copyTo(image_roi);
Rect roi2 = Rect(coord.x, coord.y, img_ssg.size().width, img_ssg.size().height);
Mat image_roi2 = img(roi2);
img_ssg.copyTo(image_roi2);
stringstream ss;
ss.str("");
ss << ssg.getId();
Point str_coord(coord.x+params->rec_params.ssg_w, coord.y+params->rec_params.ssg_h/2.0);
putText(img, ss.str(), str_coord, FONT_HERSHEY_SIMPLEX, 1, getPlaceColor(ssg.getColor()),2);
circle(img,coord,10, getPlaceColor(ssg.getColor()), -1);
}
}
//Draws tree
void Recognition::drawBranch(Mat& img, TreeNode* node, int height, double scale_x, double scale_y)
{
if(!node->isTerminal())
{
for(int i = 0; i < node->getChildren().size(); i++)
{
Point top(plot_offset+node->getXPos()*scale_x, height - plot_offset - 1 - node->getVal()*scale_y);
Point middle(plot_offset+node->getChildren()[i]->getXPos()*scale_x, height - plot_offset - 1 - node->getVal()*scale_y);
Point bottom(plot_offset+node->getChildren()[i]->getXPos()*scale_x, height - plot_offset - 1 - node->getChildren()[i]->getVal()*scale_y);
line(img, top, middle, Scalar(0,0,0), 2);
line(img, middle, bottom, Scalar(0,0,0), 2);
if(showInnerSSGs)
{
Point coord(plot_offset+node->getXPos()*scale_x, height - plot_offset - 1 - node->getVal()*scale_y);
drawInnerSSG(img, node->getDescriptor()->getMember(0), coord);
}
drawBranch(img, node->getChildren()[i], height, scale_x, scale_y);
}
}
else
{
Point coord(plot_offset+node->getXPos()*scale_x, height - plot_offset - 1 - node->getVal()*scale_y);
//Draw Place id
stringstream ss;
ss << node->getLabel();
Point str_coord(coord.x+18, coord.y-18);
//putText(img, ss.str(), str_coord, FONT_HERSHEY_SIMPLEX, 1, Scalar(255,0,0),2);
//Draw SSGs
for(int i = 0; i < node->getDescriptor()->getCount(); i++)
{
Point ssg_coord(coord.x, coord.y + i*params->rec_params.ssg_h);
if(showPlaceAsCircle)
drawSSG(img, node->getDescriptor()->getMember(i), ssg_coord);
else
drawSSGWithImages(img, node->getDescriptor()->getMember(i), ssg_coord);
}
}
}
//Draws resulting tree into image file
void Recognition::drawTree(TreeNode* root_node, int nrPlaces, int height, int width)
{
Mat img(height, width, CV_8UC3, Scalar(255,255,255));
double scale_x = (double) (width - 2*plot_offset) / nrPlaces;
double scale_y = (double) (height - 2*plot_offset) / root_node->getVal();
drawBranch(img, root_node, height, scale_x, scale_y);
emit showTree(mat2QImage(img));
imwrite(string(OUTPUT_FOLDER) + "tree.jpg",img);
waitKey(0);
}
//Returns all terminal nodes originated from given root node
void Recognition::getTerminalNodes(TreeNode* node, vector<TreeNode*>& terminal_nodes)
{
if(node->isTerminal())
{
terminal_nodes.push_back(node);
}
for(int i = 0; i < node->getChildren().size(); i++)
getTerminalNodes(node->getChildren()[i], terminal_nodes);
}
//Sort terminal nodes based on depth-first traversal
//Used for cosmetic purposes of tree drawing
void Recognition::sortTerminalNodes(TreeNode* node, int* last_pos)
{
if(node->isTerminal())
{
node->setXPos((*last_pos)++);
}
for(int i = 0; i < node->getChildren().size(); i++)
sortTerminalNodes(node->getChildren()[i], last_pos);
}
//Experimental
//Calculates merged SSGs at inner nodes using SSGs at children nodes
//Caution! This function will produce memory leak unless places deallocated manually!
PlaceSSG* Recognition::mergeSSGs(PlaceSSG* p1, PlaceSSG* p2, int id)
{
SSG ssg(id);
if(p1->getMember(0).nodes.size() == 0 || p2->getMember(0).nodes.size() == 0)
{
PlaceSSG* place_ssg = new PlaceSSG(id,ssg);
return place_ssg;
}
Mat C, P;
SSG ssg1 = p1->getMember(0);
SSG ssg2 = p2->getMember(0);
vector<pair<NodeSig,int> > ns1 = ssg1.nodes;
vector<pair<NodeSig,int> > ns2 = ssg2.nodes;
gm->matchTwoImages(ssg1, ssg2, P, C);
vector<Point> nonzero_locs;
findNonZero(P,nonzero_locs);
for(int i = 0; i < nonzero_locs.size(); i++)
{
float cost = C.at<float>(nonzero_locs[i].y, nonzero_locs[i].x);
if(cost < params->rec_params.tau_v)
{
NodeSig ns;
cv::Point p =(ns1[nonzero_locs[i].y].first.center+ns2[nonzero_locs[i].x].first.center);
ns.center = cv::Point(p.x/2,p.y/2);
ns.area = (ns1[nonzero_locs[i].y].first.area + ns2[nonzero_locs[i].x].first.area) / 2;
ns.colorR = (ns1[nonzero_locs[i].y].first.colorR + ns2[nonzero_locs[i].x].first.colorR) / 2;
ns.colorG = (ns1[nonzero_locs[i].y].first.colorG + ns2[nonzero_locs[i].x].first.colorG) / 2;
ns.colorB = (ns1[nonzero_locs[i].y].first.colorB + ns2[nonzero_locs[i].x].first.colorB) / 2;
ssg.nodes.push_back(make_pair(ns,1));
}
}
ssg.setColor(ssg1.getColor());
PlaceSSG* place_ssg = new PlaceSSG(0,ssg);
return place_ssg;
}
//Converts tree (Node) produced by SLINK algorithm into tree format(TreeNode) used in this work
//Caution! This may produce memory leaks.. Deallocate tree manually later
TreeNode** Recognition::convert2Tree(Node* tree, int nrNodes, int nrPlaces, vector<PlaceSSG>& places)
{
TreeNode* nodes = new TreeNode[nrPlaces+nrNodes];
for(int i = 0; i < nrPlaces; i++)
{
nodes[i].setLabel(i);
nodes[i].setXPos(i);
nodes[i].setDescriptor(&places[i]);
nodes[i].setVal(0);
}
for(int i = 0; i < nrNodes; i++)
{
nodes[i+nrPlaces].setLabel(i+nrPlaces);
nodes[i+nrPlaces].setVal(tree[i].distance);
nodes[i+nrPlaces].addChild(&nodes[tree[i].left]);
nodes[i+nrPlaces].addChild(&nodes[tree[i].right]);
//set merged ssg for inner nodes
nodes[i+nrPlaces].setDescriptor(mergeSSGs(nodes[tree[i].left].getDescriptor(), nodes[tree[i].right].getDescriptor(), i+nrPlaces));
}
TreeNode* root_node = &nodes[nrPlaces+nrNodes-1];
int x_pos = 0;
sortTerminalNodes(root_node, &x_pos);
for(int i = 0; i < nrNodes; i++)
{
nodes[i+nrPlaces].setXPos((nodes[tree[i].left].getXPos() + nodes[tree[i].right].getXPos() ) / 2.0);
}
return &root_node;
}
//Returns tree node as specified by its place label
//There may be more than one SSG in a place
TreeNode* Recognition::findNodeWithPlaceLabel(int label, TreeNode* root)
{
if(label == root->getLabel())
return root;
//Depth first traversal
for(int i = 0; i < root->getChildren().size(); i++){
TreeNode* p = findNodeWithPlaceLabel(label, root->getChildren()[i]);
if(p != NULL) return p;
}
return NULL;
}
//Returns tree node as specified by its SSG label
//There may be more than one SSG in a place
TreeNode* Recognition::findNodeWithSSGLabel( int site, int label, TreeNode* root)
{
if(root->isTerminal())
{
for(int i = 0; i < root->getDescriptor()->getCount(); i++)
{
if(root->getDescriptor()->getMember(i).getColor() == site && root->getDescriptor()->getMember(i).getId() == label)
{
return root;
}
}
}
//Depth first traversal
for(int i = 0; i < root->getChildren().size(); i++){
TreeNode* p = findNodeWithSSGLabel(site, label, root->getChildren()[i]);
if(p != NULL) return p;
}
return NULL;
}
//SSG Voting based distance between two SSGs
double Recognition::calculateDistanceSSGVoting(SSG& old_place, SSG& detected_place)
{
vector<NodeSig> ns;
double vote = 0;
int count = 0;
//First option
for(int i = 0; i < old_place.nodes.size(); i++)
ns.push_back(old_place.nodes[i].first);
for(int i = 0; i < detected_place.basepoints.size(); i++)
{
Mat P, C;
//voting system
if(gm->matchTwoImages(detected_place.basepoints[i],ns,P,C) < params->rec_params.tau_v)
vote += 1;
count++;
}
vote /= count;
return 1-vote;
}
//Calculates BD-Based distance between two SSG
//Calculation methods can be changed from GUI
double Recognition::calculateDistanceTSC(SSG& old_place, SSG& detected_place)
{
double total_distance = 0;
//Color is not used
if(rec_method == REC_TYPE_BD_NORMAL )
{
int bd_vec_color_idx_start = 0;
int bd_vec_filter_idx_start = 100;
int bd_vec_filter_idx_end = 599;
Mat oldp = old_place.mean_invariant.rowRange(bd_vec_filter_idx_start,bd_vec_filter_idx_end);
Mat newp = detected_place.mean_invariant.rowRange(bd_vec_filter_idx_start,bd_vec_filter_idx_end);
total_distance = norm(oldp, newp);
}
//Color information is used
else if(rec_method == REC_TYPE_BD_COLOR)
{
total_distance = norm(old_place.mean_invariant,detected_place.mean_invariant,NORM_L2);
}
//Hakan calculated log of bd vector -- this condition is used to reverse taking log process
else if(rec_method == REC_TYPE_BD_COLOR_LOG)
{
Mat a = old_place.mean_invariant*25;
float const_eps = 2.71;
cv::pow(a,const_eps,a);
Mat b = detected_place.mean_invariant*25;
cv::pow(b,const_eps,b);
total_distance = norm(a,b,NORM_L2);
}
//voting based
else if(rec_method == REC_TYPE_BD_VOTING)
{
float votes = 0;
for(int i = 0; i < detected_place.member_invariants.size().width; i++)
{
if(norm(old_place.mean_invariant,detected_place.member_invariants.col(i),NORM_L2) < params->rec_params.tau_v)
{
votes += 1;
}
}
if(votes == 0)
total_distance = 1;
else
{
total_distance = votes / detected_place.member_invariants.size().width;
total_distance = 1 - total_distance;
}
}
return total_distance;
}
//Returns distance between two places
//Calculation method is chosen by the user from GUI
double Recognition::getDistance(PlaceSSG& p1, PlaceSSG& p2)
{
int count = 0;
double distance = 0;
for(int i = 0; i < p1.getCount(); i++)
{
for(int j = 0; j < p2.getCount(); j++)
{
if(rec_method == REC_TYPE_SSG_NORMAL)
{
Mat P, C;
distance += gm->matchTwoImages(p1.getMember(i),p2.getMember(j),P,C);
}
else if(rec_method == REC_TYPE_SSG_VOTING)
{
distance += calculateDistanceSSGVoting(p1.getMember(i),p2.getMember(j));
}
else if(rec_method == REC_TYPE_BD_NORMAL || rec_method == REC_TYPE_BD_VOTING || rec_method == REC_TYPE_BD_COLOR)
{
distance += calculateDistanceTSC(p1.getMember(i),p2.getMember(j));
}
count++;
}
}
return distance / count;
}
//Calculates pairwise place distances and return distance matrix
double** Recognition::calculateDistanceMatrix(vector<PlaceSSG>& places)
{
int nrPlaces = places.size();
double** dist_matrix = new double*[nrPlaces];
for (int i = 0; i < nrPlaces; i++)
{
dist_matrix[i] = new double[nrPlaces];
}
for(int r = 0; r < nrPlaces; r++)
{
dist_matrix[r][r] = 0;
for(int c = r+1; c < nrPlaces; c++)
{
double distance = 0;
distance = getDistance(places[r], places[c]);
dist_matrix[r][c] = distance;
dist_matrix[c][r] = distance;
}
}
return dist_matrix;
}
//Performs recognition check for new detected place..
//If new place is recognized, it's merged with the recognized one and tree is not changed(it should be changed actually)
//If new place is not recognized, it's placed into tree using SLINK algorithm
int Recognition::performRecognition(vector<PlaceSSG>& places, PlaceSSG new_place, TreeNode** hierarchy)
{
int recognition_status = NOT_RECOGNIZED;
//TODO: Incremental distance matrix creation
//First create distance matrix (We don't need to calculate distance matrix from scratch)
//We'll push new place into places vector, then erase at the end
places.push_back(new_place);
//If there is not enough place for recognition
if(places.size() < 2)
return RECOGNITION_ERROR;
int nrPlaces = places.size();
//qDebug() << "New recognition calculation...";
double** dist_matrix = calculateDistanceMatrix(places);
//Find hierarchical tree using SLINK algorithm
Node* tree = solveSLink(nrPlaces, nrPlaces, dist_matrix);
*hierarchy = *convert2Tree(tree, nrPlaces-1, nrPlaces, places);
//Draw tree
drawTree(*hierarchy, nrPlaces, params->rec_params.plot_h, params->rec_params.plot_w);
//Get pointer to position of new detected place
TreeNode* new_place_node = findNodeWithPlaceLabel(nrPlaces-1, *hierarchy);
TreeNode* new_place_parent = new_place_node->getParent();
//If new detected place's h is below tau_r perform rec
//Assign it to the most closes terminal node..
if(new_place_parent->getVal() < params->rec_params.tau_r)
{
vector<TreeNode*> terminal_nodes;
getTerminalNodes(new_place_parent, terminal_nodes);
double best_dist = 999;
TreeNode* closest_node = NULL;
for(int i = 0; i < terminal_nodes.size(); i++)
{
if(new_place_node->getLabel() != terminal_nodes[i]->getLabel())
{
double dist = getDistance(*new_place_node->getDescriptor(), *terminal_nodes[i]->getDescriptor());
if(dist < best_dist)
{
best_dist = dist;
closest_node = terminal_nodes[i];
}
}
}
if(closest_node != NULL)
{
qDebug() << "Recognized!" << closest_node->getDescriptor()->getMember(0).getId() << "->" << new_place_node->getDescriptor()->getMember(0).getId();
//qDebug() << "Recognized place! " << closest_node->getLabel() << "<-" << new_place_node->getLabel();
for(int i = 0; i < new_place_node->getDescriptor()->getCount(); i++)
closest_node->getDescriptor()->addMember(new_place_node->getDescriptor()->getMember(i));
places.erase(places.end());
recognition_status = RECOGNIZED;
}
}
//Remove dist_matrix
for (int i = 0; i < nrPlaces; i++) delete[] dist_matrix[i];
delete[] dist_matrix;
return recognition_status;
}
//Performs recognition check for new detected place..
//If new place is recognized, it's merged with the recognized one and tree is not changed(it should be changed actually)
//If new place is not recognized, it's placed into tree using SLINK algorithm
int Recognition::performRecognitionHybridOld(vector<PlaceSSG>& places, PlaceSSG new_place, TreeNode** hierarchy)
{
int recognition_status = NOT_RECOGNIZED;
//TODO: Incremental distance matrix creation
//First create distance matrix (We don't need to calculate distance matrix from scratch)
//We'll push new place into places vector, then erase at the end
places.push_back(new_place);
//Hybrid method
//Calculate best candidates based on SSG method
//BD based recognition will be applied only on these candidates
vector<vector<int> > best_ssg_candidates = calculateBestSSGCandidates(places);
//If there is not enough place for recognition
if(places.size() < 2)
return RECOGNITION_ERROR;
int nrPlaces = places.size();
//qDebug() << "New recognition calculation...";
double** dist_matrix = calculateDistanceMatrix(places);
//Find hierarchical tree using SLINK algorithm
Node* tree = solveSLink(nrPlaces, nrPlaces, dist_matrix);
*hierarchy = *convert2Tree(tree, nrPlaces-1, nrPlaces, places);
//Draw tree
drawTree(*hierarchy, nrPlaces, params->rec_params.plot_h, params->rec_params.plot_w);
//Get pointer to position of new detected place
TreeNode* new_place_node = findNodeWithPlaceLabel(nrPlaces-1, *hierarchy);
TreeNode* new_place_parent = new_place_node->getParent();
//If new detected place's h is below tau_r perform rec
//Assign it to the most closes terminal node..
if(new_place_parent->getVal() < params->rec_params.tau_r)
{
vector<TreeNode*> terminal_nodes;
getTerminalNodes(new_place_parent, terminal_nodes);
double best_dist = 999;
TreeNode* closest_node = NULL;
for(int i = 0; i < terminal_nodes.size(); i++)
{
if(new_place_node->getLabel() != terminal_nodes[i]->getLabel())
{
double dist = getDistance(*new_place_node->getDescriptor(), *terminal_nodes[i]->getDescriptor());
if(dist < best_dist)
{
best_dist = dist;
closest_node = terminal_nodes[i];
}
}
}
if(closest_node != NULL)
{
vector<int> candidates = best_ssg_candidates[new_place_node->getLabel()];
//Check if any of candidates is equal recognized place based on BD method
if(find(candidates.begin(), candidates.end(),closest_node->getLabel()) != candidates.end())
{
qDebug() << "Recognized!" << closest_node->getDescriptor()->getMember(0).getId() << "->" << new_place_node->getDescriptor()->getMember(0).getId();
//qDebug() << "Recognized place! " << closest_node->getLabel() << "<-" << new_place_node->getLabel();
for(int i = 0; i < new_place_node->getDescriptor()->getCount(); i++)
closest_node->getDescriptor()->addMember(new_place_node->getDescriptor()->getMember(i));
places.erase(places.end());
recognition_status = RECOGNIZED;
}
else
{
qDebug() << "Couldn't pass SSG candidates test" << closest_node->getDescriptor()->getMember(0).getId() << "->" << new_place_node->getDescriptor()->getMember(0).getId();
}
}
}
//Remove dist_matrix
for (int i = 0; i < nrPlaces; i++) delete[] dist_matrix[i];
delete[] dist_matrix;
return recognition_status;
}
//Performs recognition check for new detected place..
//If new place is recognized, it's merged with the recognized one and tree is not changed(it should be changed actually)
//If new place is not recognized, it's placed into tree using SLINK algorithm
int Recognition::performRecognitionHybrid(vector<PlaceSSG>& places, PlaceSSG new_place, TreeNode** hierarchy, vector<vector<vector<pair<int, int> > > >& familiarities)
{
int recognition_status = NOT_RECOGNIZED;
//TODO: Incremental distance matrix creation
//First create distance matrix (We don't need to calculate distance matrix from scratch)
//We'll push new place into places vector, then erase at the end
places.push_back(new_place);
//If there is not enough place for recognition
if(places.size() < 2)
return RECOGNITION_ERROR;
int nrPlaces = places.size();
//qDebug() << "New recognition calculation...";
double** dist_matrix = calculateDistanceMatrix(places);
//Find hierarchical tree using SLINK algorithm
Node* tree = solveSLink(nrPlaces, nrPlaces, dist_matrix);
*hierarchy = *convert2Tree(tree, nrPlaces-1, nrPlaces, places);
//Draw tree
drawTree(*hierarchy, nrPlaces, params->rec_params.plot_h, params->rec_params.plot_w);
//Get pointer to position of new detected place
TreeNode* new_place_node = findNodeWithPlaceLabel(nrPlaces-1, *hierarchy);
//Find the ancestor of the detected place which has the highest height but lower than tau_f
TreeNode* highest_ancestor = new_place_node;
while(highest_ancestor->getParent() != NULL && highest_ancestor->getParent()->getVal() < params->rec_params.tau_r)
{
highest_ancestor = highest_ancestor->getParent();
}
//bool containsPair = false;
vector<vector<pair<int,int> > > familiar_nodes;
//If highest_ancestor is not NULL then check its terminal offsprings for recognition
//The familiarity between detected place and terminal offspring nodes is greater than threshold
//Therefore these are the candidate nodes
if(highest_ancestor != NULL && highest_ancestor->getLabel() != new_place_node->getLabel())
{
//Get terminal offspring nodes of highest ancestor
vector<TreeNode*> terminal_nodes;
getTerminalNodes(highest_ancestor, terminal_nodes);
float best_dissimilarity = -1;
TreeNode* closest_node = NULL;
for(int i = 0; i < terminal_nodes.size(); i++)
{
TreeNode* node = terminal_nodes[i];
vector<pair<int, int> > familiar_node_ssgs;
for(int j = 0; j < node->getDescriptor()->getCount(); j++)
{
int site = node->getDescriptor()->getMember(j).getColor();
int id = node->getDescriptor()->getMember(j).getId();
familiar_node_ssgs.push_back(make_pair(site,id));
// bool status = getMatchStatus(node->getDescriptor()->getMember(j).getColor(),
// node->getDescriptor()->getMember(j).getId(),
// new_place_node->getDescriptor()->getMember(0).getColor(),
// new_place_node->getDescriptor()->getMember(0).getId());
// containsPair |= status;
}
familiar_nodes.push_back(familiar_node_ssgs);
if(node->getLabel() != new_place_node->getLabel())
{
//Check at-least-one-common-ssg-node criteria
if(getNumberMatchedSSGNodes(*new_place_node->getDescriptor(), *node->getDescriptor(), params->rec_params.tau_v))
{
float dissimilarity = getDistance(*new_place_node->getDescriptor(), *terminal_nodes[i]->getDescriptor());
if(best_dissimilarity == -1 || dissimilarity < best_dissimilarity )
{
best_dissimilarity = dissimilarity;
closest_node = node;
}
}
}
}
//If closest node is not null, then place is recognized
if(closest_node != NULL)
{
for(int i = 0; i < new_place_node->getDescriptor()->getCount(); i++)
{
closest_node->getDescriptor()->addMember(new_place_node->getDescriptor()->getMember(i));
}
places.erase(places.end());
recognition_status = RECOGNIZED;
}
}
if(new_place_node->getDescriptor()->getMember(0).getColor() == SITE_LJ2)
familiarities.push_back(familiar_nodes);
//Remove dist_matrix
for (int i = 0; i < nrPlaces; i++) delete[] dist_matrix[i];
delete[] dist_matrix;
return recognition_status;
}
//Performs recognition check for new detected place..
//If new place is recognized, it's merged with the recognized one and tree is not changed(it should be changed actually)
//If new place is not recognized, it's placed into tree using SLINK algorithm
int Recognition::performRecognitionHybridNoRec(vector<PlaceSSG>& places, PlaceSSG new_place, TreeNode** hierarchy, vector<vector<vector<pair<int, int> > > >& familiarities,
vector<pair<pair<int,int>, pair<int,int> > >& recognized_places)
{
int recognition_status = NOT_RECOGNIZED;
//TODO: Incremental distance matrix creation
//First create distance matrix (We don't need to calculate distance matrix from scratch)
//We'll push new place into places vector, then erase at the end
places.push_back(new_place);
//If there is not enough place for recognition
if(places.size() < 2)
return RECOGNITION_ERROR;
int nrPlaces = places.size();
//qDebug() << "New recognition calculation...";
double** dist_matrix = calculateDistanceMatrix(places);
//Find hierarchical tree using SLINK algorithm
Node* tree = solveSLink(nrPlaces, nrPlaces, dist_matrix);
*hierarchy = *convert2Tree(tree, nrPlaces-1, nrPlaces, places);
//Draw tree
drawTree(*hierarchy, nrPlaces, params->rec_params.plot_h, params->rec_params.plot_w);
//Get pointer to position of new detected place
TreeNode* new_place_node = findNodeWithPlaceLabel(nrPlaces-1, *hierarchy);
//Find the ancestor of the detected place which has the highest height but lower than tau_f
TreeNode* highest_ancestor = new_place_node;
while(highest_ancestor->getParent() != NULL && highest_ancestor->getParent()->getVal() < params->rec_params.tau_r)
{
highest_ancestor = highest_ancestor->getParent();
}
//bool containsPair = false;
vector<vector<pair<int,int> > > familiar_nodes;
//If highest_ancestor is not NULL then check its terminal offsprings for recognition
//The familiarity between detected place and terminal offspring nodes is greater than threshold
//Therefore these are the candidate nodes
if(highest_ancestor != NULL && highest_ancestor->getLabel() != new_place_node->getLabel())
{
//Get terminal offspring nodes of highest ancestor
vector<TreeNode*> terminal_nodes;
getTerminalNodes(highest_ancestor, terminal_nodes);
float best_dissimilarity = -1;
TreeNode* closest_node = NULL;
for(int i = 0; i < terminal_nodes.size(); i++)
{
TreeNode* node = terminal_nodes[i];
vector<pair<int, int> > familiar_node_ssgs;
for(int j = 0; j < node->getDescriptor()->getCount(); j++)
{
int site = node->getDescriptor()->getMember(j).getColor();
int id = node->getDescriptor()->getMember(j).getId();
familiar_node_ssgs.push_back(make_pair(site,id));
// bool status = getMatchStatus(node->getDescriptor()->getMember(j).getColor(),
// node->getDescriptor()->getMember(j).getId(),
// new_place_node->getDescriptor()->getMember(0).getColor(),
// new_place_node->getDescriptor()->getMember(0).getId());
// containsPair |= status;
}
familiar_nodes.push_back(familiar_node_ssgs);
if(node->getLabel() != new_place_node->getLabel())
{
//Check at-least-one-common-ssg-node criteria
if(getNumberMatchedSSGNodes(*new_place_node->getDescriptor(), *node->getDescriptor(), params->rec_params.tau_v))
{
float dissimilarity = getDistance(*new_place_node->getDescriptor(), *terminal_nodes[i]->getDescriptor());
if(best_dissimilarity == -1 || dissimilarity < best_dissimilarity )
{
best_dissimilarity = dissimilarity;
closest_node = node;
}
}
}
}
//If closest node is not null, then place is recognized
if(closest_node != NULL)
{
for(int i = 0; i < new_place_node->getDescriptor()->getCount(); i++)
{
recognized_places.push_back(make_pair(make_pair(closest_node->getDescriptor()->getMember(0).getColor(), closest_node->getDescriptor()->getMember(0).getId()),
make_pair(new_place_node->getDescriptor()->getMember(0).getColor(), new_place_node->getDescriptor()->getMember(0).getId())));
}
recognition_status = RECOGNIZED;
}
}
// if(new_place_node->getDescriptor()->getMember(0).getColor() == SITE_FR2)
// familiarities.push_back(familiar_nodes);
//Remove dist_matrix
for (int i = 0; i < nrPlaces; i++) delete[] dist_matrix[i];
delete[] dist_matrix;
return recognition_status;
}
//Returns the tree
Node* Recognition::solveSLink(int nrows, int ncols, double** data)
{
Node* tree;
tree = treecluster(nrows, ncols, 0, 0, 0, 0, 'e', 'a', data);
//Pre-process tree