Point Cloud Library (PCL)  1.10.1
3dsc.hpp
1 /*
2  * Software License Agreement (BSD License)
3  *
4  * Point Cloud Library (PCL) - www.pointclouds.org
5  * Copyright (c) 2010-2011, Willow Garage, Inc.
6  * Copyright (c) 2012-, Open Perception, Inc.
7  *
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  *
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
17  * copyright notice, this list of conditions and the following
18  * disclaimer in the documentation and/or other materials provided
19  * with the distribution.
20  * * Neither the name of the copyright holder(s) nor the names of its
21  * contributors may be used to endorse or promote products derived
22  * from this software without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35  * POSSIBILITY OF SUCH DAMAGE.
36  *
37  */
38 
39 #ifndef PCL_FEATURES_IMPL_3DSC_HPP_
40 #define PCL_FEATURES_IMPL_3DSC_HPP_
41 
42 #include <cmath>
43 #include <pcl/features/3dsc.h>
44 #include <pcl/common/utils.h>
45 #include <pcl/common/geometry.h>
46 #include <pcl/common/angles.h>
47 
48 //////////////////////////////////////////////////////////////////////////////////////////////
49 template <typename PointInT, typename PointNT, typename PointOutT> bool
51 {
53  {
54  PCL_ERROR ("[pcl::%s::initCompute] Init failed.\n", getClassName ().c_str ());
55  return (false);
56  }
57 
58  if (search_radius_< min_radius_)
59  {
60  PCL_ERROR ("[pcl::%s::initCompute] search_radius_ must be GREATER than min_radius_.\n", getClassName ().c_str ());
61  return (false);
62  }
63 
64  // Update descriptor length
65  descriptor_length_ = elevation_bins_ * azimuth_bins_ * radius_bins_;
66 
67  // Compute radial, elevation and azimuth divisions
68  float azimuth_interval = 360.0f / static_cast<float> (azimuth_bins_);
69  float elevation_interval = 180.0f / static_cast<float> (elevation_bins_);
70 
71  // Reallocate divisions and volume lut
72  radii_interval_.clear ();
73  phi_divisions_.clear ();
74  theta_divisions_.clear ();
75  volume_lut_.clear ();
76 
77  // Fills radii interval based on formula (1) in section 2.1 of Frome's paper
78  radii_interval_.resize (radius_bins_ + 1);
79  for (std::size_t j = 0; j < radius_bins_ + 1; j++)
80  radii_interval_[j] = static_cast<float> (std::exp (std::log (min_radius_) + ((static_cast<float> (j) / static_cast<float> (radius_bins_)) * std::log (search_radius_ / min_radius_))));
81 
82  // Fill theta divisions of elevation
83  theta_divisions_.resize (elevation_bins_ + 1, elevation_interval);
84  theta_divisions_[0] = 0.f;
85  std::partial_sum(theta_divisions_.begin (), theta_divisions_.end (), theta_divisions_.begin ());
86 
87  // Fill phi didvisions of elevation
88  phi_divisions_.resize (azimuth_bins_ + 1, azimuth_interval);
89  phi_divisions_[0] = 0.f;
90  std::partial_sum(phi_divisions_.begin (), phi_divisions_.end (), phi_divisions_.begin ());
91 
92  // LookUp Table that contains the volume of all the bins
93  // "phi" term of the volume integral
94  // "integr_phi" has always the same value so we compute it only one time
95  float integr_phi = pcl::deg2rad (phi_divisions_[1]) - pcl::deg2rad (phi_divisions_[0]);
96  // exponential to compute the cube root using pow
97  float e = 1.0f / 3.0f;
98  // Resize volume look up table
99  volume_lut_.resize (radius_bins_ * elevation_bins_ * azimuth_bins_);
100  // Fill volumes look up table
101  for (std::size_t j = 0; j < radius_bins_; j++)
102  {
103  // "r" term of the volume integral
104  float integr_r = (radii_interval_[j+1] * radii_interval_[j+1] * radii_interval_[j+1] / 3.0f) - (radii_interval_[j] * radii_interval_[j] * radii_interval_[j] / 3.0f);
105 
106  for (std::size_t k = 0; k < elevation_bins_; k++)
107  {
108  // "theta" term of the volume integral
109  float integr_theta = std::cos (pcl::deg2rad (theta_divisions_[k])) - std::cos (pcl::deg2rad (theta_divisions_[k+1]));
110  // Volume
111  float V = integr_phi * integr_theta * integr_r;
112  // Compute cube root of the computed volume commented for performance but left
113  // here for clarity
114  // float cbrt = pow(V, e);
115  // cbrt = 1 / cbrt;
116 
117  for (std::size_t l = 0; l < azimuth_bins_; l++)
118  {
119  // Store in lut 1/cbrt
120  //volume_lut_[ (l*elevation_bins_*radius_bins_) + k*radius_bins_ + j ] = cbrt;
121  volume_lut_[(l*elevation_bins_*radius_bins_) + k*radius_bins_ + j] = 1.0f / powf (V, e);
122  }
123  }
124  }
125  return (true);
126 }
127 
128 //////////////////////////////////////////////////////////////////////////////////////////////
129 template <typename PointInT, typename PointNT, typename PointOutT> bool
131  std::size_t index, const pcl::PointCloud<PointNT> &normals, float rf[9], std::vector<float> &desc)
132 {
133  // The RF is formed as this x_axis | y_axis | normal
134  Eigen::Map<Eigen::Vector3f> x_axis (rf);
135  Eigen::Map<Eigen::Vector3f> y_axis (rf + 3);
136  Eigen::Map<Eigen::Vector3f> normal (rf + 6);
137 
138  // Find every point within specified search_radius_
139  std::vector<int> nn_indices;
140  std::vector<float> nn_dists;
141  const std::size_t neighb_cnt = searchForNeighbors ((*indices_)[index], search_radius_, nn_indices, nn_dists);
142  if (neighb_cnt == 0)
143  {
144  std::fill (desc.begin (), desc.end (), std::numeric_limits<float>::quiet_NaN ());
145  std::fill (rf, rf + 9, 0.f);
146  return (false);
147  }
148 
149  const auto minDistanceIt = std::min_element(nn_dists.begin (), nn_dists.end ());
150  const auto minIndex = nn_indices[std::distance (nn_dists.begin (), minDistanceIt)];
151 
152  // Get origin point
153  Vector3fMapConst origin = input_->points[(*indices_)[index]].getVector3fMap ();
154  // Get origin normal
155  // Use pre-computed normals
156  normal = normals[minIndex].getNormalVector3fMap ();
157 
158  // Compute and store the RF direction
159  x_axis[0] = rnd ();
160  x_axis[1] = rnd ();
161  x_axis[2] = rnd ();
162  if (!pcl::utils::equal (normal[2], 0.0f))
163  x_axis[2] = - (normal[0]*x_axis[0] + normal[1]*x_axis[1]) / normal[2];
164  else if (!pcl::utils::equal (normal[1], 0.0f))
165  x_axis[1] = - (normal[0]*x_axis[0] + normal[2]*x_axis[2]) / normal[1];
166  else if (!pcl::utils::equal (normal[0], 0.0f))
167  x_axis[0] = - (normal[1]*x_axis[1] + normal[2]*x_axis[2]) / normal[0];
168 
169  x_axis.normalize ();
170 
171  // Check if the computed x axis is orthogonal to the normal
172  assert (pcl::utils::equal (x_axis[0]*normal[0] + x_axis[1]*normal[1] + x_axis[2]*normal[2], 0.0f, 1E-6f));
173 
174  // Store the 3rd frame vector
175  y_axis.matrix () = normal.cross (x_axis);
176 
177  // For each point within radius
178  for (std::size_t ne = 0; ne < neighb_cnt; ne++)
179  {
180  if (pcl::utils::equal (nn_dists[ne], 0.0f))
181  continue;
182  // Get neighbours coordinates
183  Eigen::Vector3f neighbour = surface_->points[nn_indices[ne]].getVector3fMap ();
184 
185  /// ----- Compute current neighbour polar coordinates -----
186  /// Get distance between the neighbour and the origin
187  float r = std::sqrt (nn_dists[ne]);
188 
189  /// Project point into the tangent plane
190  Eigen::Vector3f proj;
191  pcl::geometry::project (neighbour, origin, normal, proj);
192  proj -= origin;
193 
194  /// Normalize to compute the dot product
195  proj.normalize ();
196 
197  /// Compute the angle between the projection and the x axis in the interval [0,360]
198  Eigen::Vector3f cross = x_axis.cross (proj);
199  float phi = pcl::rad2deg (std::atan2 (cross.norm (), x_axis.dot (proj)));
200  phi = cross.dot (normal) < 0.f ? (360.0f - phi) : phi;
201  /// Compute the angle between the neighbour and the z axis (normal) in the interval [0, 180]
202  Eigen::Vector3f no = neighbour - origin;
203  no.normalize ();
204  float theta = normal.dot (no);
205  theta = pcl::rad2deg (std::acos (std::min (1.0f, std::max (-1.0f, theta))));
206 
207  // Compute the Bin(j, k, l) coordinates of current neighbour
208  const auto rad_min = std::lower_bound(std::next (radii_interval_.cbegin ()), radii_interval_.cend (), r);
209  const auto theta_min = std::lower_bound(std::next (theta_divisions_.cbegin ()), theta_divisions_.cend (), theta);
210  const auto phi_min = std::lower_bound(std::next (phi_divisions_.cbegin ()), phi_divisions_.cend (), phi);
211 
212  // Bin (j, k, l)
213  const auto j = std::distance(radii_interval_.cbegin (), std::prev(rad_min));
214  const auto k = std::distance(theta_divisions_.cbegin (), std::prev(theta_min));
215  const auto l = std::distance(phi_divisions_.cbegin (), std::prev(phi_min));
216 
217  // Local point density = number of points in a sphere of radius "point_density_radius_" around the current neighbour
218  std::vector<int> neighbour_indices;
219  std::vector<float> neighbour_distances;
220  int point_density = searchForNeighbors (*surface_, nn_indices[ne], point_density_radius_, neighbour_indices, neighbour_distances);
221  // point_density is NOT always bigger than 0 (on error, searchForNeighbors returns 0), so we must check for that
222  if (point_density == 0)
223  continue;
224 
225  float w = (1.0f / static_cast<float> (point_density)) *
226  volume_lut_[(l*elevation_bins_*radius_bins_) + (k*radius_bins_) + j];
227 
228  assert (w >= 0.0);
229  if (w == std::numeric_limits<float>::infinity ())
230  PCL_ERROR ("Shape Context Error INF!\n");
231  if (std::isnan(w))
232  PCL_ERROR ("Shape Context Error IND!\n");
233  /// Accumulate w into correspondent Bin(j,k,l)
234  desc[(l*elevation_bins_*radius_bins_) + (k*radius_bins_) + j] += w;
235 
236  assert (desc[(l*elevation_bins_*radius_bins_) + (k*radius_bins_) + j] >= 0);
237  } // end for each neighbour
238 
239  // 3DSC does not define a repeatable local RF, we set it to zero to signal it to the user
240  std::fill (rf, rf + 9, 0);
241  return (true);
242 }
243 
244 //////////////////////////////////////////////////////////////////////////////////////////////
245 template <typename PointInT, typename PointNT, typename PointOutT> void
247 {
248  assert (descriptor_length_ == 1980);
249 
250  output.is_dense = true;
251  // Iterate over all points and compute the descriptors
252  for (std::size_t point_index = 0; point_index < indices_->size (); point_index++)
253  {
254  //output[point_index].descriptor.resize (descriptor_length_);
255 
256  // If the point is not finite, set the descriptor to NaN and continue
257  if (!isFinite ((*input_)[(*indices_)[point_index]]))
258  {
259  std::fill (output[point_index].descriptor, output[point_index].descriptor + descriptor_length_,
260  std::numeric_limits<float>::quiet_NaN ());
261  std::fill (output[point_index].rf, output[point_index].rf + 9, 0);
262  output.is_dense = false;
263  continue;
264  }
265 
266  std::vector<float> descriptor (descriptor_length_);
267  if (!computePoint (point_index, *normals_, output[point_index].rf, descriptor))
268  output.is_dense = false;
269  std::copy (descriptor.begin (), descriptor.end (), output[point_index].descriptor);
270  }
271 }
272 
273 #define PCL_INSTANTIATE_ShapeContext3DEstimation(T,NT,OutT) template class PCL_EXPORTS pcl::ShapeContext3DEstimation<T,NT,OutT>;
274 
275 #endif
pcl::ShapeContext3DEstimation::computePoint
bool computePoint(std::size_t index, const pcl::PointCloud< PointNT > &normals, float rf[9], std::vector< float > &desc)
Estimate a descriptor for a given point.
Definition: 3dsc.hpp:130
pcl::ShapeContext3DEstimation::initCompute
bool initCompute() override
Initialize computation by allocating all the intervals and the volume lookup table.
Definition: 3dsc.hpp:50
pcl::geometry::distance
float distance(const PointT &p1, const PointT &p2)
Definition: geometry.h:60
pcl::isFinite
bool isFinite(const PointT &pt)
Tests if the 3D components of a point are all finite param[in] pt point to be tested return true if f...
Definition: point_tests.h:55
pcl::ShapeContext3DEstimation::PointCloudOut
typename Feature< PointInT, PointOutT >::PointCloudOut PointCloudOut
Definition: 3dsc.h:89
geometry.h
pcl::PointCloud< PointNT >
angles.h
pcl::geometry::project
void project(const PointT &point, const PointT &plane_origin, const NormalT &plane_normal, PointT &projected)
Definition: geometry.h:81
pcl::deg2rad
float deg2rad(float alpha)
Convert an angle from degrees to radians.
Definition: angles.hpp:67
pcl::ShapeContext3DEstimation::computeFeature
void computeFeature(PointCloudOut &output) override
Estimate the actual feature.
Definition: 3dsc.hpp:246
pcl::FeatureFromNormals
Definition: feature.h:310
pcl::Vector3fMapConst
const Eigen::Map< const Eigen::Vector3f > Vector3fMapConst
Definition: point_types.hpp:173
pcl::utils::equal
bool equal(T val1, T val2, T eps=std::numeric_limits< T >::min())
Check if val1 and val2 are equal to an epsilon extent.
Definition: utils.h:55
pcl::rad2deg
float rad2deg(float alpha)
Convert an angle from radians to degrees.
Definition: angles.hpp:61