forked from opencv/opencv
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcirclesgrid.cpp
More file actions
1617 lines (1416 loc) · 48 KB
/
circlesgrid.cpp
File metadata and controls
1617 lines (1416 loc) · 48 KB
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
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "precomp.hpp"
#include "circlesgrid.hpp"
#include <limits>
//#define DEBUG_CIRCLES
#ifdef DEBUG_CIRCLES
# include <iostream>
# include "opencv2/opencv_modules.hpp"
# ifdef HAVE_OPENCV_HIGHGUI
# include "opencv2/highgui.hpp"
# else
# undef DEBUG_CIRCLES
# endif
#endif
using namespace cv;
#ifdef DEBUG_CIRCLES
void drawPoints(const std::vector<Point2f> &points, Mat &outImage, int radius = 2, Scalar color = Scalar::all(255), int thickness = -1)
{
for(size_t i=0; i<points.size(); i++)
{
circle(outImage, points[i], radius, color, thickness);
}
}
#endif
void CirclesGridClusterFinder::hierarchicalClustering(const std::vector<Point2f> &points, const Size &patternSz, std::vector<Point2f> &patternPoints)
{
#ifdef HAVE_TEGRA_OPTIMIZATION
if(tegra::useTegra() && tegra::hierarchicalClustering(points, patternSz, patternPoints))
return;
#endif
int j, n = (int)points.size();
size_t pn = static_cast<size_t>(patternSz.area());
patternPoints.clear();
if (pn >= points.size())
{
if (pn == points.size())
patternPoints = points;
return;
}
Mat dists(n, n, CV_32FC1, Scalar(0));
Mat distsMask(dists.size(), CV_8UC1, Scalar(0));
for(int i = 0; i < n; i++)
{
for(j = i+1; j < n; j++)
{
dists.at<float>(i, j) = (float)norm(points[i] - points[j]);
distsMask.at<uchar>(i, j) = 255;
//TODO: use symmetry
distsMask.at<uchar>(j, i) = 255;//distsMask.at<uchar>(i, j);
dists.at<float>(j, i) = dists.at<float>(i, j);
}
}
std::vector<std::list<size_t> > clusters(points.size());
for(size_t i=0; i<points.size(); i++)
{
clusters[i].push_back(i);
}
int patternClusterIdx = 0;
while(clusters[patternClusterIdx].size() < pn)
{
Point minLoc;
minMaxLoc(dists, 0, 0, &minLoc, 0, distsMask);
int minIdx = std::min(minLoc.x, minLoc.y);
int maxIdx = std::max(minLoc.x, minLoc.y);
distsMask.row(maxIdx).setTo(0);
distsMask.col(maxIdx).setTo(0);
Mat tmpRow = dists.row(minIdx);
Mat tmpCol = dists.col(minIdx);
cv::min(dists.row(minLoc.x), dists.row(minLoc.y), tmpRow);
tmpRow.copyTo(tmpCol);
clusters[minIdx].splice(clusters[minIdx].end(), clusters[maxIdx]);
patternClusterIdx = minIdx;
}
//the largest cluster can have more than pn points -- we need to filter out such situations
if(clusters[patternClusterIdx].size() != static_cast<size_t>(patternSz.area()))
{
return;
}
patternPoints.reserve(clusters[patternClusterIdx].size());
for(std::list<size_t>::iterator it = clusters[patternClusterIdx].begin(); it != clusters[patternClusterIdx].end();++it)
{
patternPoints.push_back(points[*it]);
}
}
void CirclesGridClusterFinder::findGrid(const std::vector<cv::Point2f> &points, cv::Size _patternSize, std::vector<Point2f>& centers)
{
patternSize = _patternSize;
centers.clear();
if(points.empty())
{
return;
}
std::vector<Point2f> patternPoints;
hierarchicalClustering(points, patternSize, patternPoints);
if(patternPoints.empty())
{
return;
}
#ifdef DEBUG_CIRCLES
Mat patternPointsImage(1024, 1248, CV_8UC1, Scalar(0));
drawPoints(patternPoints, patternPointsImage);
imshow("pattern points", patternPointsImage);
#endif
std::vector<Point2f> hull2f;
convexHull(Mat(patternPoints), hull2f, false);
const size_t cornersCount = isAsymmetricGrid ? 6 : 4;
if(hull2f.size() < cornersCount)
return;
std::vector<Point2f> corners;
findCorners(hull2f, corners);
if(corners.size() != cornersCount)
return;
std::vector<Point2f> outsideCorners, sortedCorners;
if(isAsymmetricGrid)
{
findOutsideCorners(corners, outsideCorners);
const size_t outsideCornersCount = 2;
if(outsideCorners.size() != outsideCornersCount)
return;
}
getSortedCorners(hull2f, corners, outsideCorners, sortedCorners);
if(sortedCorners.size() != cornersCount)
return;
std::vector<Point2f> rectifiedPatternPoints;
rectifyPatternPoints(patternPoints, sortedCorners, rectifiedPatternPoints);
if(patternPoints.size() != rectifiedPatternPoints.size())
return;
parsePatternPoints(patternPoints, rectifiedPatternPoints, centers);
}
void CirclesGridClusterFinder::findCorners(const std::vector<cv::Point2f> &hull2f, std::vector<cv::Point2f> &corners)
{
//find angles (cosines) of vertices in convex hull
std::vector<float> angles;
for(size_t i=0; i<hull2f.size(); i++)
{
Point2f vec1 = hull2f[(i+1) % hull2f.size()] - hull2f[i % hull2f.size()];
Point2f vec2 = hull2f[(i-1 + static_cast<int>(hull2f.size())) % hull2f.size()] - hull2f[i % hull2f.size()];
float angle = (float)(vec1.ddot(vec2) / (norm(vec1) * norm(vec2)));
angles.push_back(angle);
}
//sort angles by cosine
//corners are the most sharp angles (6)
Mat anglesMat = Mat(angles);
Mat sortedIndices;
sortIdx(anglesMat, sortedIndices, SORT_EVERY_COLUMN + SORT_DESCENDING);
CV_Assert(sortedIndices.type() == CV_32SC1);
CV_Assert(sortedIndices.cols == 1);
const int cornersCount = isAsymmetricGrid ? 6 : 4;
Mat cornersIndices;
cv::sort(sortedIndices.rowRange(0, cornersCount), cornersIndices, SORT_EVERY_COLUMN + SORT_ASCENDING);
corners.clear();
for(int i=0; i<cornersCount; i++)
{
corners.push_back(hull2f[cornersIndices.at<int>(i, 0)]);
}
}
void CirclesGridClusterFinder::findOutsideCorners(const std::vector<cv::Point2f> &corners, std::vector<cv::Point2f> &outsideCorners)
{
CV_Assert(!corners.empty());
outsideCorners.clear();
//find two pairs of the most nearest corners
int i, j, n = (int)corners.size();
#ifdef DEBUG_CIRCLES
Mat cornersImage(1024, 1248, CV_8UC1, Scalar(0));
drawPoints(corners, cornersImage);
imshow("corners", cornersImage);
#endif
std::vector<Point2f> tangentVectors(corners.size());
for(size_t k=0; k<corners.size(); k++)
{
Point2f diff = corners[(k + 1) % corners.size()] - corners[k];
tangentVectors[k] = diff * (1.0f / norm(diff));
}
//compute angles between all sides
Mat cosAngles(n, n, CV_32FC1, 0.0f);
for(i = 0; i < n; i++)
{
for(j = i + 1; j < n; j++)
{
float val = fabs(tangentVectors[i].dot(tangentVectors[j]));
cosAngles.at<float>(i, j) = val;
cosAngles.at<float>(j, i) = val;
}
}
//find two parallel sides to which outside corners belong
Point maxLoc;
minMaxLoc(cosAngles, 0, 0, 0, &maxLoc);
const int diffBetweenFalseLines = 3;
if(abs(maxLoc.x - maxLoc.y) == diffBetweenFalseLines)
{
cosAngles.row(maxLoc.x).setTo(0.0f);
cosAngles.col(maxLoc.x).setTo(0.0f);
cosAngles.row(maxLoc.y).setTo(0.0f);
cosAngles.col(maxLoc.y).setTo(0.0f);
minMaxLoc(cosAngles, 0, 0, 0, &maxLoc);
}
#ifdef DEBUG_CIRCLES
Mat linesImage(1024, 1248, CV_8UC1, Scalar(0));
line(linesImage, corners[maxLoc.y], corners[(maxLoc.y + 1) % n], Scalar(255));
line(linesImage, corners[maxLoc.x], corners[(maxLoc.x + 1) % n], Scalar(255));
imshow("lines", linesImage);
#endif
int maxIdx = std::max(maxLoc.x, maxLoc.y);
int minIdx = std::min(maxLoc.x, maxLoc.y);
const int bigDiff = 4;
if(maxIdx - minIdx == bigDiff)
{
minIdx += n;
std::swap(maxIdx, minIdx);
}
if(maxIdx - minIdx != n - bigDiff)
{
return;
}
int outsidersSegmentIdx = (minIdx + maxIdx) / 2;
outsideCorners.push_back(corners[outsidersSegmentIdx % n]);
outsideCorners.push_back(corners[(outsidersSegmentIdx + 1) % n]);
#ifdef DEBUG_CIRCLES
drawPoints(outsideCorners, cornersImage, 2, Scalar(128));
imshow("corners", cornersImage);
#endif
}
void CirclesGridClusterFinder::getSortedCorners(const std::vector<cv::Point2f> &hull2f, const std::vector<cv::Point2f> &corners, const std::vector<cv::Point2f> &outsideCorners, std::vector<cv::Point2f> &sortedCorners)
{
Point2f firstCorner;
if(isAsymmetricGrid)
{
Point2f center = std::accumulate(corners.begin(), corners.end(), Point2f(0.0f, 0.0f));
center *= 1.0 / corners.size();
std::vector<Point2f> centerToCorners;
for(size_t i=0; i<outsideCorners.size(); i++)
{
centerToCorners.push_back(outsideCorners[i] - center);
}
//TODO: use CirclesGridFinder::getDirection
float crossProduct = centerToCorners[0].x * centerToCorners[1].y - centerToCorners[0].y * centerToCorners[1].x;
//y axis is inverted in computer vision so we check > 0
bool isClockwise = crossProduct > 0;
firstCorner = isClockwise ? outsideCorners[1] : outsideCorners[0];
}
else
{
firstCorner = corners[0];
}
std::vector<Point2f>::const_iterator firstCornerIterator = std::find(hull2f.begin(), hull2f.end(), firstCorner);
sortedCorners.clear();
for(std::vector<Point2f>::const_iterator it = firstCornerIterator; it != hull2f.end();++it)
{
std::vector<Point2f>::const_iterator itCorners = std::find(corners.begin(), corners.end(), *it);
if(itCorners != corners.end())
{
sortedCorners.push_back(*it);
}
}
for(std::vector<Point2f>::const_iterator it = hull2f.begin(); it != firstCornerIterator;++it)
{
std::vector<Point2f>::const_iterator itCorners = std::find(corners.begin(), corners.end(), *it);
if(itCorners != corners.end())
{
sortedCorners.push_back(*it);
}
}
if(!isAsymmetricGrid)
{
double dist1 = norm(sortedCorners[0] - sortedCorners[1]);
double dist2 = norm(sortedCorners[1] - sortedCorners[2]);
if((dist1 > dist2 && patternSize.height > patternSize.width) || (dist1 < dist2 && patternSize.height < patternSize.width))
{
for(size_t i=0; i<sortedCorners.size()-1; i++)
{
sortedCorners[i] = sortedCorners[i+1];
}
sortedCorners[sortedCorners.size() - 1] = firstCorner;
}
}
}
void CirclesGridClusterFinder::rectifyPatternPoints(const std::vector<cv::Point2f> &patternPoints, const std::vector<cv::Point2f> &sortedCorners, std::vector<cv::Point2f> &rectifiedPatternPoints)
{
//indices of corner points in pattern
std::vector<Point> trueIndices;
trueIndices.push_back(Point(0, 0));
trueIndices.push_back(Point(patternSize.width - 1, 0));
if(isAsymmetricGrid)
{
trueIndices.push_back(Point(patternSize.width - 1, 1));
trueIndices.push_back(Point(patternSize.width - 1, patternSize.height - 2));
}
trueIndices.push_back(Point(patternSize.width - 1, patternSize.height - 1));
trueIndices.push_back(Point(0, patternSize.height - 1));
std::vector<Point2f> idealPoints;
for(size_t idx=0; idx<trueIndices.size(); idx++)
{
int i = trueIndices[idx].y;
int j = trueIndices[idx].x;
if(isAsymmetricGrid)
{
idealPoints.push_back(Point2f((2*j + i % 2)*squareSize, i*squareSize));
}
else
{
idealPoints.push_back(Point2f(j*squareSize, i*squareSize));
}
}
Mat homography = findHomography(Mat(sortedCorners), Mat(idealPoints), 0);
Mat rectifiedPointsMat;
transform(patternPoints, rectifiedPointsMat, homography);
rectifiedPatternPoints.clear();
convertPointsFromHomogeneous(rectifiedPointsMat, rectifiedPatternPoints);
}
void CirclesGridClusterFinder::parsePatternPoints(const std::vector<cv::Point2f> &patternPoints, const std::vector<cv::Point2f> &rectifiedPatternPoints, std::vector<cv::Point2f> ¢ers)
{
#ifndef HAVE_OPENCV_FLANN
(void)patternPoints;
(void)rectifiedPatternPoints;
(void)centers;
CV_Error(Error::StsNotImplemented, "The desired functionality requires flann module, which was disabled.");
#else
flann::LinearIndexParams flannIndexParams;
flann::Index flannIndex(Mat(rectifiedPatternPoints).reshape(1), flannIndexParams);
centers.clear();
for( int i = 0; i < patternSize.height; i++ )
{
for( int j = 0; j < patternSize.width; j++ )
{
Point2f idealPt;
if(isAsymmetricGrid)
idealPt = Point2f((2*j + i % 2)*squareSize, i*squareSize);
else
idealPt = Point2f(j*squareSize, i*squareSize);
Mat query(1, 2, CV_32F, &idealPt);
const int knn = 1;
int indicesbuf[knn] = {0};
float distsbuf[knn] = {0.f};
Mat indices(1, knn, CV_32S, &indicesbuf);
Mat dists(1, knn, CV_32F, &distsbuf);
flannIndex.knnSearch(query, indices, dists, knn, flann::SearchParams());
centers.push_back(patternPoints.at(indicesbuf[0]));
if(distsbuf[0] > maxRectifiedDistance)
{
#ifdef DEBUG_CIRCLES
std::cout << "Pattern not detected: too large rectified distance" << std::endl;
#endif
centers.clear();
return;
}
}
}
#endif
}
Graph::Graph(size_t n)
{
for (size_t i = 0; i < n; i++)
{
addVertex(i);
}
}
bool Graph::doesVertexExist(size_t id) const
{
return (vertices.find(id) != vertices.end());
}
void Graph::addVertex(size_t id)
{
CV_Assert( !doesVertexExist( id ) );
vertices.insert(std::pair<size_t, Vertex> (id, Vertex()));
}
void Graph::addEdge(size_t id1, size_t id2)
{
CV_Assert( doesVertexExist( id1 ) );
CV_Assert( doesVertexExist( id2 ) );
vertices[id1].neighbors.insert(id2);
vertices[id2].neighbors.insert(id1);
}
void Graph::removeEdge(size_t id1, size_t id2)
{
CV_Assert( doesVertexExist( id1 ) );
CV_Assert( doesVertexExist( id2 ) );
vertices[id1].neighbors.erase(id2);
vertices[id2].neighbors.erase(id1);
}
bool Graph::areVerticesAdjacent(size_t id1, size_t id2) const
{
Vertices::const_iterator it = vertices.find(id1);
CV_Assert(it != vertices.end());
const Neighbors & neighbors = it->second.neighbors;
return neighbors.find(id2) != neighbors.end();
}
size_t Graph::getVerticesCount() const
{
return vertices.size();
}
size_t Graph::getDegree(size_t id) const
{
Vertices::const_iterator it = vertices.find(id);
CV_Assert( it != vertices.end() );
return it->second.neighbors.size();
}
void Graph::floydWarshall(cv::Mat &distanceMatrix, int infinity) const
{
const int edgeWeight = 1;
const int n = (int)getVerticesCount();
distanceMatrix.create(n, n, CV_32SC1);
distanceMatrix.setTo(infinity);
for (Vertices::const_iterator it1 = vertices.begin(); it1 != vertices.end();++it1)
{
distanceMatrix.at<int> ((int)it1->first, (int)it1->first) = 0;
for (Neighbors::const_iterator it2 = it1->second.neighbors.begin(); it2 != it1->second.neighbors.end();++it2)
{
CV_Assert( it1->first != *it2 );
distanceMatrix.at<int> ((int)it1->first, (int)*it2) = edgeWeight;
}
}
for (Vertices::const_iterator it1 = vertices.begin(); it1 != vertices.end();++it1)
{
for (Vertices::const_iterator it2 = vertices.begin(); it2 != vertices.end();++it2)
{
for (Vertices::const_iterator it3 = vertices.begin(); it3 != vertices.end();++it3)
{
int i1 = (int)it1->first, i2 = (int)it2->first, i3 = (int)it3->first;
int val1 = distanceMatrix.at<int> (i2, i3);
int val2;
if (distanceMatrix.at<int> (i2, i1) == infinity ||
distanceMatrix.at<int> (i1, i3) == infinity)
val2 = val1;
else
{
val2 = distanceMatrix.at<int> (i2, i1) + distanceMatrix.at<int> (i1, i3);
}
distanceMatrix.at<int> (i2, i3) = (val1 == infinity) ? val2 : std::min(val1, val2);
}
}
}
}
const Graph::Neighbors& Graph::getNeighbors(size_t id) const
{
Vertices::const_iterator it = vertices.find(id);
CV_Assert( it != vertices.end() );
return it->second.neighbors;
}
CirclesGridFinder::Segment::Segment(cv::Point2f _s, cv::Point2f _e) :
s(_s), e(_e)
{
}
void computeShortestPath(Mat &predecessorMatrix, int v1, int v2, std::vector<int> &path);
void computePredecessorMatrix(const Mat &dm, int verticesCount, Mat &predecessorMatrix);
CirclesGridFinderParameters::CirclesGridFinderParameters()
{
minDensity = 10;
densityNeighborhoodSize = Size2f(16, 16);
minDistanceToAddKeypoint = 20;
kmeansAttempts = 100;
convexHullFactor = 1.1f;
keypointScale = 1;
minGraphConfidence = 9;
vertexGain = 1;
vertexPenalty = -0.6f;
edgeGain = 1;
edgePenalty = -0.6f;
existingVertexGain = 10000;
minRNGEdgeSwitchDist = 5.f;
gridType = SYMMETRIC_GRID;
}
CirclesGridFinderParameters2::CirclesGridFinderParameters2()
: CirclesGridFinderParameters()
{
squareSize = 1.0f;
maxRectifiedDistance = squareSize/2.0f;
}
CirclesGridFinder::CirclesGridFinder(Size _patternSize, const std::vector<Point2f> &testKeypoints,
const CirclesGridFinderParameters &_parameters) :
patternSize(static_cast<size_t> (_patternSize.width), static_cast<size_t> (_patternSize.height))
{
CV_Assert(_patternSize.height >= 0 && _patternSize.width >= 0);
keypoints = testKeypoints;
parameters = _parameters;
largeHoles = 0;
smallHoles = 0;
}
bool CirclesGridFinder::findHoles()
{
switch (parameters.gridType)
{
case CirclesGridFinderParameters::SYMMETRIC_GRID:
{
std::vector<Point2f> vectors, filteredVectors, basis;
Graph rng(0);
computeRNG(rng, vectors);
filterOutliersByDensity(vectors, filteredVectors);
std::vector<Graph> basisGraphs;
findBasis(filteredVectors, basis, basisGraphs);
findMCS(basis, basisGraphs);
break;
}
case CirclesGridFinderParameters::ASYMMETRIC_GRID:
{
std::vector<Point2f> vectors, tmpVectors, filteredVectors, basis;
Graph rng(0);
computeRNG(rng, tmpVectors);
rng2gridGraph(rng, vectors);
filterOutliersByDensity(vectors, filteredVectors);
std::vector<Graph> basisGraphs;
findBasis(filteredVectors, basis, basisGraphs);
findMCS(basis, basisGraphs);
eraseUsedGraph(basisGraphs);
holes2 = holes;
holes.clear();
findMCS(basis, basisGraphs);
break;
}
default:
CV_Error(Error::StsBadArg, "Unkown pattern type");
}
return (isDetectionCorrect());
//CV_Error( 0, "Detection is not correct" );
}
void CirclesGridFinder::rng2gridGraph(Graph &rng, std::vector<cv::Point2f> &vectors) const
{
for (size_t i = 0; i < rng.getVerticesCount(); i++)
{
Graph::Neighbors neighbors1 = rng.getNeighbors(i);
for (Graph::Neighbors::iterator it1 = neighbors1.begin(); it1 != neighbors1.end(); ++it1)
{
Graph::Neighbors neighbors2 = rng.getNeighbors(*it1);
for (Graph::Neighbors::iterator it2 = neighbors2.begin(); it2 != neighbors2.end(); ++it2)
{
if (i < *it2)
{
Point2f vec1 = keypoints[i] - keypoints[*it1];
Point2f vec2 = keypoints[*it1] - keypoints[*it2];
if (norm(vec1 - vec2) < parameters.minRNGEdgeSwitchDist || norm(vec1 + vec2)
< parameters.minRNGEdgeSwitchDist)
continue;
vectors.push_back(keypoints[i] - keypoints[*it2]);
vectors.push_back(keypoints[*it2] - keypoints[i]);
}
}
}
}
}
void CirclesGridFinder::eraseUsedGraph(std::vector<Graph> &basisGraphs) const
{
for (size_t i = 0; i < holes.size(); i++)
{
for (size_t j = 0; j < holes[i].size(); j++)
{
for (size_t k = 0; k < basisGraphs.size(); k++)
{
if (i != holes.size() - 1 && basisGraphs[k].areVerticesAdjacent(holes[i][j], holes[i + 1][j]))
{
basisGraphs[k].removeEdge(holes[i][j], holes[i + 1][j]);
}
if (j != holes[i].size() - 1 && basisGraphs[k].areVerticesAdjacent(holes[i][j], holes[i][j + 1]))
{
basisGraphs[k].removeEdge(holes[i][j], holes[i][j + 1]);
}
}
}
}
}
bool CirclesGridFinder::isDetectionCorrect()
{
switch (parameters.gridType)
{
case CirclesGridFinderParameters::SYMMETRIC_GRID:
{
if (holes.size() != patternSize.height)
return false;
std::set<size_t> vertices;
for (size_t i = 0; i < holes.size(); i++)
{
if (holes[i].size() != patternSize.width)
return false;
for (size_t j = 0; j < holes[i].size(); j++)
{
vertices.insert(holes[i][j]);
}
}
return vertices.size() == patternSize.area();
}
case CirclesGridFinderParameters::ASYMMETRIC_GRID:
{
if (holes.size() < holes2.size() || holes[0].size() < holes2[0].size())
{
largeHoles = &holes2;
smallHoles = &holes;
}
else
{
largeHoles = &holes;
smallHoles = &holes2;
}
size_t largeWidth = patternSize.width;
size_t largeHeight = (size_t)ceil(patternSize.height / 2.);
size_t smallWidth = patternSize.width;
size_t smallHeight = (size_t)floor(patternSize.height / 2.);
size_t sw = smallWidth, sh = smallHeight, lw = largeWidth, lh = largeHeight;
if (largeHoles->size() != largeHeight)
{
std::swap(lh, lw);
}
if (smallHoles->size() != smallHeight)
{
std::swap(sh, sw);
}
if (largeHoles->size() != lh || smallHoles->size() != sh)
{
return false;
}
std::set<size_t> vertices;
for (size_t i = 0; i < largeHoles->size(); i++)
{
if (largeHoles->at(i).size() != lw)
{
return false;
}
for (size_t j = 0; j < largeHoles->at(i).size(); j++)
{
vertices.insert(largeHoles->at(i)[j]);
}
if (i < smallHoles->size())
{
if (smallHoles->at(i).size() != sw)
{
return false;
}
for (size_t j = 0; j < smallHoles->at(i).size(); j++)
{
vertices.insert(smallHoles->at(i)[j]);
}
}
}
return (vertices.size() == largeHeight * largeWidth + smallHeight * smallWidth);
}
default:
CV_Error(0, "Unknown pattern type");
}
return false;
}
void CirclesGridFinder::findMCS(const std::vector<Point2f> &basis, std::vector<Graph> &basisGraphs)
{
holes.clear();
Path longestPath;
size_t bestGraphIdx = findLongestPath(basisGraphs, longestPath);
std::vector<size_t> holesRow = longestPath.vertices;
while (holesRow.size() > std::max(patternSize.width, patternSize.height))
{
holesRow.pop_back();
holesRow.erase(holesRow.begin());
}
if (bestGraphIdx == 0)
{
holes.push_back(holesRow);
size_t w = holes[0].size();
size_t h = holes.size();
//parameters.minGraphConfidence = holes[0].size() * parameters.vertexGain + (holes[0].size() - 1) * parameters.edgeGain;
//parameters.minGraphConfidence = holes[0].size() * parameters.vertexGain + (holes[0].size() / 2) * parameters.edgeGain;
//parameters.minGraphConfidence = holes[0].size() * parameters.existingVertexGain + (holes[0].size() / 2) * parameters.edgeGain;
parameters.minGraphConfidence = holes[0].size() * parameters.existingVertexGain;
for (size_t i = h; i < patternSize.height; i++)
{
addHolesByGraph(basisGraphs, true, basis[1]);
}
//parameters.minGraphConfidence = holes.size() * parameters.existingVertexGain + (holes.size() / 2) * parameters.edgeGain;
parameters.minGraphConfidence = holes.size() * parameters.existingVertexGain;
for (size_t i = w; i < patternSize.width; i++)
{
addHolesByGraph(basisGraphs, false, basis[0]);
}
}
else
{
holes.resize(holesRow.size());
for (size_t i = 0; i < holesRow.size(); i++)
holes[i].push_back(holesRow[i]);
size_t w = holes[0].size();
size_t h = holes.size();
parameters.minGraphConfidence = holes.size() * parameters.existingVertexGain;
for (size_t i = w; i < patternSize.width; i++)
{
addHolesByGraph(basisGraphs, false, basis[0]);
}
parameters.minGraphConfidence = holes[0].size() * parameters.existingVertexGain;
for (size_t i = h; i < patternSize.height; i++)
{
addHolesByGraph(basisGraphs, true, basis[1]);
}
}
}
Mat CirclesGridFinder::rectifyGrid(Size detectedGridSize, const std::vector<Point2f>& centers,
const std::vector<Point2f> &keypoints, std::vector<Point2f> &warpedKeypoints)
{
CV_Assert( !centers.empty() );
const float edgeLength = 30;
const Point2f offset(150, 150);
std::vector<Point2f> dstPoints;
bool isClockwiseBefore =
getDirection(centers[0], centers[detectedGridSize.width - 1], centers[centers.size() - 1]) < 0;
int iStart = isClockwiseBefore ? 0 : detectedGridSize.height - 1;
int iEnd = isClockwiseBefore ? detectedGridSize.height : -1;
int iStep = isClockwiseBefore ? 1 : -1;
for (int i = iStart; i != iEnd; i += iStep)
{
for (int j = 0; j < detectedGridSize.width; j++)
{
dstPoints.push_back(offset + Point2f(edgeLength * j, edgeLength * i));
}
}
Mat H = findHomography(Mat(centers), Mat(dstPoints), RANSAC);
//Mat H = findHomography( Mat( corners ), Mat( dstPoints ) );
if (H.empty())
{
H = Mat::zeros(3, 3, CV_64FC1);
warpedKeypoints.clear();
return H;
}
std::vector<Point2f> srcKeypoints;
for (size_t i = 0; i < keypoints.size(); i++)
{
srcKeypoints.push_back(keypoints[i]);
}
Mat dstKeypointsMat;
transform(Mat(srcKeypoints), dstKeypointsMat, H);
std::vector<Point2f> dstKeypoints;
convertPointsFromHomogeneous(dstKeypointsMat, dstKeypoints);
warpedKeypoints.clear();
for (size_t i = 0; i < dstKeypoints.size(); i++)
{
Point2f pt = dstKeypoints[i];
warpedKeypoints.push_back(pt);
}
return H;
}
size_t CirclesGridFinder::findNearestKeypoint(Point2f pt) const
{
size_t bestIdx = 0;
double minDist = std::numeric_limits<double>::max();
for (size_t i = 0; i < keypoints.size(); i++)
{
double dist = norm(pt - keypoints[i]);
if (dist < minDist)
{
minDist = dist;
bestIdx = i;
}
}
return bestIdx;
}
void CirclesGridFinder::addPoint(Point2f pt, std::vector<size_t> &points)
{
size_t ptIdx = findNearestKeypoint(pt);
if (norm(keypoints[ptIdx] - pt) > parameters.minDistanceToAddKeypoint)
{
Point2f kpt = Point2f(pt);
keypoints.push_back(kpt);
points.push_back(keypoints.size() - 1);
}
else
{
points.push_back(ptIdx);
}
}
void CirclesGridFinder::findCandidateLine(std::vector<size_t> &line, size_t seedLineIdx, bool addRow, Point2f basisVec,
std::vector<size_t> &seeds)
{
line.clear();
seeds.clear();
if (addRow)
{
for (size_t i = 0; i < holes[seedLineIdx].size(); i++)
{
Point2f pt = keypoints[holes[seedLineIdx][i]] + basisVec;
addPoint(pt, line);
seeds.push_back(holes[seedLineIdx][i]);
}
}
else
{
for (size_t i = 0; i < holes.size(); i++)
{
Point2f pt = keypoints[holes[i][seedLineIdx]] + basisVec;
addPoint(pt, line);
seeds.push_back(holes[i][seedLineIdx]);
}
}
CV_Assert( line.size() == seeds.size() );
}
void CirclesGridFinder::findCandidateHoles(std::vector<size_t> &above, std::vector<size_t> &below, bool addRow, Point2f basisVec,
std::vector<size_t> &aboveSeeds, std::vector<size_t> &belowSeeds)
{
above.clear();
below.clear();
aboveSeeds.clear();
belowSeeds.clear();
findCandidateLine(above, 0, addRow, -basisVec, aboveSeeds);
size_t lastIdx = addRow ? holes.size() - 1 : holes[0].size() - 1;
findCandidateLine(below, lastIdx, addRow, basisVec, belowSeeds);
CV_Assert( below.size() == above.size() );
CV_Assert( belowSeeds.size() == aboveSeeds.size() );
CV_Assert( below.size() == belowSeeds.size() );
}
bool CirclesGridFinder::areCentersNew(const std::vector<size_t> &newCenters, const std::vector<std::vector<size_t> > &holes)
{
for (size_t i = 0; i < newCenters.size(); i++)
{
for (size_t j = 0; j < holes.size(); j++)
{
if (holes[j].end() != std::find(holes[j].begin(), holes[j].end(), newCenters[i]))
{
return false;
}
}
}
return true;
}
void CirclesGridFinder::insertWinner(float aboveConfidence, float belowConfidence, float minConfidence, bool addRow,
const std::vector<size_t> &above, const std::vector<size_t> &below,
std::vector<std::vector<size_t> > &holes)
{
if (aboveConfidence < minConfidence && belowConfidence < minConfidence)
return;
if (addRow)
{
if (aboveConfidence >= belowConfidence)
{
if (!areCentersNew(above, holes))
CV_Error( 0, "Centers are not new" );
holes.insert(holes.begin(), above);
}
else
{
if (!areCentersNew(below, holes))
CV_Error( 0, "Centers are not new" );
holes.insert(holes.end(), below);
}
}
else
{
if (aboveConfidence >= belowConfidence)
{