-
Notifications
You must be signed in to change notification settings - Fork 0
/
nanofractal.h
executable file
·1575 lines (1376 loc) · 66.7 KB
/
nanofractal.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Nanofractal is a simplified version of the Aruco Fractal marker.
*
* With this you will be able to detect fractal markers easily. In addition, make use of the potential of fractal
* markers, robust to occlusions and providing information from all corners of the marker (internal and external).
*
* The library detects the predefined fractal markers: https://drive.google.com/file/d/1JO3V-CQIScHu2U_wwKK7kcZ0qteYbSpu/view?usp=sharing
*
* You only need to define the marker you are going to use (FRACTAL_3L_6, FRACTAL_4L_6,...), to create the
* MarkerDetector object. Then call the detect method with the input image as parameter. For example,
* nanofractal::MarkerDetector("FRACTAL_5L_6"); (See Example1).
*
* If you besides the four corners of each detected marker, need all visible corners (also inners corners) of the marker
* you should call the detect method with the image and the 2d/3d point vectors as parameters (See Example2).
*
* Note that the 3d points of the marker are normalized, if you need real 3d information you must indicate the
* size of the marker when you create the detector. For example, nanofractal::MarkerDetector("FRACTAL_3L_6", 0.85);
*
*
*
* // Example1: Fractal marker detection
*
* auto image=cv::imread("image.jpg");
* nanofractal::MarkerDetector TheDetector = nanofractal::MarkerDetector("FRACTAL_5L_6");
* auto markers=TheDetector.detect(image);
* for(const auto &m:markers)
* m.draw(image);
* cv::imwrite("/path/to/out.png",image);
*
*
* //Example2: Fractal marker detection and get 3d/2d correspondences
* auto image=cv::imread("image.jpg");
* nanofractal::MarkerDetector TheDetector = nanofractal::MarkerDetector("FRACTAL_5L_6", 0.85);
* std::vector<cv::Point2f>p2d; std::vector<cv::Point3f>p3d;
* auto markers=TheDetector.detect(image, p3d, p2d);
* //Here you can call solvepnp using p3d and p2d points
* for(auto pt:p2d)
* cv::circle(image,pt,5,cv::Scalar(0,0,255), cv::FILLED);
* for(const auto &m:markers)
* m.draw(image);
* cv::imwrite("/path/to/out.png",image);
*
*
* If you use this file in your research, you must cite:
*
* 1. "Fractal Markers: A New Approach for Long-Range Marker Pose Estimation Under Occlusion,", F. J. Romero-Ramirez,
* R. Muñoz-Salinas and R. Medina-Carnicer, in IEEE Access, vol. 7, pp. 169908-169919, year 2019.
* 2. "Speeded up detection of squared fiducial markers", Francisco J. Romero-Ramirez, Rafael Muñoz-Salinas, Rafael
* Medina-Carnicer, Image and Vision Computing, vol 76, pages 38-47, year 2018.
*
* If you have any further question, please contact fj.romero[at]uco[dot]es
*/
#ifndef _ARUCONanoFractal_H_
#define _ARUCONanoFractal_H_
#define FractalNanoVersion 4
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/calib3d.hpp>
#include <map>
#include <iostream>
#include <vector>
#include <cassert>
#include <cstdint>
#include <limits>
#include <algorithm>
#include <cstring>
/**
* The FractalMarkerDetector class detects fractal markers in the images passed
*
namespace nanofractal{
class FractalMarkerDetector{
public:
//@param fractal_config possible values (FRACTAL_2L_6,FRACTAL_3L_6,FRACTAL_4L_6,FRACTAL_5L_6)
void setParams(std::string config, float markerSize=-1);
inline std::vector<FractalMarker> detect(const cv::Mat &img);
inline std::vector<FractalMarker> detect(const cv::Mat &img, std::vector<cv::Point3f>& p3d,
std::vector<cv::Point2f>& p2d);
};
}
*/
namespace nanofractal {
namespace _private{
namespace picoflann {
struct L2{
template<typename ElementType, typename ElementType2, typename Adapter>
double compute_distance( const ElementType &elema,const ElementType2 &elemb,const Adapter & adapter,int ndims ,double worstDist)const
{
//compute dist
double sqd=0;
for(int i=0;i<ndims;i++) {
double d= adapter(elema,i)-adapter(elemb,i);
sqd+=d*d;
if (sqd>worstDist) return sqd;
}
return sqd;
}
};
template<int DIMS,typename Adapter,typename DistanceType=L2 >
class KdTreeIndex{
public:
/**
*Builds the index using the data passes in your container and the adapter
*/
template<typename Container >
inline void build(const Container &container ){
_index.clear();
_index.reserve(container.size()*2);
_index.dims=DIMS;
_index.nValues=container.size();
//Create root and assign all items
all_indices.resize(container.size());
for(size_t i=0;i<container.size();i++) all_indices[i]=i;
if (container.size()==0) return;
computeBoundingBox<Container>(_index.rootBBox,0,all_indices.size(),container);
_index.push_back(Node());
divideTree<Container>(_index,0,0,all_indices.size(),_index.rootBBox ,container);
}
inline void clear(){
_index.clear();
all_indices.clear();
}
//saves to a stream. Note that the container is not saved!
inline void toStream (std::ostream &str)const;
//reads from an stream. Note that the container is not readed!
inline void fromStream (std::istream &str);
template< typename Type,typename Container >
inline std::vector<std::pair<uint32_t,double> > searchKnn(const Container &container,const Type &val, int nn,bool sorted=true){
std::vector<std::pair<uint32_t,double> > res;
generalSearch<Type,Container>(res,container,val,-1,sorted,nn);
return res;
}
template< typename Type,typename Container >
inline std::vector<std::pair<uint32_t,double> > radiusSearch(const Container &container,const Type &val, double dist,bool sorted=true, int maxNN=-1)const{
std::vector<std::pair<uint32_t,double> > res;
generalSearch< Type,Container>(res,container,val,dist,sorted,maxNN);
return res;
}
template< typename Type,typename Container >
inline void radiusSearch(std::vector<std::pair<uint32_t,double> > &res,const Container &container,const Type &val, double dist,bool sorted=true, int maxNN=-1){
generalSearch<Type,Container>(res,container,val,dist,sorted,maxNN);
}
private:
struct Node{
inline bool isLeaf()const{return _ileft==-1 && _iright==-1;}
inline void setNodesInfo(uint32_t l,uint32_t r){_ileft=l; _iright=r;}
double div_val;
uint16_t col_index;//column index of the feature vector
std::vector<int> idx;
float divhigh,divlow;
int64_t _ileft=-1,_iright=-1;//children
void toStream(std::ostream &str) const;
void fromStream(std::istream &str);
};
typedef std::vector<std::pair<double,double> > BoundingBox;
struct Index:public std::vector<Node>{
BoundingBox rootBBox;
int dims=0;
int nValues=0;//number of elements of the set when call to build
inline void toStream(std::ostream &str)const;
inline void fromStream(std::istream &str);
};
Index _index;
DistanceType _distance;
Adapter adapter;
//next are only used during build
std::vector<uint32_t> all_indices;
int _maxLeafSize=10 ;
//temporal used during creation of the tree
template< typename Container >
void divideTree(Index &index,uint64_t nodeIdx,int startIndex,int endIndex ,BoundingBox &bbox,const Container&container){
// std::cout<<"CREATE="<<startIndex<<"-"<<endIndex<<"|";toStream(std::cout,bbox);
Node &currNode=index[nodeIdx];
int count=endIndex-startIndex;
assert(startIndex<endIndex);
if (count<= _maxLeafSize){
currNode.idx.resize(count);
for(int i=0;i<count;i++)
currNode.idx[i]= all_indices[startIndex+i];
computeBoundingBox<Container>(bbox,startIndex,endIndex,container);
// std::cout<<std::endl;
return;
}
currNode.setNodesInfo( index.size(), index.size()+1);
index.push_back(Node());
int leftNode=index.size()-1;
index.push_back(Node());
int rightNode=index.size()-1;
///SELECT THE COL (DIMENSION) ON WHICH PARTITION IS MADE
if (0){
BoundingBox _bbox;
computeBoundingBox<Container>(_bbox,startIndex,endIndex,container);
// //get the dimension with highest distnaces
double max_spread=-1;
currNode.col_index=0;
for(int i=0;i<DIMS;i++){
double spread=_bbox[i].second-_bbox[i].first;// maxV[i]-minV[i];
if ( spread>max_spread){
max_spread=spread;
currNode.col_index=i;
}
}
//select the split val
double split_val= (bbox[currNode.col_index].first + bbox[currNode.col_index].second) / 2;
if (split_val < _bbox[currNode.col_index].first) currNode.div_val = _bbox[currNode.col_index].first;
else if (split_val > _bbox[currNode.col_index].second ) currNode.div_val = _bbox[currNode.col_index].second ;
else currNode.div_val = split_val;
}
else{
///SELECT THE COL (DIMENSION) ON WHICH PARTITION IS MADE
double var[DIMS],mean[DIMS];
//compute the variance of the features to select the highest one
mean_var_calculate<Container>(startIndex,endIndex, var, mean,container);
currNode.col_index=0;
//select element with highest variance
for(int i=1;i<DIMS;i++)
if (var[i]>var[currNode.col_index]) currNode.col_index=i;
//now sort all indices according to the selected value
currNode.div_val=mean[currNode.col_index];
}
//compute the variance of the features to select the highest one
//now sort all indices according to the selected value
//std::cout<<" CUT FEAT="<<currNode.col_index<< " VAL="<<currNode.div_val<<std::endl;
int lim1,lim2;
planeSplit<Container> ( &all_indices[startIndex],count,currNode.col_index,currNode.div_val,lim1,lim2,container);
int split_index;
if (lim1>count/2) split_index = lim1;
else if (lim2<count/2) split_index = lim2;
else split_index = count/2;
// /* If either list is empty, it means that all remaining features
// * are identical. Split in the middle to maintain a balanced tree.
// */
if ((lim1==count)||(lim2==0)) split_index = count/2;
//create partitions with at least minLeafSize elements
if (_maxLeafSize!=1)
if ( split_index<_maxLeafSize || count-split_index<_maxLeafSize) {
std::sort(all_indices.begin()+ startIndex ,all_indices.begin()+endIndex,[&](const uint32_t &a,const uint32_t&b){
return adapter(container.at(a), currNode.col_index)<adapter(container.at(b),currNode.col_index);
});
split_index=count/2;
currNode.div_val=adapter(container.at(all_indices[startIndex+split_index]),currNode.col_index);
}
// currNode.div_val=_features.ptr<float>(all_indices[split_index])[currNode.col_index];
BoundingBox left_bbox(bbox);
left_bbox[currNode.col_index].second = currNode.div_val;
divideTree<Container>( index,leftNode ,startIndex,startIndex+split_index,left_bbox,container);
left_bbox[currNode.col_index].second = currNode.div_val;
assert(left_bbox[currNode.col_index].second <=currNode.div_val);
BoundingBox right_bbox(bbox);
right_bbox[currNode.col_index].first = currNode.div_val;
divideTree<Container>(index,rightNode,startIndex+split_index,endIndex,right_bbox,container);
currNode.divlow = left_bbox[currNode.col_index].second;
currNode.divhigh = right_bbox[currNode.col_index].first;
assert(currNode.divlow<=currNode.divhigh);
for (int i=0; i<DIMS; ++i) {
bbox[i].first = std::min(left_bbox[i].first, right_bbox[i].first);
bbox[i].second = std::max(left_bbox[i].second, right_bbox[i].second);
}
}
template< typename Container >
void computeBoundingBox (BoundingBox& bbox, int start,int end,const Container&container ){
bbox.resize(DIMS);
for (int i=0; i<DIMS; ++i)
bbox[i].second = bbox[i].first = adapter( container.at( all_indices[start]),i);
for (int k=start+1; k<end; ++k) {
for (int i=0; i<DIMS; ++i) {
float v= adapter( container.at(all_indices[k]),i);
if (v<bbox[i].first) bbox[i].first = v;
if (v>bbox[i].second) bbox[i].second = v;
}
}
}
template< typename Container >
void mean_var_calculate( int startindex, int endIndex, double var[], double mean[],const Container&container){
const int MAX_ELEM_MEAN=100;
//recompute centers
//compute new center
memset(mean,0,sizeof(double)*DIMS);
double sum2[DIMS];
memset(sum2,0,sizeof(double)*DIMS);
//finish when at least MAX_ELEM_MEAN elements computed
int cnt=0;
//std::min(MAX_ELEM_MEAN,endIndex-startindex );
int increment=1;
if ( endIndex-startindex>=2*MAX_ELEM_MEAN) increment=(endIndex-startindex)/MAX_ELEM_MEAN;
for(int i=startindex;i<endIndex;i+=increment) {
for(int c=0;c<DIMS;c++) {
auto val= adapter(container.at(all_indices[i]),c);
mean[c] += val;
sum2[c] += val*val;
}
cnt++;
}
double invcnt=1./double(cnt);
for(int c=0;c<DIMS;c++) {
mean[c]*=invcnt;
var[c]= sum2[c]*invcnt - mean[c]*mean[c];
}
}
/**
* Subdivide the list of points by a plane perpendicular on axe corresponding
* to the 'cutfeat' dimension at 'cutval' position.
*
* On return:
* dataset[ind[0..lim1-1]][cutfeat]<cutval
* dataset[ind[lim1..lim2-1]][cutfeat]==cutval
* dataset[ind[lim2..count]][cutfeat]>cutval
*/
template< typename Container >
void planeSplit(uint32_t* ind, int count, int cutfeat, float cutval, int& lim1, int& lim2,const Container&container){
/* Move vector indices for left subtree to front of list. */
int left = 0;
int right = count-1;
for (;; ) {
while (left<=right && adapter(container.at( ind[left]),cutfeat)<cutval) ++left;
while (left<=right && adapter(container.at( ind[right]),cutfeat)>=cutval) --right;
if (left>right) break;
std::swap(ind[left], ind[right]); ++left; --right;
}
lim1 = left;
right = count-1;
for (;; ) {
while (left<=right && adapter(container.at(ind[left]),cutfeat)<=cutval) ++left;
while (left<=right && adapter(container.at(ind[right]),cutfeat)>cutval) --right;
if (left>right) break;
std::swap(ind[left], ind[right]); ++left; --right;
}
lim2 = left;
}
template< typename Type >
inline double computeInitialDistances(const Type &elem, double dists[ ],const BoundingBox &bbox) const{
float distsq = 0.0;
for (int i = 0; i <DIMS; ++i) {
double elem_i=adapter( elem,i);
if (elem_i < bbox[i].first) {
auto d=elem_i-bbox[i].first;
dists[i] = d*d;// distance_.accum_dist(vec[i], root_bbox_[i].first, i);
distsq += dists[i];
}
if (elem_i > bbox[i].second) {
auto d=elem_i-bbox[i].second;
dists[i] = d*d;//distance_.accum_dist(vec[i], root_bbox_[i].second, i);
distsq += dists[i];
}
}
return distsq;
}
//THe function that does the search in all exact methods
template< typename Type,typename Container>
inline void generalSearch( std::vector<std::pair<uint32_t,double> > &res, const Container&container,const Type &val,double dist,bool sorted=true,uint32_t maxNn=std::numeric_limits<int>::max() )const{
double dists[DIMS];
memset(dists ,0,sizeof(double)*DIMS);
res.clear();
ResultSet hres( res ,maxNn,dist>0?dist*dist:-1.f);
float distsq = computeInitialDistances<Type>(val, dists,_index.rootBBox);
searchExactLevel<Type,Container> (_index,0,val,hres,distsq,dists,1,container);
if (sorted && res.size()>1)
std::sort(res.begin(),res.end(),[](const std::pair<uint32_t,double>&a,const std::pair<uint32_t,double>&b){return a.second<b.second;});
}
//heap having at the top the maximum element
class ResultSet{
public:
std::vector<std::pair<uint32_t,double> > &array;
int maxSize;
double maxValue=std::numeric_limits<double>::max();
bool radius_search=false;
public:
ResultSet( std::vector<std::pair<uint32_t,double> > &data_ref,uint32_t MaxSize=std::numeric_limits<uint32_t>::max(),double MaxV=-1):array(data_ref){
maxSize=MaxSize;
//set value for radius search
if (MaxV>0){
maxValue =MaxV;
radius_search=true;
}
}
inline void push (const std::pair<uint32_t,double> &val)
{
if ( radius_search && val.second<maxValue){
array.push_back(val);
}
else{
if (array.size()>=size_t(maxSize) ) {
//check if the maxium must be replaced by this
if ( val.second<array[0].second){
swap(array.front() ,array.back());
array.pop_back();
if (array.size()> 1) up (0) ;
}
else return;
}
array.push_back(val);
if (array.size()>1) down ( array.size()-1) ;
}
// array_size++;
}
inline double worstDist()const{
if (radius_search)return maxValue;//radius search
else if (array.size()<size_t(maxSize))return std::numeric_limits<double>::max();
return array[0].second;
}
inline double top()const{assert(!array.empty()); return array[0].second;}
private:
inline void down ( size_t index)
{
if(index==0) return;
size_t parentIndex =(index - 1) / 2;
if (array[parentIndex].second< array[ index].second ) {
swap( array[index],array[parentIndex] );
down (parentIndex) ;
}
}
inline void up (size_t index)
{
size_t leftIndex = 2 * index + 1 ;//vl_heap_left_child (index) ;
size_t rightIndex = 2 * index + 2;//vl_heap_right_child (index) ;
/* no childer: stop */
if (leftIndex >= array.size()) return ;
/* only left childer: easy */
if (rightIndex >= array.size()) {
if ( array [ index].second <array[leftIndex].second)
swap ( array [ index], array[leftIndex]) ;
return ;
}
/* both childern */
{
if ( array[ rightIndex].second< array[ leftIndex].second ) {
/* swap with left */
if (array [index].second< array[leftIndex].second ) {
swap ( array [index] , array[leftIndex]) ;
up ( leftIndex) ;
}
} else {
/* swap with right */
if ( array[ index].second < array[rightIndex].second) {
swap ( array[ index], array[rightIndex]) ;
up ( rightIndex) ;
}
}
}
}
};
template< typename Type,typename Container >
inline void searchExactLevel(const Index &index,int64_t nodeIdx,const Type &elem, ResultSet &res, double mindistsq, double dists[ ],double epsError ,const Container &container)const{
const Node &currNode=index[nodeIdx];
if (currNode.isLeaf()){
double worstDist=res.worstDist();
for(size_t i=0;i<currNode.idx.size();i++){
double sqd=_distance.compute_distance(elem,container.at(currNode.idx[i]),adapter,DIMS,worstDist);
if (sqd<worstDist) {
res.push( {currNode.idx[i],sqd});
worstDist=res.worstDist();
}
}
}
else{
double val = adapter( elem, currNode.col_index);
double diff1 = val - currNode.divlow;
double diff2 = val - currNode.divhigh;
uint32_t bestChild;
uint32_t otherChild;
double cut_dist;
if ((diff1+diff2)<0) {
bestChild = currNode._ileft;
otherChild = currNode._iright;
cut_dist = diff2*diff2 ;
}
else {
bestChild = currNode._iright;
otherChild = currNode._ileft;
cut_dist = diff1*diff1;
}
/* Call recursively to search next level down. */
searchExactLevel<Type,Container> (index,bestChild,elem,res, mindistsq, dists ,epsError,container );
float dst = dists[currNode.col_index];
mindistsq = mindistsq + cut_dist - dst;
dists[currNode.col_index] = cut_dist;
if (mindistsq*epsError <=res.worstDist())
searchExactLevel<Type,Container> (index,otherChild,elem,res, mindistsq, dists,epsError,container );
dists[currNode.col_index] = dst;
}
}
};
template<int DIMS,typename AAdapter,typename DistanceType>
void KdTreeIndex<DIMS,AAdapter,DistanceType>::Node::toStream(std::ostream &str) const{
str.write((char*)&div_val,sizeof(div_val));
str.write((char*)&col_index,sizeof(col_index));
str.write((char*)&divhigh,sizeof(divhigh));
str.write((char*)&divlow,sizeof(divlow));
str.write((char*)&_ileft,sizeof(_ileft));
str.write((char*)&_iright,sizeof(_iright));
uint64_t s=idx.size();
str.write((char*)&s,sizeof(s));
str.write((char*)&idx[0],sizeof(idx[0])*idx.size());
}
template<int DIMS,typename AAdapter,typename DistanceType>
void KdTreeIndex<DIMS,AAdapter,DistanceType>::Node::fromStream(std::istream &str){
str.read((char*)&div_val,sizeof(div_val));
str.read((char*)&col_index,sizeof(col_index));
str.read((char*)&divhigh,sizeof(divhigh));
str.read((char*)&divlow,sizeof(divlow));
str.read((char*)&_ileft,sizeof(_ileft));
str.read((char*)&_iright,sizeof(_iright));
uint64_t s;
str.read((char*)&s,sizeof(s));
idx.resize(s);
str.read((char*)&idx[0],sizeof(idx[0])*idx.size());
}
template<int DIMS,typename AAdapter,typename DistanceType>
void KdTreeIndex<DIMS,AAdapter,DistanceType>::Index::toStream(std::ostream &str)const
{
str.write((char*)&dims,sizeof(dims));
str.write((char*)&rootBBox[0],sizeof(rootBBox[0])*dims);
str.write((char*)&nValues,sizeof(nValues));
uint64_t s=std::vector<Node>::size();
str.write((char*)&s,sizeof(s));
for(size_t i=0;i<std::vector<Node>::size();i++) std::vector<Node>::at(i).toStream(str);
}
template<int DIMS,typename AAdapter,typename DistanceType>
void KdTreeIndex<DIMS,AAdapter,DistanceType>::Index::fromStream(std::istream &str){
str.read((char*)&dims,sizeof(dims));
rootBBox.resize(dims);
str.read((char*)&rootBBox[0],sizeof(rootBBox[0])*dims);
str.read((char*)&nValues,sizeof(nValues));
uint64_t s;;
str.read((char*)&s,sizeof(s));
std::vector<Node>::resize(s);
for(size_t i=0;i<std::vector<Node>::size();i++) std::vector<Node>::at(i).fromStream(str);
if (dims!=DIMS && this->size()!=0 && nValues!=0)
throw std::runtime_error("Number of dimensions of the index in the stream is different from the number of dimensions of this");
}
template<int DIMS,typename AAdapter,typename DistanceType>
void KdTreeIndex<DIMS,AAdapter,DistanceType>::toStream (std::ostream &str)const{
_index.toStream(str);
}
template<int DIMS,typename AAdapter,typename DistanceType>
void KdTreeIndex<DIMS,AAdapter,DistanceType>::fromStream(std::istream &str){
_index.fromStream(str);
}
}
struct Homographer{
Homographer(const std::vector<cv::Point2f> & out ){
std::vector<cv::Point2f> in={cv::Point2f(0,0),cv::Point2f(1,0),cv::Point2f(1,1),cv::Point2f(0,1)};
H=cv::getPerspectiveTransform(in, out);
}
cv::Point2f operator()(const cv::Point2f &p){
double *m=H.ptr<double>(0);
double a=m[0]*p.x+m[1]*p.y+m[2];
double b=m[3]*p.x+m[4]*p.y+m[5];
double c=m[6]*p.x+m[7]*p.y+m[8];
return cv::Point2f(a/c,b/c);
}
cv::Mat H;
};
struct PicoFlann_KeyPointAdapter{
inline float operator( )(const cv::KeyPoint &elem, int dim)const { return dim==0?elem.pt.x:elem.pt.y; }
inline float operator( )(const cv::Point2f &elem, int dim)const { return dim==0?elem.x:elem.y; }
};
/* KeyPoints Filter. Delete kpoints with low response and duplicated. */
void kfilter(std::vector<cv::KeyPoint> &kpoints)
{
float minResp = kpoints[0].response;
float maxResp = kpoints[0].response;
for (auto &p:kpoints){
p.size=40;
if(p.response < minResp) minResp = p.response;
if(p.response > maxResp) maxResp = p.response;
}
float thresoldResp = (maxResp - minResp) * 0.20f + minResp;
for(uint32_t xi=0; xi<kpoints.size();xi++)
{
//Erase keypoints with low response (20%)
if(kpoints[xi].response < thresoldResp){
kpoints[xi].size=-1;
continue;
}
//Duplicated keypoints (closer)
for(uint32_t xj=xi+1; xj<kpoints.size();xj++)
{
if(pow(kpoints[xi].pt.x - kpoints[xj].pt.x,2) + pow(kpoints[xi].pt.y - kpoints[xj].pt.y,2) < 100)
{
if(kpoints[xj].response > kpoints[xi].response)
kpoints[xi] = kpoints[xj];
kpoints[xj].size=-1;
}
}
}
kpoints.erase(std::remove_if(kpoints.begin(),kpoints.end(), [](const cv::KeyPoint &kpt){return kpt.size==-1;}), kpoints.end());
}
/*Corners classification*/
void assignClass(const cv::Mat &im, std::vector<cv::KeyPoint>& kpoints, float sizeNorm=0.f, int wsize=5)
{
if(im.type()!=CV_8UC1)
throw std::runtime_error("assignClass Input image must be 8UC1");
int wsizeFull=wsize*2+1;
cv::Mat labels = cv::Mat::zeros(wsize*2+1,wsize*2+1,CV_8UC1);
cv::Mat thresIm=cv::Mat(wsize*2+1,wsize*2+1,CV_8UC1);
for(auto &kp:kpoints)
{
float x = kp.pt.x;
float y = kp.pt.y;
//Convert point range from norm (-size/2, size/2) to (0,imageSize)
if(sizeNorm>0){
x = im.cols * (x/sizeNorm + 0.5f);
y = im.rows * (-y/sizeNorm + 0.5f);
}
x= int(x+0.5f);
y= int(y+0.5f);
cv::Rect r= cv::Rect(x-wsize,y-wsize,wsize*2+1,wsize*2+1);
//Check boundaries
if(r.x<0 || r.x+r.width>im.cols || r.y<0 ||
r.y+r.height>im.rows) continue;
int endX=r.x+r.width;
int endY=r.y+r.height;
uchar minV=255,maxV=0;
for(int y=r.y; y<endY; y++){
const uchar *ptr=im.ptr<uchar>(y);
for(int x=r.x; x<endX; x++)
{
if(minV>ptr[x]) minV=ptr[x];
if(maxV<ptr[x]) maxV=ptr[x];
}
}
if ((maxV-minV) < 25) {
kp.class_id=0;
continue;
}
double thres=(maxV+minV)/2.0;
unsigned int nZ=0;
//count non zero considering the threshold
for(int y=0; y<wsizeFull; y++){
const uchar *ptr=im.ptr<uchar>( r.y+y)+r.x;
uchar *thresPtr= thresIm.ptr<uchar>(y);
for(int x=0; x<wsizeFull; x++){
if( ptr[x]>thres) {
nZ++;
thresPtr[x]=255;
}
else thresPtr[x]=0;
}
}
//set all to zero labels.setTo(cv::Scalar::all(0));
for(int y=0; y<thresIm.rows; y++){
uchar *labelsPtr=labels.ptr<uchar>(y);
for(int x=0; x<thresIm.cols; x++) labelsPtr[x]=0;
}
uchar newLab = 1;
std::map<uchar, uchar> unions;
for(int y=0; y<thresIm.rows; y++){
uchar *thresPtr=thresIm.ptr<uchar>(y);
uchar *labelsPtr=labels.ptr<uchar>(y);
for(int x=0; x<thresIm.cols; x++)
{
uchar reg = thresPtr[x];
uchar lleft_px = 0;
uchar ltop_px = 0;
if(x-1>-1 && reg==thresPtr[x-1])
lleft_px =labelsPtr[x-1];
if(y-1>-1 && reg==thresIm.ptr<uchar>(y-1)[x])
ltop_px = labels.at<uchar>(y-1, x);
if(lleft_px==0 && ltop_px==0)
labelsPtr[x] = newLab++;
else if(lleft_px!=0 && ltop_px!=0)
{
if(lleft_px < ltop_px)
{
labelsPtr[x] = lleft_px;
unions[ltop_px] = lleft_px;
}
else if(lleft_px > ltop_px)
{
labelsPtr[x] = ltop_px;
unions[lleft_px] = ltop_px;
}
//Same
else labelsPtr[x] = ltop_px;
}
else
if(lleft_px!=0) labelsPtr[x] = lleft_px;
else labelsPtr[x] = ltop_px;
}
}
int nc= newLab-1 - unions.size();
if(nc==2)
if(nZ > thresIm.total()-nZ) kp.class_id = 0;
else kp.class_id = 1;
else if (nc > 2)
kp.class_id = 2;
}
}
}
/**
* @brief The Markers that belong to the fractal marker
*/
class FractalMarker : public std::vector<cv::Point2f>
{
public:
FractalMarker(int id, cv::Mat m, std::vector<cv::Point3f> corners, std::vector<int> id_submarkers);
FractalMarker(){};
inline int nBits() { return _M.total(); }
inline cv::Mat mat(){ return _M; }
inline cv::Mat mask(){ return _mask; }
inline std::vector<int> subMarkers(){ return _submarkers; }
void addSubFractalMarker(FractalMarker submarker);
// returns the distance of the marker side
inline float getMarkerSize() const
{
return static_cast<float>(cv::norm(keypts[0].pt - keypts[1].pt));
}
inline std::vector<cv::KeyPoint> getKeypts();
inline void draw(cv::Mat &image,const cv::Scalar color=cv::Scalar(0,0,255))const;
int id;
std::vector<cv::KeyPoint> keypts; //Corners & class. First 4 corners are external
private:
cv::Mat _M;
cv::Mat _mask;
std::vector<int> _submarkers;
};
FractalMarker::FractalMarker(int id, cv::Mat m, std::vector<cv::Point3f> corners, std::vector<int> id_submarkers)
{
this->id = id;
this->_M = m;
for(auto pt:corners)
keypts.push_back(cv::KeyPoint(pt.x,pt.y,-1,-1,-1,-1,0));
_submarkers = id_submarkers;
_mask = cv::Mat::ones(m.size(), CV_8UC1);
}
std::vector<cv::KeyPoint> FractalMarker::getKeypts()
{
if(keypts.size() > 4) return keypts;
int nBitsSquared = int(sqrt(mat().total()));
float bitSize = getMarkerSize() / (nBitsSquared+2);
//Set submarker pixels (=1) and add border
cv::Mat marker;
mat().copyTo(marker);
marker += -1 * (mask()-1);
cv::Mat markerBorder;
copyMakeBorder(marker, markerBorder, 1,1,1,1,cv::BORDER_CONSTANT,0);
//Get inner corners
for(int y=0; y< markerBorder.rows-1; y++)
{
for(int x=0; x< markerBorder.cols-1; x++)
{
int sum = markerBorder.at<uchar>(y, x) + markerBorder.at<uchar>(y, x+1) +
markerBorder.at<uchar>(y+1, x) + markerBorder.at<uchar>(y+1, x+1);
if(sum==1)
keypts.push_back(cv::KeyPoint(cv::Point2f(x-nBitsSquared/2.f,-(y-nBitsSquared/2.f))*bitSize,-1,-1,-1,-1,1));
else if(sum==3)
keypts.push_back(cv::KeyPoint(cv::Point2f(x-nBitsSquared/2.f,-(y-nBitsSquared/2.f))*bitSize,-1,-1,-1,-1,0));
else if(sum==2)
{
if((markerBorder.at<uchar>(y, x) == markerBorder.at<uchar>(y+1, x+1)) && (markerBorder.at<uchar>(y, x+1) == markerBorder.at<uchar>(y+1, x)))
keypts.push_back(cv::KeyPoint(cv::Point2f(x-nBitsSquared/2.f,-(y-nBitsSquared/2.f))*bitSize,-1,-1,-1,-1,2));
}
}
}
return keypts;
}
void FractalMarker::addSubFractalMarker(FractalMarker submarker)
{
int nBitsSqrt= sqrt(nBits());
float bitSize = getMarkerSize() / (nBitsSqrt+2.0f);
float nsubBits = submarker.getMarkerSize() / bitSize;
int x_min = int(round(submarker.keypts[0].pt.x / bitSize + nBitsSqrt/2));
int x_max = x_min + nsubBits;
int y_min = int(round(-submarker.keypts[0].pt.y / bitSize + nBitsSqrt/2));
int y_max = y_min + nsubBits;
for(int y=y_min; y<y_max; y++){
for(int x=x_min; x<x_max; x++){
_mask.at<uchar>(y,x)=0;
}
}
}
void FractalMarker::draw(cv::Mat &in, const cv::Scalar color) const{
float flineWidth= std::max(1.f, std::min(5.f, float(in.cols) / 500.f));
int lineWidth= round( flineWidth);
for(int i=0;i<4;i++)
cv::line(in, (*this)[i], (*this)[(i+1 )%4], color, lineWidth);
auto p2 = cv::Point2f(2.f * static_cast<float>(lineWidth), 2.f * static_cast<float>(lineWidth));
cv::rectangle(in, (*this)[0] - p2, (*this)[0] + p2, cv::Scalar(0, 0, 255, 255), -1);
cv::rectangle(in, (*this)[1] - p2, (*this)[1] + p2, cv::Scalar(0, 255, 0, 255), lineWidth);
cv::rectangle(in, (*this)[2] - p2, (*this)[2] + p2, cv::Scalar(255, 0, 0, 255), lineWidth);
}
/**
* @brief The FractalMarkerSet configurations
*/
class FractalMarkerSet
{
public:
FractalMarkerSet(){};
FractalMarkerSet(std::string config);
void convertToMeters(float size);
//Fractal configuration. id_marker
std::map<int, FractalMarker> fractalMarkerCollection;
//Correspondence number of bits and marker ids
std::map<int, std::vector<int>> bits_ids;
// variable indicates if the data is expressed in meters or in pixels or are normalized
int mInfoType;/* -1:NONE, 0:PIX, 1:METERS, 2:NORMALIZE*/
int idExternal;
};
void FractalMarkerSet::convertToMeters(float size)
{
if (!(mInfoType == 0 || mInfoType == 2))
throw std::runtime_error("The FractalMarkers are not expressed in pixels or normalized");
mInfoType = 1;
// now, get the size of a pixel, and change scale
float pixSizeM = size / float(fractalMarkerCollection[idExternal].getMarkerSize());
for (size_t i=0; i < fractalMarkerCollection.size(); i++)
for(auto &kpt:fractalMarkerCollection[i].keypts)
kpt.pt *= pixSizeM;
}
FractalMarkerSet::FractalMarkerSet(std::string str)
{
std::stringstream stream;
if (str=="FRACTAL_2L_6")
{
unsigned char _conf_2L_6[] = {
0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xbf,
0x00, 0x00, 0x80, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3f,
0x00, 0x00, 0x80, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3f,
0x00, 0x00, 0x80, 0xbf, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xbf,
0x00, 0x00, 0x80, 0xbf, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00,
0x01, 0x01, 0x00, 0x01, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x00, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x00,
0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01,
0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x01, 0x00,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,
0x01, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x24, 0x00, 0x00, 0x00, 0xab, 0xaa, 0xaa, 0xbe, 0xab, 0xaa, 0xaa, 0x3e,
0x00, 0x00, 0x00, 0x00, 0xab, 0xaa, 0xaa, 0x3e, 0xab, 0xaa, 0xaa, 0x3e,
0x00, 0x00, 0x00, 0x00, 0xab, 0xaa, 0xaa, 0x3e, 0xab, 0xaa, 0xaa, 0xbe,
0x00, 0x00, 0x00, 0x00, 0xab, 0xaa, 0xaa, 0xbe, 0xab, 0xaa, 0xaa, 0xbe,
0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0x01,
0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01, 0x01,
0x00, 0x01, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x01,
0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00
};
unsigned int _conf_2L_6_len = 272;
stream.write((char*) _conf_2L_6, sizeof(unsigned char)*_conf_2L_6_len);
}
else if (str=="FRACTAL_3L_6")
{
unsigned char _conf_3L_6[] = {
0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xbf,
0x00, 0x00, 0x80, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3f,
0x00, 0x00, 0x80, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3f,
0x00, 0x00, 0x80, 0xbf, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xbf,
0x00, 0x00, 0x80, 0xbf, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00,
0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, 0x01, 0x00, 0x01, 0x00, 0x00,
0x00, 0x01, 0x00, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x01, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x01, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x01, 0x00, 0x01, 0x01,
0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01, 0x00,
0x01, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00,
0xb7, 0x6d, 0xdb, 0xbe, 0xb7, 0x6d, 0xdb, 0x3e, 0x00, 0x00, 0x00, 0x00,
0xb7, 0x6d, 0xdb, 0x3e, 0xb7, 0x6d, 0xdb, 0x3e, 0x00, 0x00, 0x00, 0x00,
0xb7, 0x6d, 0xdb, 0x3e, 0xb7, 0x6d, 0xdb, 0xbe, 0x00, 0x00, 0x00, 0x00,
0xb7, 0x6d, 0xdb, 0xbe, 0xb7, 0x6d, 0xdb, 0xbe, 0x00, 0x00, 0x00, 0x00,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01,