circlesgrid.cpp 47.7 KB
Newer Older
1
/*M///////////////////////////////////////////////////////////////////////////////////////
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
 //
 //  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*/
42

A
Alexander Alekhin 已提交
43
#include "precomp.hpp"
44
#include "circlesgrid.hpp"
45
#include <limits>
46
//#define DEBUG_CIRCLES
47

48
#ifdef DEBUG_CIRCLES
R
rmensing 已提交
49
#  include <iostream>
50 51
#  include "opencv2/opencv_modules.hpp"
#  ifdef HAVE_OPENCV_HIGHGUI
52
#    include "opencv2/highgui.hpp"
53 54 55
#  else
#    undef DEBUG_CIRCLES
#  endif
56 57
#endif

58 59
using namespace cv;

60
#ifdef DEBUG_CIRCLES
61
void drawPoints(const std::vector<Point2f> &points, Mat &outImage, int radius = 2,  Scalar color = Scalar::all(255), int thickness = -1)
62 63 64 65 66 67 68 69
{
  for(size_t i=0; i<points.size(); i++)
  {
    circle(outImage, points[i], radius, color, thickness);
  }
}
#endif

70
void CirclesGridClusterFinder::hierarchicalClustering(const std::vector<Point2f> &points, const Size &patternSz, std::vector<Point2f> &patternPoints)
71
{
72
#ifdef HAVE_TEGRA_OPTIMIZATION
73
    if(tegra::useTegra() && tegra::hierarchicalClustering(points, patternSz, patternPoints))
74 75
        return;
#endif
A
Andrey Kamaev 已提交
76 77
    int j, n = (int)points.size();
    size_t pn = static_cast<size_t>(patternSz.area());
78 79 80

    patternPoints.clear();
    if (pn >= points.size())
81
    {
82 83 84
        if (pn == points.size())
            patternPoints = points;
        return;
85 86
    }

87 88
    Mat dists(n, n, CV_32FC1, Scalar(0));
    Mat distsMask(dists.size(), CV_8UC1, Scalar(0));
A
Andrey Kamaev 已提交
89
    for(int i = 0; i < n; i++)
90 91 92 93 94 95 96 97 98 99
    {
        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);
        }
    }
100

101
    std::vector<std::list<size_t> > clusters(points.size());
102 103 104 105
    for(size_t i=0; i<points.size(); i++)
    {
        clusters[i].push_back(i);
    }
106

107 108 109 110 111 112 113
    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);
114

115 116 117 118 119 120 121 122 123 124 125
        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;
    }

126
    //the largest cluster can have more than pn points -- we need to filter out such situations
A
Andrey Kamaev 已提交
127
    if(clusters[patternClusterIdx].size() != static_cast<size_t>(patternSz.area()))
128 129 130 131
    {
      return;
    }

132
    patternPoints.reserve(clusters[patternClusterIdx].size());
J
Julien Nabet 已提交
133
    for(std::list<size_t>::iterator it = clusters[patternClusterIdx].begin(); it != clusters[patternClusterIdx].end();++it)
134 135 136
    {
        patternPoints.push_back(points[*it]);
    }
137 138
}

139
void CirclesGridClusterFinder::findGrid(const std::vector<cv::Point2f> &points, cv::Size _patternSize, std::vector<Point2f>& centers)
140
{
141
  patternSize = _patternSize;
142
  centers.clear();
143 144 145 146
  if(points.empty())
  {
    return;
  }
147

148
  std::vector<Point2f> patternPoints;
149 150 151 152 153 154
  hierarchicalClustering(points, patternSize, patternPoints);
  if(patternPoints.empty())
  {
    return;
  }

155 156 157 158 159 160
#ifdef DEBUG_CIRCLES
  Mat patternPointsImage(1024, 1248, CV_8UC1, Scalar(0));
  drawPoints(patternPoints, patternPointsImage);
  imshow("pattern points", patternPointsImage);
#endif

161
  std::vector<Point2f> hull2f;
162
  convexHull(Mat(patternPoints), hull2f, false);
163
  const size_t cornersCount = isAsymmetricGrid ? 6 : 4;
164 165
  if(hull2f.size() < cornersCount)
    return;
166

167
  std::vector<Point2f> corners;
168
  findCorners(hull2f, corners);
169 170
  if(corners.size() != cornersCount)
    return;
171

172
  std::vector<Point2f> outsideCorners, sortedCorners;
173 174 175 176 177 178 179
  if(isAsymmetricGrid)
  {
    findOutsideCorners(corners, outsideCorners);
    const size_t outsideCornersCount = 2;
    if(outsideCorners.size() != outsideCornersCount)
      return;
  }
180
  getSortedCorners(hull2f, corners, outsideCorners, sortedCorners);
181 182
  if(sortedCorners.size() != cornersCount)
    return;
183

184
  std::vector<Point2f> rectifiedPatternPoints;
185
  rectifyPatternPoints(patternPoints, sortedCorners, rectifiedPatternPoints);
186 187
  if(patternPoints.size() != rectifiedPatternPoints.size())
    return;
188

189
  parsePatternPoints(patternPoints, rectifiedPatternPoints, centers);
190 191 192 193 194
}

void CirclesGridClusterFinder::findCorners(const std::vector<cv::Point2f> &hull2f, std::vector<cv::Point2f> &corners)
{
  //find angles (cosines) of vertices in convex hull
195
  std::vector<float> angles;
196 197 198 199
  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()];
200
    float angle = (float)(vec1.ddot(vec2) / (norm(vec1) * norm(vec2)));
201 202 203 204 205 206 207
    angles.push_back(angle);
  }

  //sort angles by cosine
  //corners are the most sharp angles (6)
  Mat anglesMat = Mat(angles);
  Mat sortedIndices;
208
  sortIdx(anglesMat, sortedIndices, SORT_EVERY_COLUMN + SORT_DESCENDING);
209
  CV_Assert(sortedIndices.type() == CV_32SC1);
210
  CV_Assert(sortedIndices.cols == 1);
211
  const int cornersCount = isAsymmetricGrid ? 6 : 4;
212
  Mat cornersIndices;
213
  cv::sort(sortedIndices.rowRange(0, cornersCount), cornersIndices, SORT_EVERY_COLUMN + SORT_ASCENDING);
214 215 216
  corners.clear();
  for(int i=0; i<cornersCount; i++)
  {
217
    corners.push_back(hull2f[cornersIndices.at<int>(i, 0)]);
218 219 220 221 222
  }
}

void CirclesGridClusterFinder::findOutsideCorners(const std::vector<cv::Point2f> &corners, std::vector<cv::Point2f> &outsideCorners)
{
I
Ilya Lavrenov 已提交
223
  CV_Assert(!corners.empty());
224
  outsideCorners.clear();
225
  //find two pairs of the most nearest corners
226
  int i, j, n = (int)corners.size();
227

228 229 230 231 232 233
#ifdef DEBUG_CIRCLES
  Mat cornersImage(1024, 1248, CV_8UC1, Scalar(0));
  drawPoints(corners, cornersImage);
  imshow("corners", cornersImage);
#endif

234
  std::vector<Point2f> tangentVectors(corners.size());
235
  for(size_t k=0; k<corners.size(); k++)
236 237 238 239 240 241 242
  {
    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);
243
  for(i = 0; i < n; i++)
244
  {
245
    for(j = i + 1; j < n; j++)
246
    {
247 248 249
      float val = fabs(tangentVectors[i].dot(tangentVectors[j]));
      cosAngles.at<float>(i, j) = val;
      cosAngles.at<float>(j, i) = val;
250 251
    }
  }
252 253 254 255 256 257

  //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)
258
  {
259 260 261 262 263
    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);
264 265
  }

266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
#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)
282
  {
283
    return;
284
  }
285 286 287 288 289 290 291 292

  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));
R
rmensing 已提交
293
  imshow("corners", cornersImage);
294
#endif
295 296 297 298
}

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)
{
299 300 301 302 303 304
  Point2f firstCorner;
  if(isAsymmetricGrid)
  {
    Point2f center = std::accumulate(corners.begin(), corners.end(), Point2f(0.0f, 0.0f));
    center *= 1.0 / corners.size();

305
    std::vector<Point2f> centerToCorners;
306 307 308 309
    for(size_t i=0; i<outsideCorners.size(); i++)
    {
      centerToCorners.push_back(outsideCorners[i] - center);
    }
310

311 312 313 314 315 316 317
    //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
318
  {
319
    firstCorner = corners[0];
320 321 322 323
  }

  std::vector<Point2f>::const_iterator firstCornerIterator = std::find(hull2f.begin(), hull2f.end(), firstCorner);
  sortedCorners.clear();
J
Julien Nabet 已提交
324
  for(std::vector<Point2f>::const_iterator it = firstCornerIterator; it != hull2f.end();++it)
325
  {
326
    std::vector<Point2f>::const_iterator itCorners = std::find(corners.begin(), corners.end(), *it);
327 328 329 330 331
    if(itCorners != corners.end())
    {
      sortedCorners.push_back(*it);
    }
  }
J
Julien Nabet 已提交
332
  for(std::vector<Point2f>::const_iterator it = hull2f.begin(); it != firstCornerIterator;++it)
333
  {
334
    std::vector<Point2f>::const_iterator itCorners = std::find(corners.begin(), corners.end(), *it);
335 336 337 338 339
    if(itCorners != corners.end())
    {
      sortedCorners.push_back(*it);
    }
  }
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354

  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;
    }
  }
355 356
}

357
void CirclesGridClusterFinder::rectifyPatternPoints(const std::vector<cv::Point2f> &patternPoints, const std::vector<cv::Point2f> &sortedCorners, std::vector<cv::Point2f> &rectifiedPatternPoints)
358 359
{
  //indices of corner points in pattern
360
  std::vector<Point> trueIndices;
361 362
  trueIndices.push_back(Point(0, 0));
  trueIndices.push_back(Point(patternSize.width - 1, 0));
363 364 365 366 367
  if(isAsymmetricGrid)
  {
    trueIndices.push_back(Point(patternSize.width - 1, 1));
    trueIndices.push_back(Point(patternSize.width - 1, patternSize.height - 2));
  }
368 369 370
  trueIndices.push_back(Point(patternSize.width - 1, patternSize.height - 1));
  trueIndices.push_back(Point(0, patternSize.height - 1));

371
  std::vector<Point2f> idealPoints;
372 373 374 375
  for(size_t idx=0; idx<trueIndices.size(); idx++)
  {
    int i = trueIndices[idx].y;
    int j = trueIndices[idx].x;
376 377 378 379 380 381 382 383
    if(isAsymmetricGrid)
    {
      idealPoints.push_back(Point2f((2*j + i % 2)*squareSize, i*squareSize));
    }
    else
    {
      idealPoints.push_back(Point2f(j*squareSize, i*squareSize));
    }
384 385 386 387
  }

  Mat homography = findHomography(Mat(sortedCorners), Mat(idealPoints), 0);
  Mat rectifiedPointsMat;
388
  transform(patternPoints, rectifiedPointsMat, homography);
389
  rectifiedPatternPoints.clear();
390
  convertPointsFromHomogeneous(rectifiedPointsMat, rectifiedPatternPoints);
391 392
}

393
void CirclesGridClusterFinder::parsePatternPoints(const std::vector<cv::Point2f> &patternPoints, const std::vector<cv::Point2f> &rectifiedPatternPoints, std::vector<cv::Point2f> &centers)
394 395 396 397 398 399 400 401 402
{
  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++ )
    {
403 404 405 406 407 408
      Point2f idealPt;
      if(isAsymmetricGrid)
        idealPt = Point2f((2*j + i % 2)*squareSize, i*squareSize);
      else
        idealPt = Point2f(j*squareSize, i*squareSize);

409
      Mat query(1, 2, CV_32F, &idealPt);
410 411 412
      const int knn = 1;
      int indicesbuf[knn] = {0};
      float distsbuf[knn] = {0.f};
413 414
      Mat indices(1, knn, CV_32S, &indicesbuf);
      Mat dists(1, knn, CV_32F, &distsbuf);
415
      flannIndex.knnSearch(query, indices, dists, knn, flann::SearchParams());
416
      centers.push_back(patternPoints.at(indicesbuf[0]));
417

418
      if(distsbuf[0] > maxRectifiedDistance)
419
      {
420
#ifdef DEBUG_CIRCLES
R
rmensing 已提交
421
        std::cout << "Pattern not detected: too large rectified distance" << std::endl;
422
#endif
423 424 425 426 427 428 429
        centers.clear();
        return;
      }
    }
  }
}

430
Graph::Graph(size_t n)
431
{
432
  for (size_t i = 0; i < n; i++)
433 434 435 436 437
  {
    addVertex(i);
  }
}

438
bool Graph::doesVertexExist(size_t id) const
439 440 441 442
{
  return (vertices.find(id) != vertices.end());
}

443
void Graph::addVertex(size_t id)
444
{
445
  CV_Assert( !doesVertexExist( id ) );
446

447
  vertices.insert(std::pair<size_t, Vertex> (id, Vertex()));
448 449
}

450
void Graph::addEdge(size_t id1, size_t id2)
451
{
452 453
  CV_Assert( doesVertexExist( id1 ) );
  CV_Assert( doesVertexExist( id2 ) );
454 455 456 457 458

  vertices[id1].neighbors.insert(id2);
  vertices[id2].neighbors.insert(id1);
}

459 460
void Graph::removeEdge(size_t id1, size_t id2)
{
461 462
  CV_Assert( doesVertexExist( id1 ) );
  CV_Assert( doesVertexExist( id2 ) );
463 464 465 466 467 468

  vertices[id1].neighbors.erase(id2);
  vertices[id2].neighbors.erase(id1);
}

bool Graph::areVerticesAdjacent(size_t id1, size_t id2) const
469
{
470 471
  CV_Assert( doesVertexExist( id1 ) );
  CV_Assert( doesVertexExist( id2 ) );
472 473 474 475 476 477 478 479 480 481

  Vertices::const_iterator it = vertices.find(id1);
  return it->second.neighbors.find(id2) != it->second.neighbors.end();
}

size_t Graph::getVerticesCount() const
{
  return vertices.size();
}

482
size_t Graph::getDegree(size_t id) const
483
{
484
  CV_Assert( doesVertexExist(id) );
485 486 487 488 489 490 491 492 493

  Vertices::const_iterator it = vertices.find(id);
  return it->second.neighbors.size();
}

void Graph::floydWarshall(cv::Mat &distanceMatrix, int infinity) const
{
  const int edgeWeight = 1;

494
  const int n = (int)getVerticesCount();
495 496
  distanceMatrix.create(n, n, CV_32SC1);
  distanceMatrix.setTo(infinity);
J
Julien Nabet 已提交
497
  for (Vertices::const_iterator it1 = vertices.begin(); it1 != vertices.end();++it1)
498
  {
499
    distanceMatrix.at<int> ((int)it1->first, (int)it1->first) = 0;
J
Julien Nabet 已提交
500
    for (Neighbors::const_iterator it2 = it1->second.neighbors.begin(); it2 != it1->second.neighbors.end();++it2)
501
    {
502
      CV_Assert( it1->first != *it2 );
503
      distanceMatrix.at<int> ((int)it1->first, (int)*it2) = edgeWeight;
504 505 506
    }
  }

J
Julien Nabet 已提交
507
  for (Vertices::const_iterator it1 = vertices.begin(); it1 != vertices.end();++it1)
508
  {
J
Julien Nabet 已提交
509
    for (Vertices::const_iterator it2 = vertices.begin(); it2 != vertices.end();++it2)
510
    {
J
Julien Nabet 已提交
511
      for (Vertices::const_iterator it3 = vertices.begin(); it3 != vertices.end();++it3)
512
      {
A
Andrey Kamaev 已提交
513
      int i1 = (int)it1->first, i2 = (int)it2->first, i3 = (int)it3->first;
514
        int val1 = distanceMatrix.at<int> (i2, i3);
515
        int val2;
516
        if (distanceMatrix.at<int> (i2, i1) == infinity ||
A
Andrey Kamaev 已提交
517
      distanceMatrix.at<int> (i1, i3) == infinity)
518 519
          val2 = val1;
        else
520
        {
521
          val2 = distanceMatrix.at<int> (i2, i1) + distanceMatrix.at<int> (i1, i3);
522
        }
523
        distanceMatrix.at<int> (i2, i3) = (val1 == infinity) ? val2 : std::min(val1, val2);
524 525 526 527 528
      }
    }
  }
}

529 530
const Graph::Neighbors& Graph::getNeighbors(size_t id) const
{
531
  CV_Assert( doesVertexExist(id) );
532 533 534 535 536 537 538 539 540 541

  Vertices::const_iterator it = vertices.find(id);
  return it->second.neighbors;
}

CirclesGridFinder::Segment::Segment(cv::Point2f _s, cv::Point2f _e) :
  s(_s), e(_e)
{
}

542
void computeShortestPath(Mat &predecessorMatrix, int v1, int v2, std::vector<int> &path);
543 544 545 546 547 548 549 550
void computePredecessorMatrix(const Mat &dm, int verticesCount, Mat &predecessorMatrix);

CirclesGridFinderParameters::CirclesGridFinderParameters()
{
  minDensity = 10;
  densityNeighborhoodSize = Size2f(16, 16);
  minDistanceToAddKeypoint = 20;
  kmeansAttempts = 100;
I
Ilya Lysenkov 已提交
551
  convexHullFactor = 1.1f;
552 553 554
  keypointScale = 1;

  minGraphConfidence = 9;
555 556
  vertexGain = 1;
  vertexPenalty = -0.6f;
557
  edgeGain = 1;
558 559
  edgePenalty = -0.6f;
  existingVertexGain = 10000;
560 561 562

  minRNGEdgeSwitchDist = 5.f;
  gridType = SYMMETRIC_GRID;
563 564
}

565
CirclesGridFinder::CirclesGridFinder(Size _patternSize, const std::vector<Point2f> &testKeypoints,
566
                                     const CirclesGridFinderParameters &_parameters) :
567
  patternSize(static_cast<size_t> (_patternSize.width), static_cast<size_t> (_patternSize.height))
568
{
569 570
  CV_Assert(_patternSize.height >= 0 && _patternSize.width >= 0);

571 572
  keypoints = testKeypoints;
  parameters = _parameters;
573 574
  largeHoles = 0;
  smallHoles = 0;
575 576 577 578
}

bool CirclesGridFinder::findHoles()
{
579 580 581 582
  switch (parameters.gridType)
  {
    case CirclesGridFinderParameters::SYMMETRIC_GRID:
    {
583
      std::vector<Point2f> vectors, filteredVectors, basis;
584 585 586
      Graph rng(0);
      computeRNG(rng, vectors);
      filterOutliersByDensity(vectors, filteredVectors);
587
      std::vector<Graph> basisGraphs;
588 589 590 591 592 593 594
      findBasis(filteredVectors, basis, basisGraphs);
      findMCS(basis, basisGraphs);
      break;
    }

    case CirclesGridFinderParameters::ASYMMETRIC_GRID:
    {
595
      std::vector<Point2f> vectors, tmpVectors, filteredVectors, basis;
596 597 598 599
      Graph rng(0);
      computeRNG(rng, tmpVectors);
      rng2gridGraph(rng, vectors);
      filterOutliersByDensity(vectors, filteredVectors);
600
      std::vector<Graph> basisGraphs;
601 602 603 604 605 606 607 608
      findBasis(filteredVectors, basis, basisGraphs);
      findMCS(basis, basisGraphs);
      eraseUsedGraph(basisGraphs);
      holes2 = holes;
      holes.clear();
      findMCS(basis, basisGraphs);
      break;
    }
609

610
    default:
611
      CV_Error(Error::StsBadArg, "Unkown pattern type");
612
  }
613 614 615 616
  return (isDetectionCorrect());
  //CV_Error( 0, "Detection is not correct" );
}

617
void CirclesGridFinder::rng2gridGraph(Graph &rng, std::vector<cv::Point2f> &vectors) const
618
{
619 620 621
  for (size_t i = 0; i < rng.getVerticesCount(); i++)
  {
    Graph::Neighbors neighbors1 = rng.getNeighbors(i);
J
Julien Nabet 已提交
622
    for (Graph::Neighbors::iterator it1 = neighbors1.begin(); it1 != neighbors1.end(); ++it1)
623 624
    {
      Graph::Neighbors neighbors2 = rng.getNeighbors(*it1);
J
Julien Nabet 已提交
625
      for (Graph::Neighbors::iterator it2 = neighbors2.begin(); it2 != neighbors2.end(); ++it2)
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
      {
        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]);
        }
      }
    }
  }
}
642

643
void CirclesGridFinder::eraseUsedGraph(std::vector<Graph> &basisGraphs) const
644
{
645 646 647 648
  for (size_t i = 0; i < holes.size(); i++)
  {
    for (size_t j = 0; j < holes[i].size(); j++)
    {
649 650 651 652 653 654 655 656 657 658 659 660
      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]);
        }
      }
661 662
    }
  }
663 664 665 666 667 668 669 670 671 672 673
}

bool CirclesGridFinder::isDetectionCorrect()
{
  switch (parameters.gridType)
  {
    case CirclesGridFinderParameters::SYMMETRIC_GRID:
    {
      if (holes.size() != patternSize.height)
        return false;

674
      std::set<size_t> vertices;
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
      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;
703
      size_t largeHeight = (size_t)ceil(patternSize.height / 2.);
704
      size_t smallWidth = patternSize.width;
705
      size_t smallHeight = (size_t)floor(patternSize.height / 2.);
706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721

      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;
      }

722
      std::set<size_t> vertices;
723 724 725 726 727 728
      for (size_t i = 0; i < largeHoles->size(); i++)
      {
        if (largeHoles->at(i).size() != lw)
        {
          return false;
        }
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
        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;
756 757
}

758
void CirclesGridFinder::findMCS(const std::vector<Point2f> &basis, std::vector<Graph> &basisGraphs)
759
{
760
  holes.clear();
761 762
  Path longestPath;
  size_t bestGraphIdx = findLongestPath(basisGraphs, longestPath);
763
  std::vector<size_t> holesRow = longestPath.vertices;
764 765 766 767 768 769 770 771 772 773

  while (holesRow.size() > std::max(patternSize.width, patternSize.height))
  {
    holesRow.pop_back();
    holesRow.erase(holesRow.begin());
  }

  if (bestGraphIdx == 0)
  {
    holes.push_back(holesRow);
774 775
    size_t w = holes[0].size();
    size_t h = holes.size();
776 777 778 779 780

    //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;
781
    for (size_t i = h; i < patternSize.height; i++)
782 783 784 785 786 787 788
    {
      addHolesByGraph(basisGraphs, true, basis[1]);
    }

    //parameters.minGraphConfidence = holes.size() * parameters.existingVertexGain + (holes.size() / 2) * parameters.edgeGain;
    parameters.minGraphConfidence = holes.size() * parameters.existingVertexGain;

789
    for (size_t i = w; i < patternSize.width; i++)
790 791 792 793 794 795 796 797 798 799
    {
      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]);

800 801
    size_t w = holes[0].size();
    size_t h = holes.size();
802 803

    parameters.minGraphConfidence = holes.size() * parameters.existingVertexGain;
804
    for (size_t i = w; i < patternSize.width; i++)
805 806 807 808 809
    {
      addHolesByGraph(basisGraphs, false, basis[0]);
    }

    parameters.minGraphConfidence = holes[0].size() * parameters.existingVertexGain;
810
    for (size_t i = h; i < patternSize.height; i++)
811 812 813 814 815 816
    {
      addHolesByGraph(basisGraphs, true, basis[1]);
    }
  }
}

817 818
Mat CirclesGridFinder::rectifyGrid(Size detectedGridSize, const std::vector<Point2f>& centers,
                                   const std::vector<Point2f> &keypoints, std::vector<Point2f> &warpedKeypoints)
819
{
820
  CV_Assert( !centers.empty() );
821 822 823
  const float edgeLength = 30;
  const Point2f offset(150, 150);

824
  std::vector<Point2f> dstPoints;
825 826 827 828 829 830 831
  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)
832 833 834 835 836 837 838
  {
    for (int j = 0; j < detectedGridSize.width; j++)
    {
      dstPoints.push_back(offset + Point2f(edgeLength * j, edgeLength * i));
    }
  }

839
  Mat H = findHomography(Mat(centers), Mat(dstPoints), RANSAC);
840 841
  //Mat H = findHomography( Mat( corners ), Mat( dstPoints ) );

842
  if (H.empty())
M
Matthias Grundmann 已提交
843
  {
844
      H = Mat::zeros(3, 3, CV_64FC1);
M
Matthias Grundmann 已提交
845 846 847
      warpedKeypoints.clear();
      return H;
  }
848

849
  std::vector<Point2f> srcKeypoints;
850 851
  for (size_t i = 0; i < keypoints.size(); i++)
  {
I
Ilya Lysenkov 已提交
852
    srcKeypoints.push_back(keypoints[i]);
853 854 855 856
  }

  Mat dstKeypointsMat;
  transform(Mat(srcKeypoints), dstKeypointsMat, H);
857
  std::vector<Point2f> dstKeypoints;
858
  convertPointsFromHomogeneous(dstKeypointsMat, dstKeypoints);
859 860 861 862 863

  warpedKeypoints.clear();
  for (size_t i = 0; i < dstKeypoints.size(); i++)
  {
    Point2f pt = dstKeypoints[i];
I
Ilya Lysenkov 已提交
864
    warpedKeypoints.push_back(pt);
865 866 867 868 869
  }

  return H;
}

870
size_t CirclesGridFinder::findNearestKeypoint(Point2f pt) const
871
{
872
  size_t bestIdx = 0;
I
Ilya Lysenkov 已提交
873
  double minDist = std::numeric_limits<double>::max();
874 875
  for (size_t i = 0; i < keypoints.size(); i++)
  {
I
Ilya Lysenkov 已提交
876
    double dist = norm(pt - keypoints[i]);
877 878 879 880 881 882 883 884 885
    if (dist < minDist)
    {
      minDist = dist;
      bestIdx = i;
    }
  }
  return bestIdx;
}

886
void CirclesGridFinder::addPoint(Point2f pt, std::vector<size_t> &points)
887
{
888
  size_t ptIdx = findNearestKeypoint(pt);
I
Ilya Lysenkov 已提交
889
  if (norm(keypoints[ptIdx] - pt) > parameters.minDistanceToAddKeypoint)
890
  {
I
Ilya Lysenkov 已提交
891
    Point2f kpt = Point2f(pt);
892 893 894 895 896 897 898 899 900
    keypoints.push_back(kpt);
    points.push_back(keypoints.size() - 1);
  }
  else
  {
    points.push_back(ptIdx);
  }
}

901 902
void CirclesGridFinder::findCandidateLine(std::vector<size_t> &line, size_t seedLineIdx, bool addRow, Point2f basisVec,
                                          std::vector<size_t> &seeds)
903 904 905 906 907 908 909 910
{
  line.clear();
  seeds.clear();

  if (addRow)
  {
    for (size_t i = 0; i < holes[seedLineIdx].size(); i++)
    {
I
Ilya Lysenkov 已提交
911
      Point2f pt = keypoints[holes[seedLineIdx][i]] + basisVec;
912 913 914 915 916 917 918 919
      addPoint(pt, line);
      seeds.push_back(holes[seedLineIdx][i]);
    }
  }
  else
  {
    for (size_t i = 0; i < holes.size(); i++)
    {
I
Ilya Lysenkov 已提交
920
      Point2f pt = keypoints[holes[i][seedLineIdx]] + basisVec;
921 922 923 924 925
      addPoint(pt, line);
      seeds.push_back(holes[i][seedLineIdx]);
    }
  }

926
  CV_Assert( line.size() == seeds.size() );
927 928
}

929 930
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)
931 932 933 934 935 936 937
{
  above.clear();
  below.clear();
  aboveSeeds.clear();
  belowSeeds.clear();

  findCandidateLine(above, 0, addRow, -basisVec, aboveSeeds);
938
  size_t lastIdx = addRow ? holes.size() - 1 : holes[0].size() - 1;
939 940
  findCandidateLine(below, lastIdx, addRow, basisVec, belowSeeds);

941 942 943
  CV_Assert( below.size() == above.size() );
  CV_Assert( belowSeeds.size() == aboveSeeds.size() );
  CV_Assert( below.size() == belowSeeds.size() );
944 945
}

946
bool CirclesGridFinder::areCentersNew(const std::vector<size_t> &newCenters, const std::vector<std::vector<size_t> > &holes)
947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962
{
  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,
963 964
                                     const std::vector<size_t> &above, const std::vector<size_t> &below,
                                     std::vector<std::vector<size_t> > &holes)
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
{
  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)
    {
      if (!areCentersNew(above, holes))
        CV_Error( 0, "Centers are not new" );

      for (size_t i = 0; i < holes.size(); i++)
      {
        holes[i].insert(holes[i].begin(), above[i]);
      }
    }
    else
    {
      if (!areCentersNew(below, holes))
        CV_Error( 0, "Centers are not new" );

      for (size_t i = 0; i < holes.size(); i++)
      {
        holes[i].insert(holes[i].end(), below[i]);
      }
    }
  }
}

1011 1012
float CirclesGridFinder::computeGraphConfidence(const std::vector<Graph> &basisGraphs, bool addRow,
                                                const std::vector<size_t> &points, const std::vector<size_t> &seeds)
1013
{
1014
  CV_Assert( points.size() == seeds.size() );
1015
  float confidence = 0;
1016
  const size_t vCount = basisGraphs[0].getVerticesCount();
1017
  CV_Assert( basisGraphs[0].getVerticesCount() == basisGraphs[1].getVerticesCount() );
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056

  for (size_t i = 0; i < seeds.size(); i++)
  {
    if (seeds[i] < vCount && points[i] < vCount)
    {
      if (!basisGraphs[addRow].areVerticesAdjacent(seeds[i], points[i]))
      {
        confidence += parameters.vertexPenalty;
      }
      else
      {
        confidence += parameters.vertexGain;
      }
    }

    if (points[i] < vCount)
    {
      confidence += parameters.existingVertexGain;
    }
  }

  for (size_t i = 1; i < points.size(); i++)
  {
    if (points[i - 1] < vCount && points[i] < vCount)
    {
      if (!basisGraphs[!addRow].areVerticesAdjacent(points[i - 1], points[i]))
      {
        confidence += parameters.edgePenalty;
      }
      else
      {
        confidence += parameters.edgeGain;
      }
    }
  }
  return confidence;

}

1057
void CirclesGridFinder::addHolesByGraph(const std::vector<Graph> &basisGraphs, bool addRow, Point2f basisVec)
1058
{
1059
  std::vector<size_t> above, below, aboveSeeds, belowSeeds;
1060 1061 1062 1063 1064 1065 1066
  findCandidateHoles(above, below, addRow, basisVec, aboveSeeds, belowSeeds);
  float aboveConfidence = computeGraphConfidence(basisGraphs, addRow, above, aboveSeeds);
  float belowConfidence = computeGraphConfidence(basisGraphs, addRow, below, belowSeeds);

  insertWinner(aboveConfidence, belowConfidence, parameters.minGraphConfidence, addRow, above, below, holes);
}

1067
void CirclesGridFinder::filterOutliersByDensity(const std::vector<Point2f> &samples, std::vector<Point2f> &filteredSamples)
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
{
  if (samples.empty())
    CV_Error( 0, "samples is empty" );

  filteredSamples.clear();

  for (size_t i = 0; i < samples.size(); i++)
  {
    Rect_<float> rect(samples[i] - Point2f(parameters.densityNeighborhoodSize) * 0.5,
                      parameters.densityNeighborhoodSize);
    int neighborsCount = 0;
    for (size_t j = 0; j < samples.size(); j++)
    {
      if (rect.contains(samples[j]))
        neighborsCount++;
    }
    if (neighborsCount >= parameters.minDensity)
      filteredSamples.push_back(samples[i]);
  }

  if (filteredSamples.empty())
    CV_Error( 0, "filteredSamples is empty" );
}

1092
void CirclesGridFinder::findBasis(const std::vector<Point2f> &samples, std::vector<Point2f> &basis, std::vector<Graph> &basisGraphs)
1093 1094 1095 1096 1097
{
  basis.clear();
  Mat bestLabels;
  TermCriteria termCriteria;
  Mat centers;
1098
  const int clustersCount = 4;
1099
  kmeans(Mat(samples).reshape(1, 0), clustersCount, bestLabels, termCriteria, parameters.kmeansAttempts,
1100
         KMEANS_RANDOM_CENTERS, centers);
1101
  CV_Assert( centers.type() == CV_32FC1 );
1102

1103
  std::vector<int> basisIndices;
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
  //TODO: only remove duplicate
  for (int i = 0; i < clustersCount; i++)
  {
    int maxIdx = (fabs(centers.at<float> (i, 0)) < fabs(centers.at<float> (i, 1)));
    if (centers.at<float> (i, maxIdx) > 0)
    {
      Point2f vec(centers.at<float> (i, 0), centers.at<float> (i, 1));
      basis.push_back(vec);
      basisIndices.push_back(i);
    }
  }
  if (basis.size() != 2)
1116
    CV_Error(0, "Basis size is not 2");
1117 1118 1119 1120 1121 1122 1123 1124 1125

  if (basis[1].x > basis[0].x)
  {
    std::swap(basis[0], basis[1]);
    std::swap(basisIndices[0], basisIndices[1]);
  }

  const float minBasisDif = 2;
  if (norm(basis[0] - basis[1]) < minBasisDif)
1126
    CV_Error(0, "degenerate basis" );
1127

1128
  std::vector<std::vector<Point2f> > clusters(2), hulls(2);
1129
  for (int k = 0; k < (int)samples.size(); k++)
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
  {
    int label = bestLabels.at<int> (k, 0);
    int idx = -1;
    if (label == basisIndices[0])
      idx = 0;
    if (label == basisIndices[1])
      idx = 1;
    if (idx >= 0)
    {
      clusters[idx].push_back(basis[idx] + parameters.convexHullFactor * (samples[k] - basis[idx]));
    }
  }
  for (size_t i = 0; i < basis.size(); i++)
  {
    convexHull(Mat(clusters[i]), hulls[i]);
  }

  basisGraphs.resize(basis.size(), Graph(keypoints.size()));
  for (size_t i = 0; i < keypoints.size(); i++)
  {
    for (size_t j = 0; j < keypoints.size(); j++)
    {
      if (i == j)
        continue;

I
Ilya Lysenkov 已提交
1155
      Point2f vec = keypoints[i] - keypoints[j];
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165

      for (size_t k = 0; k < hulls.size(); k++)
      {
        if (pointPolygonTest(Mat(hulls[k]), vec, false) >= 0)
        {
          basisGraphs[k].addEdge(i, j);
        }
      }
    }
  }
1166 1167
  if (basisGraphs.size() != 2)
    CV_Error(0, "Number of basis graphs is not 2");
1168 1169
}

1170
void CirclesGridFinder::computeRNG(Graph &rng, std::vector<cv::Point2f> &vectors, Mat *drawImage) const
1171
{
1172
  rng = Graph(keypoints.size());
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
  vectors.clear();

  //TODO: use more fast algorithm instead of naive N^3
  for (size_t i = 0; i < keypoints.size(); i++)
  {
    for (size_t j = 0; j < keypoints.size(); j++)
    {
      if (i == j)
        continue;

I
Ilya Lysenkov 已提交
1183
      Point2f vec = keypoints[i] - keypoints[j];
I
Ilya Lysenkov 已提交
1184
      double dist = norm(vec);
1185 1186 1187 1188 1189 1190 1191

      bool isNeighbors = true;
      for (size_t k = 0; k < keypoints.size(); k++)
      {
        if (k == i || k == j)
          continue;

I
Ilya Lysenkov 已提交
1192 1193
        double dist1 = norm(keypoints[i] - keypoints[k]);
        double dist2 = norm(keypoints[j] - keypoints[k]);
1194 1195 1196 1197 1198 1199 1200 1201 1202
        if (dist1 < dist && dist2 < dist)
        {
          isNeighbors = false;
          break;
        }
      }

      if (isNeighbors)
      {
1203
        rng.addEdge(i, j);
I
Ilya Lysenkov 已提交
1204
        vectors.push_back(keypoints[i] - keypoints[j]);
1205 1206
        if (drawImage != 0)
        {
I
Ilya Lysenkov 已提交
1207 1208 1209
          line(*drawImage, keypoints[i], keypoints[j], Scalar(255, 0, 0), 2);
          circle(*drawImage, keypoints[i], 3, Scalar(0, 0, 255), -1);
          circle(*drawImage, keypoints[j], 3, Scalar(0, 0, 255), -1);
1210 1211 1212 1213 1214 1215 1216 1217
        }
      }
    }
  }
}

void computePredecessorMatrix(const Mat &dm, int verticesCount, Mat &predecessorMatrix)
{
1218
  CV_Assert( dm.type() == CV_32SC1 );
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
  predecessorMatrix.create(verticesCount, verticesCount, CV_32SC1);
  predecessorMatrix = -1;
  for (int i = 0; i < predecessorMatrix.rows; i++)
  {
    for (int j = 0; j < predecessorMatrix.cols; j++)
    {
      int dist = dm.at<int> (i, j);
      for (int k = 0; k < verticesCount; k++)
      {
        if (dm.at<int> (i, k) == dist - 1 && dm.at<int> (k, j) == 1)
        {
          predecessorMatrix.at<int> (i, j) = k;
          break;
        }
      }
    }
  }
}

1238
static void computeShortestPath(Mat &predecessorMatrix, size_t v1, size_t v2, std::vector<size_t> &path)
1239
{
1240
  if (predecessorMatrix.at<int> ((int)v1, (int)v2) < 0)
1241 1242 1243 1244 1245
  {
    path.push_back(v1);
    return;
  }

1246
  computeShortestPath(predecessorMatrix, v1, predecessorMatrix.at<int> ((int)v1, (int)v2), path);
1247 1248 1249
  path.push_back(v2);
}

1250
size_t CirclesGridFinder::findLongestPath(std::vector<Graph> &basisGraphs, Path &bestPath)
1251
{
1252 1253
  std::vector<Path> longestPaths(1);
  std::vector<int> confidences;
1254 1255 1256 1257 1258 1259 1260 1261 1262

  size_t bestGraphIdx = 0;
  const int infinity = -1;
  for (size_t graphIdx = 0; graphIdx < basisGraphs.size(); graphIdx++)
  {
    const Graph &g = basisGraphs[graphIdx];
    Mat distanceMatrix;
    g.floydWarshall(distanceMatrix, infinity);
    Mat predecessorMatrix;
1263
    computePredecessorMatrix(distanceMatrix, (int)g.getVerticesCount(), predecessorMatrix);
1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276

    double maxVal;
    Point maxLoc;
    minMaxLoc(distanceMatrix, 0, &maxVal, 0, &maxLoc);

    if (maxVal > longestPaths[0].length)
    {
      longestPaths.clear();
      confidences.clear();
      bestGraphIdx = graphIdx;
    }
    if (longestPaths.empty() || (maxVal == longestPaths[0].length && graphIdx == bestGraphIdx))
    {
I
Ilya Lysenkov 已提交
1277
      Path path = Path(maxLoc.x, maxLoc.y, cvRound(maxVal));
1278 1279 1280 1281 1282
      CV_Assert(maxLoc.x >= 0 && maxLoc.y >= 0)
        ;
      size_t id1 = static_cast<size_t> (maxLoc.x);
      size_t id2 = static_cast<size_t> (maxLoc.y);
      computeShortestPath(predecessorMatrix, id1, id2, path.vertices);
1283 1284 1285
      longestPaths.push_back(path);

      int conf = 0;
1286
      for (int v2 = 0; v2 < (int)path.vertices.size(); v2++)
1287
      {
1288
        conf += (int)basisGraphs[1 - (int)graphIdx].getDegree(v2);
1289 1290 1291 1292 1293 1294 1295 1296 1297
      }
      confidences.push_back(conf);
    }
  }
  //if( bestGraphIdx != 0 )
  //CV_Error( 0, "" );

  int maxConf = -1;
  int bestPathIdx = -1;
1298
  for (int i = 0; i < (int)confidences.size(); i++)
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
  {
    if (confidences[i] > maxConf)
    {
      maxConf = confidences[i];
      bestPathIdx = i;
    }
  }

  //int bestPathIdx = rand() % longestPaths.size();
  bestPath = longestPaths.at(bestPathIdx);
I
Ilya Lysenkov 已提交
1309 1310
  bool needReverse = (bestGraphIdx == 0 && keypoints[bestPath.lastVertex].x < keypoints[bestPath.firstVertex].x)
      || (bestGraphIdx == 1 && keypoints[bestPath.lastVertex].y < keypoints[bestPath.firstVertex].y);
1311 1312 1313 1314 1315 1316 1317 1318
  if (needReverse)
  {
    std::swap(bestPath.lastVertex, bestPath.firstVertex);
    std::reverse(bestPath.vertices.begin(), bestPath.vertices.end());
  }
  return bestGraphIdx;
}

1319
void CirclesGridFinder::drawBasis(const std::vector<Point2f> &basis, Point2f origin, Mat &drawImg) const
1320 1321 1322 1323
{
  for (size_t i = 0; i < basis.size(); i++)
  {
    Point2f pt(basis[i]);
1324
    line(drawImg, origin, origin + pt, Scalar(0, (double)(i * 255), 0), 2);
1325 1326 1327
  }
}

1328
void CirclesGridFinder::drawBasisGraphs(const std::vector<Graph> &basisGraphs, Mat &drawImage, bool drawEdges,
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
                                        bool drawVertices) const
{
  //const int vertexRadius = 1;
  const int vertexRadius = 3;
  const Scalar vertexColor = Scalar(0, 0, 255);
  const int vertexThickness = -1;

  const Scalar edgeColor = Scalar(255, 0, 0);
  //const int edgeThickness = 1;
  const int edgeThickness = 2;

  if (drawEdges)
  {
    for (size_t i = 0; i < basisGraphs.size(); i++)
    {
      for (size_t v1 = 0; v1 < basisGraphs[i].getVerticesCount(); v1++)
      {
        for (size_t v2 = 0; v2 < basisGraphs[i].getVerticesCount(); v2++)
        {
          if (basisGraphs[i].areVerticesAdjacent(v1, v2))
          {
I
Ilya Lysenkov 已提交
1350
            line(drawImage, keypoints[v1], keypoints[v2], edgeColor, edgeThickness);
1351 1352 1353 1354 1355 1356 1357 1358 1359
          }
        }
      }
    }
  }
  if (drawVertices)
  {
    for (size_t v = 0; v < basisGraphs[0].getVerticesCount(); v++)
    {
I
Ilya Lysenkov 已提交
1360
      circle(drawImage, keypoints[v], vertexRadius, vertexColor, vertexThickness);
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
    }
  }
}

void CirclesGridFinder::drawHoles(const Mat &srcImage, Mat &drawImage) const
{
  //const int holeRadius = 4;
  //const int holeRadius = 2;
  //const int holeThickness = 1;
  const int holeRadius = 3;
  const int holeThickness = -1;

  //const Scalar holeColor = Scalar(0, 0, 255);
  const Scalar holeColor = Scalar(0, 255, 0);

  if (srcImage.channels() == 1)
1377
    cvtColor(srcImage, drawImage, COLOR_GRAY2RGB);
1378 1379 1380 1381 1382 1383 1384 1385
  else
    srcImage.copyTo(drawImage);

  for (size_t i = 0; i < holes.size(); i++)
  {
    for (size_t j = 0; j < holes[i].size(); j++)
    {
      if (j != holes[i].size() - 1)
I
Ilya Lysenkov 已提交
1386
        line(drawImage, keypoints[holes[i][j]], keypoints[holes[i][j + 1]], Scalar(255, 0, 0), 2);
1387
      if (i != holes.size() - 1)
I
Ilya Lysenkov 已提交
1388
        line(drawImage, keypoints[holes[i][j]], keypoints[holes[i + 1][j]], Scalar(255, 0, 0), 2);
1389

I
Ilya Lysenkov 已提交
1390 1391
      //circle(drawImage, keypoints[holes[i][j]], holeRadius, holeColor, holeThickness);
      circle(drawImage, keypoints[holes[i][j]], holeRadius, holeColor, holeThickness);
1392 1393 1394 1395 1396 1397 1398 1399 1400
    }
  }
}

Size CirclesGridFinder::getDetectedGridSize() const
{
  if (holes.size() == 0)
    return Size(0, 0);

1401
  return Size((int)holes[0].size(), (int)holes.size());
1402 1403
}

1404
void CirclesGridFinder::getHoles(std::vector<Point2f> &outHoles) const
1405 1406 1407 1408 1409 1410 1411
{
  outHoles.clear();

  for (size_t i = 0; i < holes.size(); i++)
  {
    for (size_t j = 0; j < holes[i].size(); j++)
    {
I
Ilya Lysenkov 已提交
1412
      outHoles.push_back(keypoints[holes[i][j]]);
1413 1414 1415
    }
  }
}
1416

1417
static bool areIndicesCorrect(Point pos, std::vector<std::vector<size_t> > *points)
1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
{
  if (pos.y < 0 || pos.x < 0)
    return false;
  return (static_cast<size_t> (pos.y) < points->size() && static_cast<size_t> (pos.x) < points->at(pos.y).size());
}

void CirclesGridFinder::getAsymmetricHoles(std::vector<cv::Point2f> &outHoles) const
{
  outHoles.clear();

1428 1429
  std::vector<Point> largeCornerIndices, smallCornerIndices;
  std::vector<Point> firstSteps, secondSteps;
1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
  size_t cornerIdx = getFirstCorner(largeCornerIndices, smallCornerIndices, firstSteps, secondSteps);
  CV_Assert(largeHoles != 0 && smallHoles != 0)
    ;

  Point srcLargePos = largeCornerIndices[cornerIdx];
  Point srcSmallPos = smallCornerIndices[cornerIdx];

  while (areIndicesCorrect(srcLargePos, largeHoles) || areIndicesCorrect(srcSmallPos, smallHoles))
  {
    Point largePos = srcLargePos;
    while (areIndicesCorrect(largePos, largeHoles))
    {
      outHoles.push_back(keypoints[largeHoles->at(largePos.y)[largePos.x]]);
      largePos += firstSteps[cornerIdx];
    }
    srcLargePos += secondSteps[cornerIdx];

    Point smallPos = srcSmallPos;
    while (areIndicesCorrect(smallPos, smallHoles))
    {
      outHoles.push_back(keypoints[smallHoles->at(smallPos.y)[smallPos.x]]);
      smallPos += firstSteps[cornerIdx];
    }
    srcSmallPos += secondSteps[cornerIdx];
  }
}

double CirclesGridFinder::getDirection(Point2f p1, Point2f p2, Point2f p3)
{
  Point2f a = p3 - p1;
  Point2f b = p2 - p1;
  return a.x * b.y - a.y * b.x;
}

bool CirclesGridFinder::areSegmentsIntersecting(Segment seg1, Segment seg2)
{
  bool doesStraddle1 = (getDirection(seg2.s, seg2.e, seg1.s) * getDirection(seg2.s, seg2.e, seg1.e)) < 0;
  bool doesStraddle2 = (getDirection(seg1.s, seg1.e, seg2.s) * getDirection(seg1.s, seg1.e, seg2.e)) < 0;
  return doesStraddle1 && doesStraddle2;

  /*
   Point2f t1 = e1-s1;
   Point2f n1(t1.y, -t1.x);
   double c1 = -n1.ddot(s1);

   Point2f t2 = e2-s2;
   Point2f n2(t2.y, -t2.x);
   double c2 = -n2.ddot(s2);

   bool seg1 = ((n1.ddot(s2) + c1) * (n1.ddot(e2) + c1)) <= 0;
   bool seg1 = ((n2.ddot(s1) + c2) * (n2.ddot(e1) + c2)) <= 0;

   return seg1 && seg2;
   */
}

1486 1487 1488
void CirclesGridFinder::getCornerSegments(const std::vector<std::vector<size_t> > &points, std::vector<std::vector<Segment> > &segments,
                                          std::vector<Point> &cornerIndices, std::vector<Point> &firstSteps,
                                          std::vector<Point> &secondSteps) const
1489 1490 1491 1492 1493
{
  segments.clear();
  cornerIndices.clear();
  firstSteps.clear();
  secondSteps.clear();
1494 1495
  int h = (int)points.size();
  int w = (int)points[0].size();
1496 1497 1498 1499
  CV_Assert(h >= 2 && w >= 2)
    ;

  //all 8 segments with one end in a corner
1500
  std::vector<Segment> corner;
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538
  corner.push_back(Segment(keypoints[points[1][0]], keypoints[points[0][0]]));
  corner.push_back(Segment(keypoints[points[0][0]], keypoints[points[0][1]]));
  segments.push_back(corner);
  cornerIndices.push_back(Point(0, 0));
  firstSteps.push_back(Point(1, 0));
  secondSteps.push_back(Point(0, 1));
  corner.clear();

  corner.push_back(Segment(keypoints[points[0][w - 2]], keypoints[points[0][w - 1]]));
  corner.push_back(Segment(keypoints[points[0][w - 1]], keypoints[points[1][w - 1]]));
  segments.push_back(corner);
  cornerIndices.push_back(Point(w - 1, 0));
  firstSteps.push_back(Point(0, 1));
  secondSteps.push_back(Point(-1, 0));
  corner.clear();

  corner.push_back(Segment(keypoints[points[h - 2][w - 1]], keypoints[points[h - 1][w - 1]]));
  corner.push_back(Segment(keypoints[points[h - 1][w - 1]], keypoints[points[h - 1][w - 2]]));
  segments.push_back(corner);
  cornerIndices.push_back(Point(w - 1, h - 1));
  firstSteps.push_back(Point(-1, 0));
  secondSteps.push_back(Point(0, -1));
  corner.clear();

  corner.push_back(Segment(keypoints[points[h - 1][1]], keypoints[points[h - 1][0]]));
  corner.push_back(Segment(keypoints[points[h - 1][0]], keypoints[points[h - 2][0]]));
  cornerIndices.push_back(Point(0, h - 1));
  firstSteps.push_back(Point(0, -1));
  secondSteps.push_back(Point(1, 0));
  segments.push_back(corner);
  corner.clear();

  //y axis is inverted in computer vision so we check < 0
  bool isClockwise =
      getDirection(keypoints[points[0][0]], keypoints[points[0][w - 1]], keypoints[points[h - 1][w - 1]]) < 0;
  if (!isClockwise)
  {
#ifdef DEBUG_CIRCLES
R
rmensing 已提交
1539
    std::cout << "Corners are counterclockwise" << std::endl;
1540 1541
#endif
    std::reverse(segments.begin(), segments.end());
1542 1543 1544 1545
    std::reverse(cornerIndices.begin(), cornerIndices.end());
    std::reverse(firstSteps.begin(), firstSteps.end());
    std::reverse(secondSteps.begin(), secondSteps.end());
    std::swap(firstSteps, secondSteps);
1546 1547 1548
  }
}

1549
bool CirclesGridFinder::doesIntersectionExist(const std::vector<Segment> &corner, const std::vector<std::vector<Segment> > &segments)
1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
{
  for (size_t i = 0; i < corner.size(); i++)
  {
    for (size_t j = 0; j < segments.size(); j++)
    {
      for (size_t k = 0; k < segments[j].size(); k++)
      {
        if (areSegmentsIntersecting(corner[i], segments[j][k]))
          return true;
      }
    }
  }

  return false;
}

1566 1567
size_t CirclesGridFinder::getFirstCorner(std::vector<Point> &largeCornerIndices, std::vector<Point> &smallCornerIndices, std::vector<
    Point> &firstSteps, std::vector<Point> &secondSteps) const
1568
{
1569 1570
  std::vector<std::vector<Segment> > largeSegments;
  std::vector<std::vector<Segment> > smallSegments;
1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588

  getCornerSegments(*largeHoles, largeSegments, largeCornerIndices, firstSteps, secondSteps);
  getCornerSegments(*smallHoles, smallSegments, smallCornerIndices, firstSteps, secondSteps);

  const size_t cornersCount = 4;
  CV_Assert(largeSegments.size() == cornersCount)
    ;

  bool isInsider[cornersCount];

  for (size_t i = 0; i < cornersCount; i++)
  {
    isInsider[i] = doesIntersectionExist(largeSegments[i], smallSegments);
  }

  int cornerIdx = 0;
  bool waitOutsider = true;

1589
  for(;;)
1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
  {
    if (waitOutsider)
    {
      if (!isInsider[(cornerIdx + 1) % cornersCount])
        waitOutsider = false;
    }
    else
    {
      if (isInsider[(cornerIdx + 1) % cornersCount])
        break;
    }

    cornerIdx = (cornerIdx + 1) % cornersCount;
  }

  return cornerIdx;
}