ppf_match_3d.cpp 19.9 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
//
//  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"
#include "hash_murmur.hpp"

namespace cv 
{
namespace ppf_match_3d
{
48 49 50

static const size_t PPF_LENGTH = 5;

51
// routines for assisting sort
52
static bool pose3DPtrCompare(const Pose3DPtr& a, const Pose3DPtr& b)
53
{
54 55
  CV_Assert(!a.empty() && !b.empty());
  return ( a->numVotes > b->numVotes );
56 57
}

58
static int sortPoseClusters(const PoseCluster3DPtr& a, const PoseCluster3DPtr& b)
59
{
60
  CV_Assert(!a.empty() && !b.empty());
Bence Magyar's avatar
Bence Magyar committed
61
  return ( a->numVotes > b->numVotes );
62 63 64 65 66
}

// simple hashing
/*static int hashPPFSimple(const double f[4], const double AngleStep, const double DistanceStep)
{
Bence Magyar's avatar
Bence Magyar committed
67 68 69 70 71 72 73
  const unsigned char d1 = (unsigned char) (floor ((double)f[0] / (double)AngleStep));
  const unsigned char d2 = (unsigned char) (floor ((double)f[1] / (double)AngleStep));
  const unsigned char d3 = (unsigned char) (floor ((double)f[2] / (double)AngleStep));
  const unsigned char d4 = (unsigned char) (floor ((double)f[3] / (double)DistanceStep));

  int hashKey = (d1 | (d2<<8) | (d3<<16) | (d4<<24));
  return hashKey;
74 75 76 77 78
}*/

// quantize ppf and hash it for proper indexing
static KeyType hashPPF(const double f[4], const double AngleStep, const double DistanceStep)
{
Bence Magyar's avatar
Bence Magyar committed
79 80 81 82 83 84 85 86 87 88
  const int d1 = (int) (floor ((double)f[0] / (double)AngleStep));
  const int d2 = (int) (floor ((double)f[1] / (double)AngleStep));
  const int d3 = (int) (floor ((double)f[2] / (double)AngleStep));
  const int d4 = (int) (floor ((double)f[3] / (double)DistanceStep));
  int key[4]={d1,d2,d3,d4};
  KeyType hashKey=0;

  murmurHash(key, 4*sizeof(int), 42, &hashKey);

  return hashKey;
89 90 91 92
}

/*static size_t hashMurmur(unsigned int key)
{
Bence Magyar's avatar
Bence Magyar committed
93 94 95
  size_t hashKey=0;
  hashMurmurx86((void*)&key, 4, 42, &hashKey);
  return hashKey;
96 97 98 99
}*/

static double computeAlpha(const double p1[4], const double n1[4], const double p2[4])
{
Bence Magyar's avatar
Bence Magyar committed
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
  double Tmg[3], mpt[3], row2[3], row3[3], alpha;

  computeTransformRTyz(p1, n1, row2, row3, Tmg);

  // checked row2, row3: They are correct

  mpt[1] = Tmg[1] + row2[0] * p2[0] + row2[1] * p2[1] + row2[2] * p2[2];
  mpt[2] = Tmg[2] + row3[0] * p2[0] + row3[1] * p2[1] + row3[2] * p2[2];

  alpha=atan2(-mpt[2], mpt[1]);

  if ( alpha != alpha)
  {
    return 0;
  }

  if (sin(alpha)*mpt[2]<0.0)
    alpha=-alpha;

  return (-alpha);
120 121 122 123
}

PPF3DDetector::PPF3DDetector()
{
124 125 126 127 128 129
  sampling_step_relative = 0.05;
  distance_step_relative = 0.05;
  scene_sample_step = (int)(1/0.04);
  angle_step_relative = 30;
  angle_step_radians = (360.0/angle_step_relative)*M_PI/180.0;
  angle_step = angle_step_radians;
Bence Magyar's avatar
Bence Magyar committed
130 131 132
  trained = false;

  setSearchParams();
133 134 135 136
}

PPF3DDetector::PPF3DDetector(const double RelativeSamplingStep, const double RelativeDistanceStep, const double NumAngles)
{
137 138 139 140
  sampling_step_relative = RelativeSamplingStep;
  distance_step_relative = RelativeDistanceStep;
  angle_step_relative = NumAngles;
  angle_step_radians = (360.0/angle_step_relative)*M_PI/180.0;
Bence Magyar's avatar
Bence Magyar committed
141
  //SceneSampleStep = 1.0/RelativeSceneSampleStep;
142
  angle_step = angle_step_radians;
Bence Magyar's avatar
Bence Magyar committed
143 144 145
  trained = false;

  setSearchParams();
146 147
}

148
void PPF3DDetector::setSearchParams(const double positionThreshold, const double rotationThreshold, const bool useWeightedClustering)
149
{
Bence Magyar's avatar
Bence Magyar committed
150
  if (positionThreshold<0)
151
    position_threshold = sampling_step_relative;
Bence Magyar's avatar
Bence Magyar committed
152
  else
153
    position_threshold = positionThreshold;
Bence Magyar's avatar
Bence Magyar committed
154 155

  if (rotationThreshold<0)
156
    rotation_threshold = ((360/angle_step) / 180.0 * M_PI);
Bence Magyar's avatar
Bence Magyar committed
157
  else
158
    rotation_threshold = rotationThreshold;
Bence Magyar's avatar
Bence Magyar committed
159

160
  use_weighted_avg = useWeightedClustering;
161 162 163
}

// compute per point PPF as in paper
Bence Magyar's avatar
Bence Magyar committed
164 165 166
void PPF3DDetector::computePPFFeatures(const double p1[4], const double n1[4],
                                       const double p2[4], const double n2[4],
                                       double f[4])
167
{
Bence Magyar's avatar
Bence Magyar committed
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
  /*
  Vectors will be defined as of length 4 instead of 3, because of:
  - Further SIMD vectorization
  - Cache alignment
  */

  double d[4] = {p2[0] - p1[0], p2[1] - p1[1], p2[2] - p1[2], 0};

  double norm = TNorm3(d);
  f[3] = norm;

  if (norm)
  {
    d[0] /= f[3];
    d[1] /= f[3];
    d[2] /= f[3];
  }
  else
  {
    // TODO: Handle this
    f[0] = 0;
    f[1] = 0;
    f[2] = 0;
    return ;
  }

  /*
  Tolga Birdal's note:
  Issues of numerical stability is of concern here.
  Bertram's suggestion: atan2(a dot b, |axb|)
  My correction :
  I guess it should be: angle = atan2(norm(cross(a,b)), dot(a,b))
  The macro is implemented accordingly.
  TAngle3 actually outputs in range [0, pi] as
  Bertram suggests
  */

  f[0] = TAngle3(n1, d);
  f[1] = TAngle3(n2, d);
  f[2] = TAngle3(n1, n2);
208 209 210 211
}

void PPF3DDetector::clearTrainingModels()
{
Bence Magyar's avatar
Bence Magyar committed
212 213 214 215 216 217 218 219 220 221 222
  if (this->hash_nodes)
  {
    free(this->hash_nodes);
    this->hash_nodes=0;
  }

  if (this->hash_table)
  {
    hashtableDestroy(this->hash_table);
    this->hash_table=0;
  }
223 224 225 226
}

PPF3DDetector::~PPF3DDetector()
{
Bence Magyar's avatar
Bence Magyar committed
227
  clearTrainingModels();
228 229 230 231 232
}

// TODO: Check all step sizes to be positive
void PPF3DDetector::trainModel(const Mat &PC)
{
Bence Magyar's avatar
Bence Magyar committed
233 234 235 236 237 238 239 240 241 242 243 244
  CV_Assert(PC.type() == CV_32F || PC.type() == CV_32FC1);

  // compute bbox
  float xRange[2], yRange[2], zRange[2];
  computeBboxStd(PC, xRange, yRange, zRange);

  // compute sampling step from diameter of bbox
  float dx = xRange[1] - xRange[0];
  float dy = yRange[1] - yRange[0];
  float dz = zRange[1] - zRange[0];
  float diameter = sqrt ( dx * dx + dy * dy + dz * dz );

245
  float distanceStep = (float)(diameter * sampling_step_relative);
Bence Magyar's avatar
Bence Magyar committed
246

247
  Mat sampled = samplePCByQuantization(PC, xRange, yRange, zRange, (float)sampling_step_relative,0);
Bence Magyar's avatar
Bence Magyar committed
248 249 250 251 252 253

  int size = sampled.rows*sampled.rows;

  hashtable_int* hashTable = hashtableCreate(size, NULL);

  int numPPF = sampled.rows*sampled.rows;
254 255
  ppf = Mat(numPPF, PPF_LENGTH, CV_32FC1);
  int ppfStep = (int)ppf.step;
Bence Magyar's avatar
Bence Magyar committed
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
  int sampledStep = (int)sampled.step;

  // TODO: Maybe I could sample 1/5th of them here. Check the performance later.
  int numRefPoints = sampled.rows;

  // pre-allocate the hash nodes
  hash_nodes = (THash*)calloc(numRefPoints*numRefPoints, sizeof(THash));

  // TODO : This can easily be parallelized. But we have to lock hashtable_insert.
  // I realized that performance drops when this loop is parallelized (unordered
  // inserts into the hashtable
  // But it is still there to be investigated. For now, I leave this unparallelized
  // since this is just a training part.
  for (int i=0; i<numRefPoints; i++)
  {
    float* f1 = (float*)(&sampled.data[i * sampledStep]);
    const double p1[4] = {f1[0], f1[1], f1[2], 0};
    const double n1[4] = {f1[3], f1[4], f1[5], 0};

    //printf("///////////////////// NEW REFERENCE ////////////////////////\n");
    for (int j=0; j<numRefPoints; j++)
277
    {
Bence Magyar's avatar
Bence Magyar committed
278 279 280 281 282 283 284 285 286
      // cannnot compute the ppf with myself
      if (i!=j)
      {
        float* f2 = (float*)(&sampled.data[j * sampledStep]);
        const double p2[4] = {f2[0], f2[1], f2[2], 0};
        const double n2[4] = {f2[3], f2[4], f2[5], 0};

        double f[4]={0};
        computePPFFeatures(p1, n1, p2, n2, f);
287
        KeyType hashValue = hashPPF(f, angle_step_radians, distanceStep);
Bence Magyar's avatar
Bence Magyar committed
288 289 290 291 292 293 294 295 296 297 298
        double alpha = computeAlpha(p1, n1, p2);
        unsigned int corrInd = i*numRefPoints+j;
        unsigned int ppfInd = corrInd*ppfStep;

        THash* hashNode = &hash_nodes[i*numRefPoints+j];
        hashNode->id = hashValue;
        hashNode->i = i;
        hashNode->ppfInd = ppfInd;

        hashtableInsertHashed(hashTable, hashValue, (void*)hashNode);

299
        float* ppfRow = (float*)(&(ppf.data[ ppfInd ]));
Bence Magyar's avatar
Bence Magyar committed
300 301 302 303 304 305
        ppfRow[0] = (float)f[0];
        ppfRow[1] = (float)f[1];
        ppfRow[2] = (float)f[2];
        ppfRow[3] = (float)f[3];
        ppfRow[4] = (float)alpha;
      }
306
    }
Bence Magyar's avatar
Bence Magyar committed
307 308
  }

309
  angle_step = angle_step_radians;
Bence Magyar's avatar
Bence Magyar committed
310 311 312 313
  distance_step = distanceStep;
  hash_table = hashTable;
  ppf_step = ppfStep;
  num_ref_points = numRefPoints;
314
  sampled_pc = sampled;
Bence Magyar's avatar
Bence Magyar committed
315
  trained = true;
316 317 318 319 320 321 322 323 324
}



///////////////////////// MATCHING ////////////////////////////////////////


bool PPF3DDetector::matchPose(const Pose3D& sourcePose, const Pose3D& targetPose)
{
Bence Magyar's avatar
Bence Magyar committed
325 326 327 328 329 330
  // translational difference
  double dv[3] = {targetPose.t[0]-sourcePose.t[0], targetPose.t[1]-sourcePose.t[1], targetPose.t[2]-sourcePose.t[2]};
  double dNorm = sqrt(dv[0]*dv[0]+dv[1]*dv[1]+dv[2]*dv[2]);

  const double phi = fabs ( sourcePose.angle - targetPose.angle );

331
  return (phi<this->rotation_threshold && dNorm < this->position_threshold);
332 333
}

334
void PPF3DDetector::clusterPoses(std::vector<Pose3DPtr> poseList, int numPoses, std::vector<Pose3DPtr> &finalPoses)
335
{
336
  std::vector<PoseCluster3DPtr> poseClusters;
Bence Magyar's avatar
Bence Magyar committed
337 338 339 340

  finalPoses.clear();

  // sort the poses for stability
341
  std::sort(poseList.begin(), poseList.end(), pose3DPtrCompare);
Bence Magyar's avatar
Bence Magyar committed
342 343 344

  for (int i=0; i<numPoses; i++)
  {
345
    Pose3DPtr pose = poseList[i];
Bence Magyar's avatar
Bence Magyar committed
346 347 348 349
    bool assigned = false;

    // search all clusters
    for (size_t j=0; j<poseClusters.size() && !assigned; j++)
350
    {
351
      const Pose3DPtr poseCenter = poseClusters[j]->poseList[0];
Bence Magyar's avatar
Bence Magyar committed
352 353 354 355 356
      if (matchPose(*pose, *poseCenter))
      {
        poseClusters[j]->addPose(pose);
        assigned = true;
      }
357
    }
Bence Magyar's avatar
Bence Magyar committed
358 359

    if (!assigned)
360
    {
361
      poseClusters.push_back(PoseCluster3DPtr(new PoseCluster3D(pose)));
Bence Magyar's avatar
Bence Magyar committed
362 363 364 365
    }
  }

  // sort the clusters so that we could output multiple hypothesis
366
  std::sort(poseClusters.begin(), poseClusters.end(), sortPoseClusters);
Bence Magyar's avatar
Bence Magyar committed
367 368 369 370 371

  finalPoses.resize(poseClusters.size());

  // TODO: Use MinMatchScore

372
  if (use_weighted_avg)
Bence Magyar's avatar
Bence Magyar committed
373
  {
374 375 376
#if defined _OPENMP
#pragma omp parallel for
#endif
Bence Magyar's avatar
Bence Magyar committed
377
    // uses weighting by the number of votes
378
    for (int i=0; i<static_cast<int>(poseClusters.size()); i++)
379
    {
Bence Magyar's avatar
Bence Magyar committed
380 381 382 383
      // We could only average the quaternions. So I will make use of them here
      double qAvg[4]={0}, tAvg[3]={0};

      // Perform the final averaging
384 385
      PoseCluster3DPtr curCluster = poseClusters[i];
      std::vector<Pose3DPtr> curPoses = curCluster->poseList;
Bence Magyar's avatar
Bence Magyar committed
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
      int curSize = (int)curPoses.size();
      int numTotalVotes = 0;

      for (int j=0; j<curSize; j++)
        numTotalVotes += curPoses[j]->numVotes;

      double wSum=0;

      for (int j=0; j<curSize; j++)
      {
        const double w = (double)curPoses[j]->numVotes / (double)numTotalVotes;

        qAvg[0]+= w*curPoses[j]->q[0];
        qAvg[1]+= w*curPoses[j]->q[1];
        qAvg[2]+= w*curPoses[j]->q[2];
        qAvg[3]+= w*curPoses[j]->q[3];

        tAvg[0]+= w*curPoses[j]->t[0];
        tAvg[1]+= w*curPoses[j]->t[1];
        tAvg[2]+= w*curPoses[j]->t[2];
        wSum+=w;
      }

      tAvg[0]/=wSum;
      tAvg[1]/=wSum;
      tAvg[2]/=wSum;

      qAvg[0]/=wSum;
      qAvg[1]/=wSum;
      qAvg[2]/=wSum;
      qAvg[3]/=wSum;

      curPoses[0]->updatePoseQuat(qAvg, tAvg);
      curPoses[0]->numVotes=curCluster->numVotes;

      finalPoses[i]=curPoses[0]->clone();
    }
  }
  else
  {
426 427 428
#if defined _OPENMP
#pragma omp parallel for
#endif
429
    for (int i=0; i<static_cast<int>(poseClusters.size()); i++)
Bence Magyar's avatar
Bence Magyar committed
430 431 432 433 434
    {
      // We could only average the quaternions. So I will make use of them here
      double qAvg[4]={0}, tAvg[3]={0};

      // Perform the final averaging
435 436 437
      PoseCluster3DPtr curCluster = poseClusters[i];
      std::vector<Pose3DPtr> curPoses = curCluster->poseList;
      const int curSize = (int)curPoses.size();
Bence Magyar's avatar
Bence Magyar committed
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463

      for (int j=0; j<curSize; j++)
      {
        qAvg[0]+= curPoses[j]->q[0];
        qAvg[1]+= curPoses[j]->q[1];
        qAvg[2]+= curPoses[j]->q[2];
        qAvg[3]+= curPoses[j]->q[3];

        tAvg[0]+= curPoses[j]->t[0];
        tAvg[1]+= curPoses[j]->t[1];
        tAvg[2]+= curPoses[j]->t[2];
      }

      tAvg[0]/=(double)curSize;
      tAvg[1]/=(double)curSize;
      tAvg[2]/=(double)curSize;

      qAvg[0]/=(double)curSize;
      qAvg[1]/=(double)curSize;
      qAvg[2]/=(double)curSize;
      qAvg[3]/=(double)curSize;

      curPoses[0]->updatePoseQuat(qAvg, tAvg);
      curPoses[0]->numVotes=curCluster->numVotes;

      finalPoses[i]=curPoses[0]->clone();
464
    }
Bence Magyar's avatar
Bence Magyar committed
465 466 467
  }

  poseClusters.clear();
468 469
}

470
void PPF3DDetector::match(const Mat& pc, std::vector<Pose3DPtr>& results, const double relativeSceneSampleStep, const double relativeSceneDistance)
471
{
Bence Magyar's avatar
Bence Magyar committed
472 473 474 475 476 477 478 479
  if (!trained)
  {
    throw cv::Exception(cv::Error::StsError, "The model is not trained. Cannot match without training", __FUNCTION__, __FILE__, __LINE__);
  }

  CV_Assert(pc.type() == CV_32F || pc.type() == CV_32FC1);
  CV_Assert(relativeSceneSampleStep<=1 && relativeSceneSampleStep>0);

480
  scene_sample_step = (int)(1.0/relativeSceneSampleStep);
Bence Magyar's avatar
Bence Magyar committed
481 482 483 484 485

  //int numNeighbors = 10;
  int numAngles = (int) (floor (2 * M_PI / angle_step));
  float distanceStep = (float)distance_step;
  unsigned int n = num_ref_points;
486
  std::vector<Pose3DPtr> poseList;
487
  int sceneSamplingStep = scene_sample_step;
Bence Magyar's avatar
Bence Magyar committed
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505

  // compute bbox
  float xRange[2], yRange[2], zRange[2];
  computeBboxStd(pc, xRange, yRange, zRange);

  // sample the point cloud
  /*float dx = xRange[1] - xRange[0];
  float dy = yRange[1] - yRange[0];
  float dz = zRange[1] - zRange[0];
  float diameter = sqrt ( dx * dx + dy * dy + dz * dz );
  float distanceSampleStep = diameter * RelativeSceneDistance;*/
  Mat sampled = samplePCByQuantization(pc, xRange, yRange, zRange, (float)relativeSceneDistance, 0);

  // allocate the accumulator : Moved this to the inside of the loop
  /*#if !defined (_OPENMP)
     unsigned int* accumulator = (unsigned int*)calloc(numAngles*n, sizeof(unsigned int));
  #endif*/

506
  poseList.reserve((sampled.rows/sceneSamplingStep)+4);
Bence Magyar's avatar
Bence Magyar committed
507

508 509 510
#if defined _OPENMP
#pragma omp parallel for
#endif
Bence Magyar's avatar
Bence Magyar committed
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
  for (int i = 0; i < sampled.rows; i += sceneSamplingStep)
  {
    unsigned int refIndMax = 0, alphaIndMax = 0;
    unsigned int maxVotes = 0;

    float* f1 = (float*)(&sampled.data[i * sampled.step]);
    const double p1[4] = {f1[0], f1[1], f1[2], 0};
    const double n1[4] = {f1[3], f1[4], f1[5], 0};
    double *row2, *row3, tsg[3]={0}, Rsg[9]={0}, RInv[9]={0};

    unsigned int* accumulator = (unsigned int*)calloc(numAngles*n, sizeof(unsigned int));
    computeTransformRT(p1, n1, Rsg, tsg);
    row2=&Rsg[3];
    row3=&Rsg[6];

    // Tolga Birdal's notice:
    // As a later update, we might want to look into a local neighborhood only
    // To do this, simply search the local neighborhood by radius look up
    // and collect the neighbors to compute the relative pose

    for (int j = 0; j < sampled.rows; j ++)
532
    {
Bence Magyar's avatar
Bence Magyar committed
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
      if (i!=j)
      {
        float* f2 = (float*)(&sampled.data[j * sampled.step]);
        const double p2[4] = {f2[0], f2[1], f2[2], 0};
        const double n2[4] = {f2[3], f2[4], f2[5], 0};
        double p2t[4], alpha_scene;

        double f[4]={0};
        computePPFFeatures(p1, n1, p2, n2, f);
        KeyType hashValue = hashPPF(f, angle_step, distanceStep);

        // we don't need to call this here, as we already estimate the tsg from scene reference point
        // double alpha = computeAlpha(p1, n1, p2);
        p2t[1] = tsg[1] + row2[0] * p2[0] + row2[1] * p2[1] + row2[2] * p2[2];
        p2t[2] = tsg[2] + row3[0] * p2[0] + row3[1] * p2[1] + row3[2] * p2[2];

        alpha_scene=atan2(-p2t[2], p2t[1]);

        if ( alpha_scene != alpha_scene)
552
        {
Bence Magyar's avatar
Bence Magyar committed
553
          continue;
554
        }
Bence Magyar's avatar
Bence Magyar committed
555 556 557 558 559 560 561 562 563

        if (sin(alpha_scene)*p2t[2]<0.0)
          alpha_scene=-alpha_scene;

        alpha_scene=-alpha_scene;

        hashnode_i* node = hashtableGetBucketHashed(hash_table, (hashValue));

        while (node)
564
        {
Bence Magyar's avatar
Bence Magyar committed
565 566 567
          THash* tData = (THash*) node->data;
          int corrI = (int)tData->i;
          int ppfInd = (int)tData->ppfInd;
568 569
          float* ppfCorrScene = (float*)(&ppf.data[ppfInd]);
          double alpha_model = (double)ppfCorrScene[PPF_LENGTH-1];
Bence Magyar's avatar
Bence Magyar committed
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
          double alpha = alpha_model - alpha_scene;

          /*  Tolga Birdal's note: Map alpha to the indices:
                  atan2 generates results in (-pi pi]
                  That's why alpha should be in range [-2pi 2pi]
                  So the quantization would be :
                  numAngles * (alpha+2pi)/(4pi)
                  */

          //printf("%f\n", alpha);
          int alpha_index = (int)(numAngles*(alpha + 2*M_PI) / (4*M_PI));

          unsigned int accIndex = corrI * numAngles + alpha_index;

          accumulator[accIndex]++;
          node = node->next;
586
        }
Bence Magyar's avatar
Bence Magyar committed
587
      }
588
    }
Bence Magyar's avatar
Bence Magyar committed
589 590 591

    // Maximize the accumulator
    for (unsigned int k = 0; k < n; k++)
592
    {
Bence Magyar's avatar
Bence Magyar committed
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
      for (int j = 0; j < numAngles; j++)
      {
        const unsigned int accInd = k*numAngles + j;
        const unsigned int accVal = accumulator[ accInd ];
        if (accVal > maxVotes)
        {
          maxVotes = accVal;
          refIndMax = k;
          alphaIndMax = j;
        }

#if !defined (_OPENMP)
        accumulator[accInd ] = 0;
#endif
      }
608
    }
Bence Magyar's avatar
Bence Magyar committed
609 610 611 612 613 614 615 616 617 618 619 620 621 622

    // invert Tsg : Luckily rotation is orthogonal: Inverse = Transpose.
    // We are not required to invert.
    double tInv[3], tmg[3], Rmg[9];
    matrixTranspose33(Rsg, RInv);
    matrixProduct331(RInv, tsg, tInv);

    double TsgInv[16] = { RInv[0], RInv[1], RInv[2], -tInv[0],
                          RInv[3], RInv[4], RInv[5], -tInv[1],
                          RInv[6], RInv[7], RInv[8], -tInv[2],
                          0, 0, 0, 1
                        };

    // TODO : Compute pose
623
    const float* fMax = (float*)(&sampled_pc.data[refIndMax * sampled_pc.step]);
Bence Magyar's avatar
Bence Magyar committed
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
    const double pMax[4] = {fMax[0], fMax[1], fMax[2], 1};
    const double nMax[4] = {fMax[3], fMax[4], fMax[5], 1};

    computeTransformRT(pMax, nMax, Rmg, tmg);
    row2=&Rsg[3];
    row3=&Rsg[6];

    double Tmg[16] = { Rmg[0], Rmg[1], Rmg[2], tmg[0],
                       Rmg[3], Rmg[4], Rmg[5], tmg[1],
                       Rmg[6], Rmg[7], Rmg[8], tmg[2],
                       0, 0, 0, 1
                     };

    // convert alpha_index to alpha
    int alpha_index = alphaIndMax;
    double alpha = (alpha_index*(4*M_PI))/numAngles-2*M_PI;

    // Equation 2:
    double Talpha[16]={0};
    getUnitXRotation_44(alpha, Talpha);

    double Temp[16]={0};
646
    double rawPose[16]={0};
Bence Magyar's avatar
Bence Magyar committed
647
    matrixProduct44(Talpha, Tmg, Temp);
648
    matrixProduct44(TsgInv, Temp, rawPose);
Bence Magyar's avatar
Bence Magyar committed
649

650 651 652
    Pose3DPtr pose(new Pose3D(alpha, refIndMax, maxVotes));
    pose->updatePose(rawPose);
    poseList.push_back(pose);
Bence Magyar's avatar
Bence Magyar committed
653 654 655 656 657 658 659 660 661 662 663 664

#if defined (_OPENMP)
    free(accumulator);
#endif
  }

  // TODO : Make the parameters relative if not arguments.
  //double MinMatchScore = 0.5;

  int numPosesAdded = sampled.rows/sceneSamplingStep;

  clusterPoses(poseList, numPosesAdded, results);
665 666 667 668 669
}

} // namespace ppf_match_3d

} // namespace cv