icp.cpp 14.3 KB
Newer Older
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
//
//  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) 2014, OpenCV Foundation, 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.
//
// Author: Tolga Birdal <tbirdal AT gmail.com>

#include "precomp.hpp"

namespace cv
{
namespace ppf_match_3d
{
static void subtractColumns(Mat srcPC, double mean[3])
{
Bence Magyar's avatar
Bence Magyar committed
49 50 51 52
  int height = srcPC.rows;

  for (int i=0; i<height; i++)
  {
53
    float *row = srcPC.ptr<float>(i);
54
    {
Bence Magyar's avatar
Bence Magyar committed
55 56 57
      row[0]-=(float)mean[0];
      row[1]-=(float)mean[1];
      row[2]-=(float)mean[2];
58
    }
Bence Magyar's avatar
Bence Magyar committed
59
  }
60 61 62 63 64
}

// as in PCA
static void computeMeanCols(Mat srcPC, double mean[3])
{
Bence Magyar's avatar
Bence Magyar committed
65 66 67 68 69 70
  int height = srcPC.rows;

  double mean1=0, mean2 = 0, mean3 = 0;

  for (int i=0; i<height; i++)
  {
71
    const float *row = srcPC.ptr<float>(i);
72
    {
Bence Magyar's avatar
Bence Magyar committed
73 74 75
      mean1 += (double)row[0];
      mean2 += (double)row[1];
      mean3 += (double)row[2];
76
    }
Bence Magyar's avatar
Bence Magyar committed
77 78 79 80 81 82 83 84 85
  }

  mean1/=(double)height;
  mean2/=(double)height;
  mean3/=(double)height;

  mean[0] = mean1;
  mean[1] = mean2;
  mean[2] = mean3;
86 87 88 89 90 91 92 93 94 95 96 97
}

// as in PCA
/*static void subtractMeanFromColumns(Mat srcPC, double mean[3])
{
    computeMeanCols(srcPC, mean);
    subtractColumns(srcPC, mean);
}*/

// compute the average distance to the origin
static double computeDistToOrigin(Mat srcPC)
{
Bence Magyar's avatar
Bence Magyar committed
98 99 100 101 102
  int height = srcPC.rows;
  double dist = 0;

  for (int i=0; i<height; i++)
  {
103
    const float *row = srcPC.ptr<float>(i);
Bence Magyar's avatar
Bence Magyar committed
104 105 106 107
    dist += sqrt(row[0]*row[0]+row[1]*row[1]+row[2]*row[2]);
  }

  return dist;
108 109 110 111 112
}

// From numerical receipes: Finds the median of an array
static float medianF(float arr[], int n)
{
Bence Magyar's avatar
Bence Magyar committed
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
  int low, high ;
  int median;
  int middle, ll, hh;

  low = 0 ;
  high = n-1 ;
  median = (low + high) >>1;
  for (;;)
  {
    if (high <= low) /* One element only */
      return arr[median] ;

    if (high == low + 1)
    {
      /* Two elements only */
      if (arr[low] > arr[high])
        std::swap(arr[low], arr[high]) ;
      return arr[median] ;
    }

    /* Find median of low, middle and high items; swap into position low */
    middle = (low + high) >>1;
    if (arr[middle] > arr[high])
      std::swap(arr[middle], arr[high]) ;
    if (arr[low] > arr[high])
      std::swap(arr[low], arr[high]) ;
    if (arr[middle] > arr[low])
      std::swap(arr[middle], arr[low]) ;

    /* Swap low item (now in position middle) into position (low+1) */
    std::swap(arr[middle], arr[low+1]) ;

    /* Nibble from each end towards middle, swapping items when stuck */
    ll = low + 1;
    hh = high;
148 149
    for (;;)
    {
Bence Magyar's avatar
Bence Magyar committed
150 151 152 153 154 155 156 157 158 159 160
      do
        ll++;
      while (arr[low] > arr[ll]) ;
      do
        hh--;
      while (arr[hh]  > arr[low]) ;

      if (hh < ll)
        break;

      std::swap(arr[ll], arr[hh]) ;
161
    }
Bence Magyar's avatar
Bence Magyar committed
162 163 164 165 166 167 168 169 170 171

    /* Swap middle item (in position low) back into correct position */
    std::swap(arr[low], arr[hh]) ;

    /* Re-set active partition */
    if (hh <= median)
      low = ll;
    if (hh >= median)
      high = hh - 1;
  }
172 173 174 175
}

static float getRejectionThreshold(float* r, int m, float outlierScale)
{
Bence Magyar's avatar
Bence Magyar committed
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
  float* t=(float*)calloc(m, sizeof(float));
  int i=0;
  float s=0, medR, threshold;

  memcpy(t, r, m*sizeof(float));
  medR=medianF(t, m);

  for (i=0; i<m; i++)
    t[i] = (float)fabs((double)r[i]-(double)medR);

  s = 1.48257968f * medianF(t, m);

  threshold = (outlierScale*s+medR);

  free(t);
  return threshold;
192 193 194 195 196
}

// Kok Lim Low's linearization
static void minimizePointToPlaneMetric(Mat Src, Mat Dst, Mat& X)
{
Bence Magyar's avatar
Bence Magyar committed
197 198 199 200
  //Mat sub = Dst - Src;
  Mat A = Mat(Src.rows, 6, CV_64F);
  Mat b = Mat(Src.rows, 1, CV_64F);

201 202 203
#if defined _OPENMP
#pragma omp parallel for
#endif
Bence Magyar's avatar
Bence Magyar committed
204 205
  for (int i=0; i<Src.rows; i++)
  {
206 207
    const double *srcPt = Src.ptr<double>(i);
    const double *dstPt = Dst.ptr<double>(i);
Bence Magyar's avatar
Bence Magyar committed
208
    const double *normals = &dstPt[3];
209 210
    double *bVal = b.ptr<double>(i);
    double *aRow = A.ptr<double>(i);
Bence Magyar's avatar
Bence Magyar committed
211 212 213 214 215 216 217 218 219 220 221 222

    const double sub[3]={dstPt[0]-srcPt[0], dstPt[1]-srcPt[1], dstPt[2]-srcPt[2]};

    *bVal = TDot3(sub, normals);
    TCross(srcPt, normals, aRow);

    aRow[3] = normals[0];
    aRow[4] = normals[1];
    aRow[5] = normals[2];
  }

  cv::solve(A, b, X, DECOMP_SVD);
223 224 225 226 227
}


static void getTransformMat(Mat X, double Pose[16])
{
Bence Magyar's avatar
Bence Magyar committed
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
  Mat DCM;
  double *r1, *r2, *r3;
  double* x = (double*)X.data;

  const double sx = sin(x[0]);
  const double cx = cos(x[0]);
  const double sy = sin(x[1]);
  const double cy = cos(x[1]);
  const double sz = sin(x[2]);
  const double cz = cos(x[2]);

  Mat R1 = Mat::eye(3,3, CV_64F);
  Mat R2 = Mat::eye(3,3, CV_64F);
  Mat R3 = Mat::eye(3,3, CV_64F);

  r1= (double*)R1.data;
  r2= (double*)R2.data;
  r3= (double*)R3.data;

  r1[4]= cx;
  r1[5]= -sx;
  r1[7]= sx;
  r1[8]= cx;

  r2[0]= cy;
  r2[2]= sy;
  r2[6]= -sy;
  r2[8]= cy;

  r3[0]= cz;
  r3[1]= -sz;
  r3[3]= sz;
  r3[4]= cz;

  DCM = R1*(R2*R3);

  Pose[0] = DCM.at<double>(0,0);
  Pose[1] = DCM.at<double>(0,1);
  Pose[2] = DCM.at<double>(0,2);
  Pose[4] = DCM.at<double>(1,0);
  Pose[5] = DCM.at<double>(1,1);
  Pose[6] = DCM.at<double>(1,2);
  Pose[8] = DCM.at<double>(2,0);
  Pose[9] = DCM.at<double>(2,1);
  Pose[10] = DCM.at<double>(2,2);
  Pose[3]=x[3];
  Pose[7]=x[4];
  Pose[11]=x[5];
  Pose[15]=1;
277 278 279 280 281 282 283 284
}

/* Fast way to look up the duplicates
duplicates is pre-allocated
make sure that the max element in array will not exceed maxElement
*/
static hashtable_int* getHashtable(int* data, size_t length, int numMaxElement)
{
Bence Magyar's avatar
Bence Magyar committed
285 286 287 288 289 290 291 292
  hashtable_int* hashtable = hashtableCreate(static_cast<size_t>(numMaxElement*2), 0);
  for (size_t i = 0; i < length; i++)
  {
    const KeyType key = (KeyType)data[i];
    hashtableInsertHashed(hashtable, key+1, reinterpret_cast<void*>(i+1));
  }

  return hashtable;
293 294 295
}

// source point clouds are assumed to contain their normals
Hamdi Sahloul's avatar
Hamdi Sahloul committed
296
int ICP::registerModelToScene(const Mat& srcPC, const Mat& dstPC, double& residual, Matx44d& pose)
297
{
Bence Magyar's avatar
Bence Magyar committed
298 299
  int n = srcPC.rows;

300
  const bool useRobustReject = m_rejectionScale>0;
Bence Magyar's avatar
Bence Magyar committed
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322

  Mat srcTemp = srcPC.clone();
  Mat dstTemp = dstPC.clone();
  double meanSrc[3], meanDst[3];
  computeMeanCols(srcTemp, meanSrc);
  computeMeanCols(dstTemp, meanDst);
  double meanAvg[3]={0.5*(meanSrc[0]+meanDst[0]), 0.5*(meanSrc[1]+meanDst[1]), 0.5*(meanSrc[2]+meanDst[2])};
  subtractColumns(srcTemp, meanAvg);
  subtractColumns(dstTemp, meanAvg);

  double distSrc = computeDistToOrigin(srcTemp);
  double distDst = computeDistToOrigin(dstTemp);

  double scale = (double)n / ((distSrc + distDst)*0.5);

  srcTemp(cv::Range(0, srcTemp.rows), cv::Range(0,3)) *= scale;
  dstTemp(cv::Range(0, dstTemp.rows), cv::Range(0,3)) *= scale;

  Mat srcPC0 = srcTemp;
  Mat dstPC0 = dstTemp;

  // initialize pose
Hamdi Sahloul's avatar
Hamdi Sahloul committed
323
  matrixIdentity(4, pose.val);
Bence Magyar's avatar
Bence Magyar committed
324 325 326 327 328 329 330 331 332 333 334 335 336

  Mat M = Mat::eye(4,4,CV_64F);

  double tempResidual = 0;


  // walk the pyramid
  for (int level = m_numLevels-1; level >=0; level--)
  {
    const double impact = 2;
    double div = pow((double)impact, (double)level);
    //double div2 = div*div;
    const int numSamples = cvRound((double)(n/(div)));
337 338
    const double TolP = m_tolerance*(double)(level+1)*(level+1);
    const int MaxIterationsPyr = cvRound((double)m_maxIterations/(level+1));
Bence Magyar's avatar
Bence Magyar committed
339 340

    // Obtain the sampled point clouds for this level: Also rotates the normals
Hamdi Sahloul's avatar
Hamdi Sahloul committed
341
    Mat srcPCT = transformPCPose(srcPC0, pose.val);
Bence Magyar's avatar
Bence Magyar committed
342 343 344

    const int sampleStep = cvRound((double)n/(double)numSamples);

345
    srcPCT = samplePCUniform(srcPCT, sampleStep);
Bence Magyar's avatar
Bence Magyar committed
346
    /*
347 348
    Tolga Birdal thinks that downsampling the scene points might decrease the accuracy.
    Hamdi Sahloul, however, noticed that accuracy increased (pose residual decreased slightly).
Bence Magyar's avatar
Bence Magyar committed
349
    */
350 351
    Mat dstPCS = samplePCUniform(dstPC0, sampleStep);
    void* flann = indexPCFlann(dstPCS);
Bence Magyar's avatar
Bence Magyar committed
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

    double fval_old=9999999999;
    double fval_perc=0;
    double fval_min=9999999999;
    Mat Src_Moved = srcPCT.clone();

    int i=0;

    size_t numElSrc = (size_t)Src_Moved.rows;
    int sizesResult[2] = {(int)numElSrc, 1};
    float* distances = new float[numElSrc];
    int* indices = new int[numElSrc];

    Mat Indices(2, sizesResult, CV_32S, indices, 0);
    Mat Distances(2, sizesResult, CV_32F, distances, 0);

    // use robust weighting for outlier treatment
    int* indicesModel = new int[numElSrc];
    int* indicesScene = new int[numElSrc];

    int* newI = new int[numElSrc];
    int* newJ = new int[numElSrc];

    double PoseX[16]={0};
    matrixIdentity(4, PoseX);

    while ( (!(fval_perc<(1+TolP) && fval_perc>(1-TolP))) && i<MaxIterationsPyr)
379
    {
380
      uint di=0, selInd = 0;
Bence Magyar's avatar
Bence Magyar committed
381 382 383 384 385

      queryPCFlann(flann, Src_Moved, Indices, Distances);

      for (di=0; di<numElSrc; di++)
      {
386
        newI[di] = di;
Bence Magyar's avatar
Bence Magyar committed
387 388 389
        newJ[di] = indices[di];
      }

390
      if (useRobustReject)
Bence Magyar's avatar
Bence Magyar committed
391 392 393 394 395 396 397
      {
        int numInliers = 0;
        float threshold = getRejectionThreshold(distances, Distances.rows, m_rejectionScale);
        Mat acceptInd = Distances<threshold;

        uchar *accPtr = (uchar*)acceptInd.data;
        for (int l=0; l<acceptInd.rows; l++)
398
        {
Bence Magyar's avatar
Bence Magyar committed
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
          if (accPtr[l])
          {
            newI[numInliers] = l;
            newJ[numInliers] = indices[l];
            numInliers++;
          }
        }
        numElSrc=numInliers;
      }

      // Step 2: Picky ICP
      // Among the resulting corresponding pairs, if more than one scene point p_i
      // is assigned to the same model point m_j, then select p_i that corresponds
      // to the minimum distance

414
      hashtable_int* duplicateTable = getHashtable(newJ, numElSrc, dstPCS.rows);
Bence Magyar's avatar
Bence Magyar committed
415 416 417 418 419 420 421 422

      for (di=0; di<duplicateTable->size; di++)
      {
        hashnode_i *node = duplicateTable->nodes[di];

        if (node)
        {
          // select the first node
423
          size_t idx = reinterpret_cast<size_t>(node->data)-1, dn=0;
Bence Magyar's avatar
Bence Magyar committed
424
          int dup = (int)node->key-1;
425
          size_t minIdxD = idx;
Bence Magyar's avatar
Bence Magyar committed
426 427 428 429
          float minDist = distances[idx];

          while ( node )
          {
430
            idx = reinterpret_cast<size_t>(node->data)-1;
Bence Magyar's avatar
Bence Magyar committed
431 432

            if (distances[idx] < minDist)
433
            {
Bence Magyar's avatar
Bence Magyar committed
434 435
              minDist = distances[idx];
              minIdxD = idx;
436
            }
Bence Magyar's avatar
Bence Magyar committed
437 438 439 440 441 442 443 444

            node = node->next;
            dn++;
          }

          indicesModel[ selInd ] = newI[ minIdxD ];
          indicesScene[ selInd ] = dup ;
          selInd++;
445
        }
Bence Magyar's avatar
Bence Magyar committed
446 447 448 449
      }

      hashtableDestroy(duplicateTable);

450
      if (selInd >= 6)
Bence Magyar's avatar
Bence Magyar committed
451 452
      {

453 454
        Mat Src_Match = Mat(selInd, srcPCT.cols, CV_64F);
        Mat Dst_Match = Mat(selInd, srcPCT.cols, CV_64F);
Bence Magyar's avatar
Bence Magyar committed
455 456 457 458 459

        for (di=0; di<selInd; di++)
        {
          const int indModel = indicesModel[di];
          const int indScene = indicesScene[di];
460
          const float *srcPt = srcPCT.ptr<float>(indModel);
461
          const float *dstPt = dstPCS.ptr<float>(indScene);
462 463
          double *srcMatchPt = Src_Match.ptr<double>(di);
          double *dstMatchPt = Dst_Match.ptr<double>(di);
Bence Magyar's avatar
Bence Magyar committed
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
          int ci=0;

          for (ci=0; ci<srcPCT.cols; ci++)
          {
            srcMatchPt[ci] = (double)srcPt[ci];
            dstMatchPt[ci] = (double)dstPt[ci];
          }
        }

        Mat X;
        minimizePointToPlaneMetric(Src_Match, Dst_Match, X);

        getTransformMat(X, PoseX);
        Src_Moved = transformPCPose(srcPCT, PoseX);

        double fval = cv::norm(Src_Match, Dst_Match)/(double)(Src_Moved.rows);

        // Calculate change in error between iterations
        fval_perc=fval/fval_old;

        // Store error value
        fval_old=fval;

        if (fval < fval_min)
          fval_min = fval;
      }
      else
        break;

      i++;

495
    }
Bence Magyar's avatar
Bence Magyar committed
496 497

    double TempPose[16];
Hamdi Sahloul's avatar
Hamdi Sahloul committed
498
    matrixProduct44(PoseX, pose.val, TempPose);
Bence Magyar's avatar
Bence Magyar committed
499 500 501

    // no need to copy the last 4 rows
    for (int c=0; c<12; c++)
Hamdi Sahloul's avatar
Hamdi Sahloul committed
502
      pose.val[c] = TempPose[c];
Bence Magyar's avatar
Bence Magyar committed
503

504
    residual = tempResidual;
Bence Magyar's avatar
Bence Magyar committed
505 506 507 508 509 510 511 512 513

    delete[] newI;
    delete[] newJ;
    delete[] indicesModel;
    delete[] indicesScene;
    delete[] distances;
    delete[] indices;

    tempResidual = fval_min;
514
    destroyFlann(flann);
Bence Magyar's avatar
Bence Magyar committed
515 516 517
  }

  // Pose(1:3, 4) = Pose(1:3, 4)./scale;
Hamdi Sahloul's avatar
Hamdi Sahloul committed
518 519 520
  pose.val[3] = pose.val[3]/scale + meanAvg[0];
  pose.val[7] = pose.val[7]/scale + meanAvg[1];
  pose.val[11] = pose.val[11]/scale + meanAvg[2];
Bence Magyar's avatar
Bence Magyar committed
521 522 523

  // In MATLAB this would be : Pose(1:3, 4) = Pose(1:3, 4)./scale + meanAvg' - Pose(1:3, 1:3)*meanAvg';
  double Rpose[9], Cpose[3];
Hamdi Sahloul's avatar
Hamdi Sahloul committed
524
  poseToR(pose.val, Rpose);
Bence Magyar's avatar
Bence Magyar committed
525
  matrixProduct331(Rpose, meanAvg, Cpose);
Hamdi Sahloul's avatar
Hamdi Sahloul committed
526 527 528
  pose.val[3] -= Cpose[0];
  pose.val[7] -= Cpose[1];
  pose.val[11] -= Cpose[2];
Bence Magyar's avatar
Bence Magyar committed
529

530
  residual = tempResidual;
Bence Magyar's avatar
Bence Magyar committed
531 532

  return 0;
533 534 535
}

// source point clouds are assumed to contain their normals
536
int ICP::registerModelToScene(const Mat& srcPC, const Mat& dstPC, std::vector<Pose3DPtr>& poses)
537
{
538 539 540 541
  #if defined _OPENMP
  #pragma omp parallel for
  #endif
  for (int i=0; i<(int)poses.size(); i++)
Bence Magyar's avatar
Bence Magyar committed
542
  {
Hamdi Sahloul's avatar
Hamdi Sahloul committed
543
    Matx44d poseICP = Matx44d::eye();
544 545
    Mat srcTemp = transformPCPose(srcPC, poses[i]->pose);
    registerModelToScene(srcTemp, dstPC, poses[i]->residual, poseICP);
Hamdi Sahloul's avatar
Hamdi Sahloul committed
546
    poses[i]->appendPose(poseICP.val);
Bence Magyar's avatar
Bence Magyar committed
547 548
  }
  return 0;
549 550 551 552 553
}

} // namespace ppf_match_3d

} // namespace cv