NormalSpace.cpp
Go to the documentation of this file.
1 // kate: replace-tabs off; indent-width 4; indent-mode normal
2 // vim: ts=4:sw=4:noexpandtab
3 /*
4 
5 Copyright (c) 2010--2018,
6 François Pomerleau and Stephane Magnenat, ASL, ETHZ, Switzerland
7 You can contact the authors at <f dot pomerleau at gmail dot com> and
8 <stephane at magnenat dot net>
9 
10 All rights reserved.
11 
12 Redistribution and use in source and binary forms, with or without
13 modification, are permitted provided that the following conditions are met:
14  * Redistributions of source code must retain the above copyright
15  notice, this list of conditions and the following disclaimer.
16  * Redistributions in binary form must reproduce the above copyright
17  notice, this list of conditions and the following disclaimer in the
18  documentation and/or other materials provided with the distribution.
19  * Neither the name of the <organization> nor the
20  names of its contributors may be used to endorse or promote products
21  derived from this software without specific prior written permission.
22 
23 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
24 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
25 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
26 DISCLAIMED. IN NO EVENT SHALL ETH-ASL BE LIABLE FOR ANY
27 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
28 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
30 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
32 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 
34 */
35 #include "NormalSpace.h"
36 
37 #include <algorithm>
38 #include <vector>
39 #include <unordered_map>
40 #include <random>
41 #include <ciso646>
42 #include <cmath>
43 #include <numeric>
44 
45 // NormalSpaceDataPointsFilter
46 template <typename T>
48  PointMatcher<T>::DataPointsFilter("NormalSpaceDataPointsFilter",
49  NormalSpaceDataPointsFilter::availableParameters(), params),
50  nbSample{Parametrizable::get<std::size_t>("nbSample")},
51  seed{Parametrizable::get<std::size_t>("seed")},
52  epsilon{Parametrizable::get<T>("epsilon")},
53  nbBucket{std::size_t(ceil(2.0 * M_PI / epsilon) * ceil(M_PI / epsilon))}
54 {
55 }
56 
57 template <typename T>
60 {
61  DataPoints output(input);
62  inPlaceFilter(output);
63  return output;
64 }
65 
66 //TODO: Add support for 2D by building histogram of polar coordinate with uniform sampling
67 
68 template <typename T>
70 {
71  //check dimension
72  const std::size_t featDim = cloud.features.rows();
73  if(featDim < 4) //3D case support only
74  {
75  std::cerr << "ERROR: NormalSpaceDataPointsFilter does not support 2D point cloud yet (does nothing)" << std::endl;
76  return;
77  }
78 
79  //Check number of points
80  const int nbPoints = cloud.getNbPoints();
81  if(nbSample >= std::size_t(nbPoints))
82  return;
83 
84  //Check if there is normals info
85  if (!cloud.descriptorExists("normals"))
86  throw InvalidField("OrientNormalsDataPointsFilter: Error, cannot find normals in descriptors.");
87 
88  const auto& normals = cloud.getDescriptorViewByName("normals");
89 
90  std::mt19937 gen(seed); //Standard mersenne_twister_engine seeded with seed
91 
92  //bucketed normal space
93  std::vector<std::vector<int> > idBuckets;
94  idBuckets.resize(nbBucket);
95 
96  std::vector<std::size_t> keepIndexes;
97  keepIndexes.reserve(nbSample);
98 
99  // Generate a random sequence of indices so that elements are placed in buckets in random order
100  std::vector<std::size_t> randIdcs(nbPoints);
101  std::iota(randIdcs.begin(), randIdcs.end(), 0);
102  std::shuffle(randIdcs.begin(), randIdcs.end(), gen);
103 
105  for (auto randIdx : randIdcs)
106  {
107  // Allow for slight approximiation errors
108  assert(normals.col(randIdx).head(3).norm() >= 1.0-0.00001);
109  assert(normals.col(randIdx).head(3).norm() <= 1.0+0.00001);
110  // Catch errors where theta will be NaN
111  assert((normals(2,randIdx) <= 1.0) && (normals(2,randIdx) >= -1.0));
112 
113  //Theta = polar angle in [0 ; pi]
114  const T theta = std::acos(normals(2, randIdx));
115  //Phi = azimuthal angle in [0 ; 2pi]
116  const T phi = std::fmod(std::atan2(normals(1, randIdx), normals(0, randIdx)) + 2. * M_PI, 2. * M_PI);
117 
118  // Catch normal space hashing errors
119  assert(bucketIdx(theta, phi) < nbBucket);
120  idBuckets[bucketIdx(theta, phi)].push_back(randIdx);
121  }
122 
123  // Remove empty buckets
124  idBuckets.erase(std::remove_if(idBuckets.begin(), idBuckets.end(),
125  [](const std::vector<int>& bucket) { return bucket.empty(); }),
126  idBuckets.end());
127 
129  for (std::size_t i=0; i<nbSample; i++)
130  {
131  // Get a random bucket
132  std::uniform_int_distribution<std::size_t> uniBucket(0,idBuckets.size()-1);
133  std::size_t curBucketIdx = uniBucket(gen);
134  std::vector<int>& curBucket = idBuckets[curBucketIdx];
135 
137  int idToKeep = curBucket[curBucket.size()-1];
138  curBucket.pop_back();
139  keepIndexes.push_back(static_cast<std::size_t>(idToKeep));
140 
141  // Remove the bucket if it is empty
142  if (curBucket.empty()) {
143  idBuckets.erase(idBuckets.begin()+curBucketIdx);
144  }
145  }
146 
147  //TODO: evaluate performances between this solution and sorting the indexes
148  // We build map of (old index to new index), in case we sample pts at the begining of the pointcloud
149  std::unordered_map<std::size_t, std::size_t> mapidx;
150  std::size_t idx = 0;
151 
153  for(std::size_t id : keepIndexes)
154  {
155  //retrieve index from lookup table if sampling in already switched element
156  if(id<idx)
157  id = mapidx[id];
158  //Switch columns id and idx
159  cloud.swapCols(idx, id);
160  //Maintain new index position
161  mapidx[idx] = id;
162  //Update index
163  ++idx;
164  }
165  cloud.conservativeResize(nbSample);
166 }
167 
168 template <typename T>
169 std::size_t NormalSpaceDataPointsFilter<T>::bucketIdx(T theta, T phi) const
170 {
171  //Theta = polar angle in [0 ; pi] and Phi = azimuthal angle in [0 ; 2pi]
172  assert( (theta >= 0.0) && (theta <= static_cast<T>(M_PI)) && "Theta not in [0, Pi]");
173  assert( (phi >= 0) && (phi <= 2*static_cast<T>(M_PI)) && "Phi not in [0, 2Pi]");
174 
175  // Wrap Theta at Pi
176  if (theta == static_cast<T>(M_PI)) { theta = 0.0; };
177  // Wrap Phi at 2Pi
178  if (phi == 2*static_cast<T>(M_PI)) { phi = 0.0; };
179  // block number block size element number
180  return static_cast<std::size_t>( floor(theta/epsilon) * ceil(2.0*M_PI/epsilon) + floor(phi/epsilon) );
181 }
182 
183 template struct NormalSpaceDataPointsFilter<float>;
NormalSpaceDataPointsFilter::bucketIdx
std::size_t bucketIdx(T theta, T phi) const
Definition: NormalSpace.cpp:169
PointMatcher::DataPoints::swapCols
void swapCols(Index iCol, Index jCol)
Swap column i and j in the point cloud, swap also features and descriptors if any....
Definition: pointmatcher/DataPoints.cpp:406
NormalSpaceDataPointsFilter::inPlaceFilter
virtual void inPlaceFilter(DataPoints &cloud)
Apply these filters to a point cloud without copying.
Definition: NormalSpace.cpp:69
build_map.T
T
Definition: build_map.py:34
PointMatcher::DataPoints::descriptorExists
bool descriptorExists(const std::string &name) const
Look if a descriptor with a given name exist.
Definition: pointmatcher/DataPoints.cpp:583
PointMatcher
Functions and classes that are dependant on scalar type are defined in this templatized class.
Definition: PointMatcher.h:130
PointMatcher::DataPoints
A point cloud.
Definition: PointMatcher.h:207
PointMatcher::DataPoints::InvalidField
An exception thrown when one tries to access features or descriptors unexisting or of wrong dimension...
Definition: PointMatcher.h:250
NormalSpaceDataPointsFilter::NormalSpaceDataPointsFilter
NormalSpaceDataPointsFilter(const Parameters &params=Parameters())
Definition: NormalSpace.cpp:47
align_sequence.params
params
Definition: align_sequence.py:13
PointMatcher::DataPointsFilter
A data filter takes a point cloud as input, transforms it, and produces another point cloud as output...
Definition: PointMatcher.h:440
PointMatcher::DataPoints::getNbPoints
unsigned getNbPoints() const
Return the number of points contained in the point cloud.
Definition: pointmatcher/DataPoints.cpp:158
PointMatcher::DataPoints::features
Matrix features
features of points in the cloud
Definition: PointMatcher.h:331
NormalSpace.h
PointMatcher::DataPoints::conservativeResize
void conservativeResize(Index pointCount)
Resize the cloud to pointCount points, conserving existing ones.
Definition: pointmatcher/DataPoints.cpp:328
NormalSpaceDataPointsFilter::Parameters
Parametrizable::Parameters Parameters
Definition: NormalSpace.h:49
PointMatcher::DataPoints::getDescriptorViewByName
ConstView getDescriptorViewByName(const std::string &name) const
Get a const view on a descriptor by name, throw an exception if it does not exist.
Definition: pointmatcher/DataPoints.cpp:555
NormalSpaceDataPointsFilter::filter
virtual DataPoints filter(const DataPoints &input)
Apply filters to input point cloud. This is the non-destructive version and returns a copy.
Definition: NormalSpace.cpp:59
NormalSpaceDataPointsFilter
Definition: NormalSpace.h:40


libpointmatcher
Author(s):
autogenerated on Mon Sep 16 2024 02:24:09