ppf_helpers.cpp 20.7 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 49 50 51 52 53 54 55 56 57 58 59
//
//  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
{

typedef cv::flann::L2<float> Distance_32F;
typedef cv::flann::GenericIndex< Distance_32F > FlannIndex;

void shuffle(int *array, size_t n);
Mat genRandomMat(int rows, int cols, double mean, double stddev, int type);
void getRandQuat(double q[4]);
void getRandomRotation(double R[9]);
void meanCovLocalPC(const float* pc, const int ws, const int point_count, double CovMat[3][3], double Mean[4]);
void meanCovLocalPCInd(const float* pc, const int* Indices, const int ws, const int point_count, double CovMat[3][3], double Mean[4]);

Mat loadPLYSimple(const char* fileName, int withNormals)
{
Bence Magyar's avatar
Bence Magyar committed
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
  Mat cloud;
  int numVertices=0;

  std::ifstream ifs(fileName);

  if (!ifs.is_open())
  {
    printf("Cannot open file...\n");
    return Mat();
  }

  std::string str;
  while (str.substr(0, 10) !="end_header")
  {
    std::string entry = str.substr(0, 14);
    if (entry == "element vertex")
76
    {
Bence Magyar's avatar
Bence Magyar committed
77
      numVertices = atoi(str.substr(15, str.size()-15).c_str());
78
    }
Bence Magyar's avatar
Bence Magyar committed
79 80 81 82 83 84 85 86 87 88
    std::getline(ifs, str);
  }

  if (withNormals)
    cloud=Mat(numVertices, 6, CV_32FC1);
  else
    cloud=Mat(numVertices, 3, CV_32FC1);

  for (int i = 0; i < numVertices; i++)
  {
89
    float* data = cloud.ptr<float>(i);
Bence Magyar's avatar
Bence Magyar committed
90
    if (withNormals)
91
    {
Bence Magyar's avatar
Bence Magyar committed
92 93 94 95 96 97 98 99 100 101
      ifs >> data[0] >> data[1] >> data[2] >> data[3] >> data[4] >> data[5];

      // normalize to unit norm
      double norm = sqrt(data[3]*data[3] + data[4]*data[4] + data[5]*data[5]);
      if (norm>0.00001)
      {
        data[3]/=(float)norm;
        data[4]/=(float)norm;
        data[5]/=(float)norm;
      }
102 103 104
    }
    else
    {
Bence Magyar's avatar
Bence Magyar committed
105
      ifs >> data[0] >> data[1] >> data[2];
106
    }
Bence Magyar's avatar
Bence Magyar committed
107 108 109 110
  }

  //cloud *= 5.0f;
  return cloud;
111 112 113 114
}

void writePLY(Mat PC, const char* FileName)
{
Bence Magyar's avatar
Bence Magyar committed
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
  std::ofstream outFile( FileName );

  if ( !outFile )
  {
    //cerr << "Error opening output file: " << FileName << "!" << endl;
    printf("Error opening output file: %s!\n", FileName);
    exit( 1 );
  }

  ////
  // Header
  ////

  const int pointNum = ( int ) PC.rows;
  const int vertNum  = ( int ) PC.cols;

  outFile << "ply" << std::endl;
  outFile << "format ascii 1.0" << std::endl;
  outFile << "element vertex " << pointNum << std::endl;
  outFile << "property float x" << std::endl;
  outFile << "property float y" << std::endl;
  outFile << "property float z" << std::endl;
  if (vertNum==6)
  {
    outFile << "property float nx" << std::endl;
    outFile << "property float ny" << std::endl;
    outFile << "property float nz" << std::endl;
  }
  outFile << "end_header" << std::endl;

  ////
  // Points
  ////

  for ( int pi = 0; pi < pointNum; ++pi )
  {
151
    const float* point = PC.ptr<float>(pi);
Bence Magyar's avatar
Bence Magyar committed
152 153 154

    outFile << point[0] << " "<<point[1]<<" "<<point[2];

155 156
    if (vertNum==6)
    {
Bence Magyar's avatar
Bence Magyar committed
157
      outFile<<" " << point[3] << " "<<point[4]<<" "<<point[5];
158
    }
Bence Magyar's avatar
Bence Magyar committed
159 160 161 162 163

    outFile << std::endl;
  }

  return;
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
void writePLYVisibleNormals(Mat PC, const char* FileName)
{
  std::ofstream outFile(FileName);

  if (!outFile)
  {
    //cerr << "Error opening output file: " << FileName << "!" << endl;
    printf("Error opening output file: %s!\n", FileName);
    exit(1);
  }

  ////
  // Header
  ////

  const int pointNum = (int)PC.rows;
  const int vertNum = (int)PC.cols;
  const bool hasNormals = vertNum == 6;

  outFile << "ply" << std::endl;
  outFile << "format ascii 1.0" << std::endl;
  outFile << "element vertex " << (hasNormals? 2*pointNum:pointNum) << std::endl;
  outFile << "property float x" << std::endl;
  outFile << "property float y" << std::endl;
  outFile << "property float z" << std::endl;
  if (hasNormals)
  {
    outFile << "property uchar red" << std::endl;
    outFile << "property uchar green" << std::endl;
    outFile << "property uchar blue" << std::endl;
  }
  outFile << "end_header" << std::endl;

  ////
  // Points
  ////

  for (int pi = 0; pi < pointNum; ++pi)
  {
205
    const float* point = PC.ptr<float>(pi);
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221

    outFile << point[0] << " " << point[1] << " " << point[2];

    if (hasNormals)
    {
      outFile << " 127 127 127" << std::endl;
      outFile << point[0]+point[3] << " " << point[1]+point[4] << " " << point[2]+point[5];
      outFile << " 255 0 0";
    }

    outFile << std::endl;
  }

  return;
}

222 223
Mat samplePCUniform(Mat PC, int sampleStep)
{
Bence Magyar's avatar
Bence Magyar committed
224 225 226 227 228 229 230 231 232 233
  int numRows = PC.rows/sampleStep;
  Mat sampledPC = Mat(numRows, PC.cols, PC.type());

  int c=0;
  for (int i=0; i<PC.rows && c<numRows; i+=sampleStep)
  {
    PC.row(i).copyTo(sampledPC.row(c++));
  }

  return sampledPC;
234 235 236 237
}

Mat samplePCUniformInd(Mat PC, int sampleStep, std::vector<int> &indices)
{
Bence Magyar's avatar
Bence Magyar committed
238 239 240 241 242 243 244 245 246 247 248 249
  int numRows = cvRound((double)PC.rows/(double)sampleStep);
  indices.resize(numRows);
  Mat sampledPC = Mat(numRows, PC.cols, PC.type());

  int c=0;
  for (int i=0; i<PC.rows && c<numRows; i+=sampleStep)
  {
    indices[c] = i;
    PC.row(i).copyTo(sampledPC.row(c++));
  }

  return sampledPC;
250 251 252 253
}

void* indexPCFlann(Mat pc)
{
Bence Magyar's avatar
Bence Magyar committed
254 255 256
  Mat dest_32f;
  pc.colRange(0,3).copyTo(dest_32f);
  return new FlannIndex(dest_32f, cvflann::KDTreeSingleIndexParams(8));
257 258 259 260
}

void destroyFlann(void* flannIndex)
{
Bence Magyar's avatar
Bence Magyar committed
261
  delete ((FlannIndex*)flannIndex);
262 263 264
}

// For speed purposes this function assumes that PC, Indices and Distances are created with continuous structures
Bence Magyar's avatar
Bence Magyar committed
265
void queryPCFlann(void* flannIndex, Mat& pc, Mat& indices, Mat& distances)
266 267 268 269 270
{
  queryPCFlann(flannIndex, pc, indices, distances, 1);
}

void queryPCFlann(void* flannIndex, Mat& pc, Mat& indices, Mat& distances, const int numNeighbors)
271
{
Bence Magyar's avatar
Bence Magyar committed
272
  Mat obj_32f;
273 274
  pc.colRange(0, 3).copyTo(obj_32f);
  ((FlannIndex*)flannIndex)->knnSearch(obj_32f, indices, distances, numNeighbors, cvflann::SearchParams(32));
275 276 277 278 279 280 281
}

// uses a volume instead of an octree
// TODO: Right now normals are required.
// This is much faster than sample_pc_octree
Mat samplePCByQuantization(Mat pc, float xrange[2], float yrange[2], float zrange[2], float sampleStep, int weightByCenter)
{
Bence Magyar's avatar
Bence Magyar committed
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
  std::vector< std::vector<int> > map;

  int numSamplesDim = (int)(1.0/sampleStep);

  float xr = xrange[1] - xrange[0];
  float yr = yrange[1] - yrange[0];
  float zr = zrange[1] - zrange[0];

  int numPoints = 0;

  map.resize((numSamplesDim+1)*(numSamplesDim+1)*(numSamplesDim+1));

  // OpenMP might seem like a good idea, but it didn't speed this up for me
  //#pragma omp parallel for
  for (int i=0; i<pc.rows; i++)
  {
298
    const float* point = pc.ptr<float>(i);
Bence Magyar's avatar
Bence Magyar committed
299 300 301 302 303 304 305 306

    // quantize a point
    const int xCell =(int) ((float)numSamplesDim*(point[0]-xrange[0])/xr);
    const int yCell =(int) ((float)numSamplesDim*(point[1]-yrange[0])/yr);
    const int zCell =(int) ((float)numSamplesDim*(point[2]-zrange[0])/zr);
    const int index = xCell*numSamplesDim*numSamplesDim+yCell*numSamplesDim+zCell;

    /*#pragma omp critical
307
        {*/
Bence Magyar's avatar
Bence Magyar committed
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
    map[index].push_back(i);
    //  }
  }

  for (unsigned int i=0; i<map.size(); i++)
  {
    numPoints += (map[i].size()>0);
  }

  Mat pcSampled = Mat(numPoints, pc.cols, CV_32F);
  int c = 0;

  for (unsigned int i=0; i<map.size(); i++)
  {
    double px=0, py=0, pz=0;
    double nx=0, ny=0, nz=0;

    std::vector<int> curCell = map[i];
    int cn = (int)curCell.size();
    if (cn>0)
328
    {
Bence Magyar's avatar
Bence Magyar committed
329 330 331 332 333 334 335 336 337 338 339 340 341 342
      if (weightByCenter)
      {
        int xCell, yCell, zCell;
        double xc, yc, zc;
        double weightSum = 0 ;
        zCell = i % numSamplesDim;
        yCell = ((i-zCell)/numSamplesDim) % numSamplesDim;
        xCell = ((i-zCell-yCell*numSamplesDim)/(numSamplesDim*numSamplesDim));

        xc = ((double)xCell+0.5) * (double)xr/numSamplesDim + (double)xrange[0];
        yc = ((double)yCell+0.5) * (double)yr/numSamplesDim + (double)yrange[0];
        zc = ((double)zCell+0.5) * (double)zr/numSamplesDim + (double)zrange[0];

        for (int j=0; j<cn; j++)
343
        {
Bence Magyar's avatar
Bence Magyar committed
344
          const int ptInd = curCell[j];
345
          float* point = pc.ptr<float>(ptInd);
Bence Magyar's avatar
Bence Magyar committed
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
          const double dx = point[0]-xc;
          const double dy = point[1]-yc;
          const double dz = point[2]-zc;
          const double d = sqrt(dx*dx+dy*dy+dz*dz);
          double w = 0;

          if (d>EPS)
          {
            // it is possible to use different weighting schemes.
            // inverse weigthing was just good for me
            // exp( - (distance/h)**2 )
            //const double w = exp(-d*d);
            w = 1.0/d;
          }

          //float weights[3]={1,1,1};
          px += w*(double)point[0];
          py += w*(double)point[1];
          pz += w*(double)point[2];
          nx += w*(double)point[3];
          ny += w*(double)point[4];
          nz += w*(double)point[5];

          weightSum+=w;
370
        }
Bence Magyar's avatar
Bence Magyar committed
371 372 373 374 375 376 377 378 379 380 381 382
        px/=(double)weightSum;
        py/=(double)weightSum;
        pz/=(double)weightSum;
        nx/=(double)weightSum;
        ny/=(double)weightSum;
        nz/=(double)weightSum;
      }
      else
      {
        for (int j=0; j<cn; j++)
        {
          const int ptInd = curCell[j];
383
          float* point = pc.ptr<float>(ptInd);
Bence Magyar's avatar
Bence Magyar committed
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401

          px += (double)point[0];
          py += (double)point[1];
          pz += (double)point[2];
          nx += (double)point[3];
          ny += (double)point[4];
          nz += (double)point[5];
        }

        px/=(double)cn;
        py/=(double)cn;
        pz/=(double)cn;
        nx/=(double)cn;
        ny/=(double)cn;
        nz/=(double)cn;

      }

402
      float *pcData = pcSampled.ptr<float>(c);
Bence Magyar's avatar
Bence Magyar committed
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
      pcData[0]=(float)px;
      pcData[1]=(float)py;
      pcData[2]=(float)pz;

      // normalize the normals
      double norm = sqrt(nx*nx+ny*ny+nz*nz);

      if (norm>EPS)
      {
        pcData[3]=(float)(nx/norm);
        pcData[4]=(float)(ny/norm);
        pcData[5]=(float)(nz/norm);
      }
      //#pragma omp atomic
      c++;

      curCell.clear();
420
    }
Bence Magyar's avatar
Bence Magyar committed
421 422 423 424
  }

  map.clear();
  return pcSampled;
425 426 427 428
}

void shuffle(int *array, size_t n)
{
Bence Magyar's avatar
Bence Magyar committed
429 430 431 432 433 434 435 436
  size_t i;
  for (i = 0; i < n - 1; i++)
  {
    size_t j = i + rand() / (RAND_MAX / (n - i) + 1);
    int t = array[j];
    array[j] = array[i];
    array[i] = t;
  }
437 438 439 440 441
}

// compute the standard bounding box
void computeBboxStd(Mat pc, float xRange[2], float yRange[2], float zRange[2])
{
Bence Magyar's avatar
Bence Magyar committed
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
  Mat pcPts = pc.colRange(0, 3);
  int num = pcPts.rows;

  float* points = (float*)pcPts.data;

  xRange[0] = points[0];
  xRange[1] = points[0];
  yRange[0] = points[1];
  yRange[1] = points[1];
  zRange[0] = points[2];
  zRange[1] = points[2];

  for  ( int  ind = 0; ind < num; ind++ )
  {
    const float* row = (float*)(pcPts.data + (ind * pcPts.step));
    const float x = row[0];
    const float y = row[1];
    const float z = row[2];

    if (x<xRange[0])
      xRange[0]=x;
    if (x>xRange[1])
      xRange[1]=x;

    if (y<yRange[0])
      yRange[0]=y;
    if (y>yRange[1])
      yRange[1]=y;

    if (z<zRange[0])
      zRange[0]=z;
    if (z>zRange[1])
      zRange[1]=z;
  }
476 477 478 479
}

Mat normalizePCCoeff(Mat pc, float scale, float* Cx, float* Cy, float* Cz, float* MinVal, float* MaxVal)
{
Bence Magyar's avatar
Bence Magyar committed
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
  double minVal=0, maxVal=0;

  Mat x,y,z, pcn;
  pc.col(0).copyTo(x);
  pc.col(1).copyTo(y);
  pc.col(2).copyTo(z);

  float cx = (float) cv::mean(x).val[0];
  float cy = (float) cv::mean(y).val[0];
  float cz = (float) cv::mean(z).val[0];

  cv::minMaxIdx(pc, &minVal, &maxVal);

  x=x-cx;
  y=y-cy;
  z=z-cz;
  pcn.create(pc.rows, 3, CV_32FC1);
  x.copyTo(pcn.col(0));
  y.copyTo(pcn.col(1));
  z.copyTo(pcn.col(2));

  cv::minMaxIdx(pcn, &minVal, &maxVal);
  pcn=(float)scale*(pcn)/((float)maxVal-(float)minVal);

  *MinVal=(float)minVal;
  *MaxVal=(float)maxVal;
  *Cx=(float)cx;
  *Cy=(float)cy;
  *Cz=(float)cz;

  return pcn;
511 512 513 514
}

Mat transPCCoeff(Mat pc, float scale, float Cx, float Cy, float Cz, float MinVal, float MaxVal)
{
Bence Magyar's avatar
Bence Magyar committed
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
  Mat x,y,z, pcn;
  pc.col(0).copyTo(x);
  pc.col(1).copyTo(y);
  pc.col(2).copyTo(z);

  x=x-Cx;
  y=y-Cy;
  z=z-Cz;
  pcn.create(pc.rows, 3, CV_32FC1);
  x.copyTo(pcn.col(0));
  y.copyTo(pcn.col(1));
  z.copyTo(pcn.col(2));

  pcn=(float)scale*(pcn)/((float)MaxVal-(float)MinVal);

  return pcn;
531 532 533 534
}

Mat transformPCPose(Mat pc, double Pose[16])
{
Bence Magyar's avatar
Bence Magyar committed
535 536 537 538 539
  Mat pct = Mat(pc.rows, pc.cols, CV_32F);

  double R[9], t[3];
  poseToRT(Pose, R, t);

540 541 542
#if defined _OPENMP
#pragma omp parallel for
#endif
Bence Magyar's avatar
Bence Magyar committed
543 544
  for (int i=0; i<pc.rows; i++)
  {
545 546
    const float *pcData = pc.ptr<float>(i);
    float *pcDataT = pct.ptr<float>(i);
Bence Magyar's avatar
Bence Magyar committed
547 548 549 550 551 552 553 554 555 556
    const float *n1 = &pcData[3];
    float *nT = &pcDataT[3];

    double p[4] = {(double)pcData[0], (double)pcData[1], (double)pcData[2], 1};
    double p2[4];

    matrixProduct441(Pose, p, p2);

    // p2[3] should normally be 1
    if (fabs(p2[3])>EPS)
557
    {
Bence Magyar's avatar
Bence Magyar committed
558 559 560 561 562
      pcDataT[0] = (float)(p2[0]/p2[3]);
      pcDataT[1] = (float)(p2[1]/p2[3]);
      pcDataT[2] = (float)(p2[2]/p2[3]);
    }

563 564 565 566 567
    // If the point cloud has normals,
    // then rotate them as well
    if (pc.cols == 6)
    {
      double n[3] = { (double)n1[0], (double)n1[1], (double)n1[2] }, n2[3];
Bence Magyar's avatar
Bence Magyar committed
568

569 570
      matrixProduct331(R, n, n2);
      double nNorm = sqrt(n2[0]*n2[0]+n2[1]*n2[1]+n2[2]*n2[2]);
Bence Magyar's avatar
Bence Magyar committed
571

572 573 574 575 576 577
      if (nNorm>EPS)
      {
        nT[0]=(float)(n2[0]/nNorm);
        nT[1]=(float)(n2[1]/nNorm);
        nT[2]=(float)(n2[2]/nNorm);
      }
578
    }
Bence Magyar's avatar
Bence Magyar committed
579 580 581
  }

  return pct;
582 583 584 585
}

Mat genRandomMat(int rows, int cols, double mean, double stddev, int type)
{
Bence Magyar's avatar
Bence Magyar committed
586 587 588 589 590 591 592
  Mat meanMat = mean*Mat::ones(1,1,type);
  Mat sigmaMat= stddev*Mat::ones(1,1,type);
  RNG rng(time(0));
  Mat matr(rows, cols,type);
  rng.fill(matr, RNG::NORMAL, meanMat, sigmaMat);

  return matr;
593 594 595 596
}

void getRandQuat(double q[4])
{
Bence Magyar's avatar
Bence Magyar committed
597 598 599 600 601 602 603 604 605 606 607 608
  q[0] = (float)rand()/(float)(RAND_MAX);
  q[1] = (float)rand()/(float)(RAND_MAX);
  q[2] = (float)rand()/(float)(RAND_MAX);
  q[3] = (float)rand()/(float)(RAND_MAX);

  double n = sqrt(q[0]*q[0]+q[1]*q[1]+q[2]*q[2]+q[3]*q[3]);
  q[0]/=n;
  q[1]/=n;
  q[2]/=n;
  q[3]/=n;

  q[0]=fabs(q[0]);
609 610 611 612
}

void getRandomRotation(double R[9])
{
Bence Magyar's avatar
Bence Magyar committed
613 614 615
  double q[4];
  getRandQuat(q);
  quatToDCM(q, R);
616 617 618 619
}

void getRandomPose(double Pose[16])
{
Bence Magyar's avatar
Bence Magyar committed
620 621 622 623 624 625 626 627 628 629
  double R[9], t[3];

  srand((unsigned int)time(0));
  getRandomRotation(R);

  t[0] = (float)rand()/(float)(RAND_MAX);
  t[1] = (float)rand()/(float)(RAND_MAX);
  t[2] = (float)rand()/(float)(RAND_MAX);

  rtToPose(R,t,Pose);
630 631 632 633
}

Mat addNoisePC(Mat pc, double scale)
{
Bence Magyar's avatar
Bence Magyar committed
634 635
  Mat randT = genRandomMat(pc.rows,pc.cols,0,scale,CV_32FC1);
  return randT + pc;
636 637 638 639 640 641 642 643 644 645 646 647
}

/*
The routines below use the eigenvectors of the local covariance matrix
to compute the normals of a point cloud.
The algorithm uses FLANN and Joachim Kopp's fast 3x3 eigenvector computations
to improve accuracy and increase speed
Also, view point flipping as in point cloud library is implemented
*/

void meanCovLocalPC(const float* pc, const int ws, const int point_count, double CovMat[3][3], double Mean[4])
{
Bence Magyar's avatar
Bence Magyar committed
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
  int i;
  double accu[16]={0};

  // For each point in the cloud
  for (i = 0; i < point_count; ++i)
  {
    const float* cloud = &pc[i*ws];
    accu [0] += cloud[0] * cloud[0];
    accu [1] += cloud[0] * cloud[1];
    accu [2] += cloud[0] * cloud[2];
    accu [3] += cloud[1] * cloud[1]; // 4
    accu [4] += cloud[1] * cloud[2]; // 5
    accu [5] += cloud[2] * cloud[2]; // 8
    accu [6] += cloud[0];
    accu [7] += cloud[1];
    accu [8] += cloud[2];
  }

  for (i = 0; i < 9; ++i)
    accu[i]/=(double)point_count;

  Mean[0] = accu[6];
  Mean[1] = accu[7];
  Mean[2] = accu[8];
  Mean[3] = 0;
  CovMat[0][0] = accu [0] - accu [6] * accu [6];
  CovMat[0][1] = accu [1] - accu [6] * accu [7];
  CovMat[0][2] = accu [2] - accu [6] * accu [8];
  CovMat[1][1] = accu [3] - accu [7] * accu [7];
  CovMat[1][2] = accu [4] - accu [7] * accu [8];
  CovMat[2][2] = accu [5] - accu [8] * accu [8];
  CovMat[1][0] = CovMat[0][1];
  CovMat[2][0] = CovMat[0][2];
  CovMat[2][1] = CovMat[1][2];

683 684 685 686
}

void meanCovLocalPCInd(const float* pc, const int* Indices, const int ws, const int point_count, double CovMat[3][3], double Mean[4])
{
Bence Magyar's avatar
Bence Magyar committed
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
  int i;
  double accu[16]={0};

  for (i = 0; i < point_count; ++i)
  {
    const float* cloud = &pc[ Indices[i] * ws ];
    accu [0] += cloud[0] * cloud[0];
    accu [1] += cloud[0] * cloud[1];
    accu [2] += cloud[0] * cloud[2];
    accu [3] += cloud[1] * cloud[1]; // 4
    accu [4] += cloud[1] * cloud[2]; // 5
    accu [5] += cloud[2] * cloud[2]; // 8
    accu [6] += cloud[0];
    accu [7] += cloud[1];
    accu [8] += cloud[2];
  }

  for (i = 0; i < 9; ++i)
    accu[i]/=(double)point_count;

  Mean[0] = accu[6];
  Mean[1] = accu[7];
  Mean[2] = accu[8];
  Mean[3] = 0;
  CovMat[0][0] = accu [0] - accu [6] * accu [6];
  CovMat[0][1] = accu [1] - accu [6] * accu [7];
  CovMat[0][2] = accu [2] - accu [6] * accu [8];
  CovMat[1][1] = accu [3] - accu [7] * accu [7];
  CovMat[1][2] = accu [4] - accu [7] * accu [8];
  CovMat[2][2] = accu [5] - accu [8] * accu [8];
  CovMat[1][0] = CovMat[0][1];
  CovMat[2][0] = CovMat[0][2];
  CovMat[2][1] = CovMat[1][2];

721 722
}

723
CV_EXPORTS int computeNormalsPC3d(const Mat& PC, Mat& PCNormals, const int NumNeighbors, const bool FlipViewpoint, const Vec3d& viewpoint)
724
{
Bence Magyar's avatar
Bence Magyar committed
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
  int i;

  if (PC.cols!=3 && PC.cols!=6) // 3d data is expected
  {
    //return -1;
    CV_Error(cv::Error::BadImageSize, "PC should have 3 or 6 elements in its columns");
  }

  int sizes[2] = {PC.rows, 3};
  int sizesResult[2] = {PC.rows, NumNeighbors};
  float* dataset = new float[PC.rows*3];
  float* distances = new float[PC.rows*NumNeighbors];
  int* indices = new int[PC.rows*NumNeighbors];

  for (i=0; i<PC.rows; i++)
  {
741
    const float* src = PC.ptr<float>(i);
Bence Magyar's avatar
Bence Magyar committed
742 743 744 745 746 747 748 749 750 751 752 753 754 755
    float* dst = (float*)(&dataset[i*3]);

    dst[0] = src[0];
    dst[1] = src[1];
    dst[2] = src[2];
  }

  Mat PCInput(2, sizes, CV_32F, dataset, 0);

  void* flannIndex = indexPCFlann(PCInput);

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

756
  queryPCFlann(flannIndex, PCInput, Indices, Distances, NumNeighbors);
Bence Magyar's avatar
Bence Magyar committed
757 758 759 760 761 762 763 764 765
  destroyFlann(flannIndex);
  flannIndex = 0;

  PCNormals = Mat(PC.rows, 6, CV_32F);

  for (i=0; i<PC.rows; i++)
  {
    double C[3][3], mu[4];
    const float* pci = &dataset[i*3];
766
    float* pcr = PCNormals.ptr<float>(i);
Bence Magyar's avatar
Bence Magyar committed
767 768 769 770 771 772 773 774
    double nr[3];

    int* indLocal = &indices[i*NumNeighbors];

    // compute covariance matrix
    meanCovLocalPCInd(dataset, indLocal, 3, NumNeighbors, C, mu);

    // eigenvectors of covariance matrix
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
    Mat cov(3, 3, CV_64F), eigVect, eigVal;
    double* covData = (double*)cov.data;
    covData[0] = C[0][0];
    covData[1] = C[0][1];
    covData[2] = C[0][2];
    covData[3] = C[1][0];
    covData[4] = C[1][1];
    covData[5] = C[1][2];
    covData[6] = C[2][0];
    covData[7] = C[2][1];
    covData[8] = C[2][2];
    eigen(cov, eigVal, eigVect);
    Mat lowestEigVec;
    //the eigenvector for the lowest eigenvalue is in the last row
    eigVect.row(eigVect.rows - 1).copyTo(lowestEigVec);
    double* eigData = (double*)lowestEigVec.data;
    nr[0] = eigData[0];
    nr[1] = eigData[1];
    nr[2] = eigData[2];
Bence Magyar's avatar
Bence Magyar committed
794 795 796 797 798 799

    pcr[0] = pci[0];
    pcr[1] = pci[1];
    pcr[2] = pci[2];

    if (FlipViewpoint)
800
    {
Bence Magyar's avatar
Bence Magyar committed
801
      flipNormalViewpoint(pci, viewpoint[0], viewpoint[1], viewpoint[2], &nr[0], &nr[1], &nr[2]);
802
    }
Bence Magyar's avatar
Bence Magyar committed
803 804 805 806 807 808 809 810 811 812 813

    pcr[3] = (float)nr[0];
    pcr[4] = (float)nr[1];
    pcr[5] = (float)nr[2];
  }

  delete[] indices;
  delete[] distances;
  delete[] dataset;

  return 1;
814 815 816 817 818
}

} // namespace ppf_match_3d

} // namespace cv