Point Cloud Library (PCL)  1.4.0
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Defines
spin_image.hpp
Go to the documentation of this file.
00001 /*
00002  * Software License Agreement (BSD License)
00003  *
00004  *  Point Cloud Library (PCL) - www.pointclouds.org
00005  *  Copyright (c) 2010-2011, Willow Garage, Inc.
00006  *
00007  *  All rights reserved.
00008  *
00009  *  Redistribution and use in source and binary forms, with or without
00010  *  modification, are permitted provided that the following conditions
00011  *  are met:
00012  *
00013  *   * Redistributions of source code must retain the above copyright
00014  *     notice, this list of conditions and the following disclaimer.
00015  *   * Redistributions in binary form must reproduce the above
00016  *     copyright notice, this list of conditions and the following
00017  *     disclaimer in the documentation and/or other materials provided
00018  *     with the distribution.
00019  *   * Neither the name of Willow Garage, Inc. nor the names of its
00020  *     contributors may be used to endorse or promote products derived
00021  *     from this software without specific prior written permission.
00022  *
00023  *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
00024  *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
00025  *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
00026  *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
00027  *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
00028  *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
00029  *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
00030  *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
00031  *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
00032  *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
00033  *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
00034  *  POSSIBILITY OF SUCH DAMAGE.
00035  *
00036  * $Id: spin_image.hpp 3755 2011-12-31 23:45:30Z rusu $
00037  *
00038  */
00039 
00040 #ifndef PCL_FEATURES_IMPL_SPIN_IMAGE_H_
00041 #define PCL_FEATURES_IMPL_SPIN_IMAGE_H_
00042 
00043 #include <limits>
00044 #include <pcl/point_cloud.h>
00045 #include <pcl/point_types.h>
00046 #include <pcl/exceptions.h>
00047 #include <pcl/kdtree/kdtree_flann.h>
00048 #include <pcl/features/spin_image.h>
00049 
00050 
00051 template <typename PointInT, typename PointNT, typename PointOutT>
00052 const double pcl::SpinImageEstimation<PointInT, PointNT, PointOutT>::PI = 4.0 * std::atan2(1.0, 1.0);
00053 
00055 template <typename PointInT, typename PointNT, typename PointOutT>
00056 pcl::SpinImageEstimation<PointInT, PointNT, PointOutT>::SpinImageEstimation (
00057   unsigned int image_width, double support_angle_cos, unsigned int min_pts_neighb):
00058     is_angular_(false), use_custom_axis_(false), use_custom_axes_cloud_(false), 
00059     is_radial_(false),
00060     image_width_(image_width), support_angle_cos_(support_angle_cos), min_pts_neighb_(min_pts_neighb)
00061 {
00062   assert (support_angle_cos_ <= 1.0 && support_angle_cos_ >= 0.0); // may be permit negative cosine?
00063 
00064   feature_name_ = "SpinImageEstimation";
00065 }
00066 
00067 
00069 template <typename PointInT, typename PointNT, typename PointOutT> Eigen::ArrayXXd 
00070 pcl::SpinImageEstimation<PointInT, PointNT, PointOutT>::computeSiForPoint (int index) const
00071 {
00072   assert (image_width_ > 0);
00073   assert (support_angle_cos_ <= 1.0 && support_angle_cos_ >= 0.0); // may be permit negative cosine?
00074 
00075   const Eigen::Vector3f origin_point (input_->points[index].getVector3fMap ());
00076 
00077   Eigen::Vector3f origin_normal;
00078   origin_normal = 
00079     input_normals_ ? 
00080       input_normals_->points[index].getNormalVector3fMap () :
00081       Eigen::Vector3f (); // just a placeholder; should never be used!
00082 
00083   const Eigen::Vector3f rotation_axis = use_custom_axis_ ? 
00084     rotation_axis_.getNormalVector3fMap () : 
00085     use_custom_axes_cloud_ ?
00086       rotation_axes_cloud_->points[index].getNormalVector3fMap () :
00087       origin_normal;  
00088 
00089   Eigen::ArrayXXd m_matrix (Eigen::ArrayXXd::Zero (image_width_+1, 2*image_width_+1));
00090   Eigen::ArrayXXd m_averAngles (Eigen::ArrayXXd::Zero (image_width_+1, 2*image_width_+1));
00091 
00092   // OK, we are interested in the points of the cylinder of height 2*r and
00093   // base radius r, where r = m_dBinSize * in_iImageWidth
00094   // it can be embedded to the sphere of radius sqrt(2) * m_dBinSize * in_iImageWidth
00095   // suppose that points are uniformly distributed, so we lose ~40%
00096   // according to the volumes ratio
00097   double bin_size = 0.0;
00098   if (is_radial_)
00099   {
00100     bin_size = search_radius_ / image_width_;  
00101   }
00102   else
00103   {
00104     bin_size = search_radius_ / image_width_ / sqrt(2.0);
00105   }
00106 
00107   std::vector<int> nn_indices;
00108   std::vector<float> nn_sqr_dists;
00109   const int neighb_cnt = this->searchForNeighbors (index, search_radius_, nn_indices, nn_sqr_dists);
00110   if (neighb_cnt < (int)min_pts_neighb_)
00111   {
00112     throw PCLException (
00113       "Too few points for spin image, use setMinPointCountInNeighbourhood() to decrease the threshold or use larger feature radius",
00114       "spin_image.hpp", "computeSiForPoint");
00115   }
00116 
00117   // for all neighbor points
00118   for (int i_neigh = 0; i_neigh < neighb_cnt ; i_neigh++)
00119   {
00120     // first, skip the points with distant normals
00121     double cos_between_normals = -2.0; // should be initialized if used
00122     if (support_angle_cos_ > 0.0 || is_angular_) // not bogus
00123     {
00124       cos_between_normals = origin_normal.dot (
00125         normals_->points[nn_indices[i_neigh]].getNormalVector3fMap ());
00126       if (fabs(cos_between_normals) > (1.0 + 10*std::numeric_limits<float>::epsilon())) // should be okay for numeric stability
00127       {      
00128         PCL_ERROR ("[pcl::%s::computeSiForPoint] Normal for the point %d and/or the point %d are not normalized, dot ptoduct is %f.\n", 
00129           getClassName ().c_str (), nn_indices[i_neigh], index, cos_between_normals);
00130         throw PCLException ("Some normals are not normalized",
00131           "spin_image.hpp", "computeSiForPoint");
00132       }
00133       cos_between_normals = std::max (-1.0, std::min (1.0, cos_between_normals));
00134 
00135       if (fabs (cos_between_normals) < support_angle_cos_ )    // allow counter-directed normals
00136       {
00137         continue;
00138       }
00139 
00140       if (cos_between_normals < 0.0)
00141       {
00142         cos_between_normals = -cos_between_normals; // the normal is not used explicitly from now
00143       }
00144     }
00145     
00146     // now compute the coordinate in cylindric coordinate system associated with the origin point
00147     const Eigen::Vector3f direction (
00148       surface_->points[nn_indices[i_neigh]].getVector3fMap () - origin_point);
00149     const double direction_norm = direction.norm ();
00150     if (fabs(direction_norm) < 10*std::numeric_limits<double>::epsilon ())  
00151       continue;  // ignore the point itself; it does not contribute really
00152     assert (direction_norm > 0.0);
00153 
00154     // the angle between the normal vector and the direction to the point
00155     double cos_dir_axis = direction.dot(rotation_axis) / direction_norm;
00156     if (fabs(cos_dir_axis) > (1.0 + 10*std::numeric_limits<float>::epsilon())) // should be okay for numeric stability
00157     {      
00158       PCL_ERROR ("[pcl::%s::computeSiForPoint] Rotation axis for the point %d are not normalized, dot ptoduct is %f.\n", 
00159         getClassName ().c_str (), index, cos_dir_axis);
00160       throw PCLException ("Some rotation axis is not normalized",
00161         "spin_image.hpp", "computeSiForPoint");
00162     }
00163     cos_dir_axis = std::max (-1.0, std::min (1.0, cos_dir_axis));
00164 
00165     // compute coordinates w.r.t. the reference frame
00166     double beta = std::numeric_limits<double>::signaling_NaN ();
00167     double alpha = std::numeric_limits<double>::signaling_NaN ();
00168     if (is_radial_) // radial spin image structure
00169     {
00170       beta = asin (cos_dir_axis);  // yes, arc sine! to get the angle against tangent, not normal!
00171       alpha = direction_norm;
00172     }
00173     else // rectangular spin-image structure
00174     {
00175       beta = direction_norm * cos_dir_axis;
00176       alpha = direction_norm * sqrt (1.0 - cos_dir_axis*cos_dir_axis);
00177 
00178       if (fabs (beta) >= bin_size * image_width_ || alpha >= bin_size * image_width_)
00179       {
00180         continue;  // outside the cylinder
00181       }
00182     }
00183 
00184     assert (alpha >= 0.0);
00185     assert (alpha <= bin_size * image_width_ + 20 * std::numeric_limits<float>::epsilon () );
00186 
00187 
00188     // bilinear interpolation
00189     double beta_bin_size = is_radial_ ? (PI / 2 / image_width_) : bin_size;
00190     int beta_bin = int(std::floor (beta / beta_bin_size)) + int(image_width_);
00191     assert (0 <= beta_bin && beta_bin < m_matrix.cols ());
00192     int alpha_bin = int(std::floor (alpha / bin_size));
00193     assert (0 <= alpha_bin && alpha_bin < m_matrix.rows ());
00194 
00195     if (alpha_bin == (int)image_width_)  // border points
00196     {
00197       alpha_bin--;
00198       // HACK: to prevent a > 1
00199       alpha = bin_size * (alpha_bin + 1) - std::numeric_limits<double>::epsilon ();
00200     }
00201     if (beta_bin == int(2*image_width_) )  // border points
00202     {
00203       beta_bin--;
00204       // HACK: to prevent b > 1
00205       beta = beta_bin_size * (beta_bin - int(image_width_) + 1) - std::numeric_limits<double>::epsilon ();
00206     }
00207 
00208     double a = alpha/bin_size - double(alpha_bin);
00209     double b = beta/beta_bin_size - double(beta_bin-int(image_width_)); 
00210 
00211     assert (0 <= a && a <= 1);
00212     assert (0 <= b && b <= 1);
00213 
00214     m_matrix(alpha_bin, beta_bin) += (1-a) * (1-b);
00215     m_matrix(alpha_bin+1, beta_bin) += a * (1-b);
00216     m_matrix(alpha_bin, beta_bin+1) += (1-a) * b;
00217     m_matrix(alpha_bin+1, beta_bin+1) += a * b;
00218 
00219     if (is_angular_)
00220     {
00221       m_averAngles(alpha_bin, beta_bin) += (1-a) * (1-b) * acos (cos_between_normals); 
00222       m_averAngles(alpha_bin+1, beta_bin) += a * (1-b) * acos (cos_between_normals);
00223       m_averAngles(alpha_bin, beta_bin+1) += (1-a) * b * acos (cos_between_normals);
00224       m_averAngles(alpha_bin+1, beta_bin+1) += a * b * acos (cos_between_normals);
00225     }
00226   }
00227 
00228   if (is_angular_)
00229   {
00230     // transform sum to average
00231     m_matrix = m_averAngles / (m_matrix + std::numeric_limits<double>::epsilon ()); // +eps to avoid division by zero
00232   }
00233   else if (neighb_cnt > 1) // to avoid division by zero, also no need to divide by 1
00234   {
00235     // normalization
00236     m_matrix /= m_matrix.sum();
00237   }
00238 
00239   return m_matrix;
00240 }
00241 
00242 
00244 template <typename PointInT, typename PointNT, typename PointOutT> bool 
00245 pcl::SpinImageEstimation<PointInT, PointNT, PointOutT>::initCompute ()
00246 {
00247   // If the surface won't be set, make fake surface and fake surface normals
00248   // if we wouldn't do it here, the following method would alarm that no surface normals is given
00249   if (!surface_)
00250   {
00251     surface_ = input_;
00252     normals_ = input_normals_;
00253     fake_surface_ = true;
00254   }
00255 
00256   if (!FeatureFromNormals<PointInT, PointNT, PointOutT>::initCompute ())
00257   {
00258     PCL_ERROR ("[pcl::%s::initCompute] Init failed.\n", getClassName ().c_str ());
00259     return (false);
00260   }
00261 
00262   if (fake_surface_ && !input_normals_)
00263   {
00264     input_normals_ = normals_; // normals_ is set, as checked earlier
00265   }
00266   
00267 
00268   assert(!(use_custom_axis_ && use_custom_axes_cloud_));
00269 
00270   if (!use_custom_axis_ && !use_custom_axes_cloud_ // use input normals as rotation axes
00271     && !input_normals_)
00272   {
00273     PCL_ERROR ("[pcl::%s::initCompute] No normals for input cloud were given!\n", getClassName ().c_str ());
00274     // Cleanup
00275     FeatureFromNormals<PointInT, PointNT, PointOutT>::deinitCompute ();
00276     return (false);
00277   }
00278 
00279   if ((is_angular_ || support_angle_cos_ > 0.0) // support angle is not bogus NOTE this is for randomly-flipped normals
00280     && !input_normals_)
00281   {
00282     PCL_ERROR ("[pcl::%s::initCompute] No normals for input cloud were given!\n", getClassName ().c_str ());
00283     // Cleanup
00284     FeatureFromNormals<PointInT, PointNT, PointOutT>::deinitCompute ();
00285     return (false);
00286   }
00287 
00288   if (use_custom_axes_cloud_ 
00289     && rotation_axes_cloud_->size () == input_->size ())
00290   {
00291     PCL_ERROR ("[pcl::%s::initCompute] Rotation axis cloud have different size from input!\n", getClassName ().c_str ());
00292     // Cleanup
00293     FeatureFromNormals<PointInT, PointNT, PointOutT>::deinitCompute ();
00294     return (false);
00295   }
00296 
00297   return true;
00298 }
00299 
00300 
00302 template <typename PointInT, typename PointNT, typename PointOutT> void 
00303 pcl::SpinImageEstimation<PointInT, PointNT, PointOutT>::computeFeature (PointCloudOut &output)
00304 { 
00305   for (int i_input = 0; i_input < (int)indices_->size (); ++i_input)
00306   {
00307     Eigen::ArrayXXd res = computeSiForPoint (indices_->at (i_input));
00308 
00309     // Copy into the resultant cloud
00310     for (int iRow = 0; iRow < res.rows () ; iRow++)
00311     {
00312       for (int iCol = 0; iCol < res.cols () ; iCol++)
00313       {
00314         output.points[i_input].histogram[ iRow*res.cols () + iCol ] = (float)res(iRow, iCol);
00315       }
00316     }   
00317   } 
00318 }
00319 
00321 template <typename PointInT, typename PointNT> void 
00322 pcl::SpinImageEstimation<PointInT, PointNT, Eigen::MatrixXf>::computeFeature (pcl::PointCloud<Eigen::MatrixXf> &output)
00323 { 
00324   output.points.resize (indices_->size (), 153);
00325   for (int i_input = 0; i_input < (int)indices_->size (); ++i_input)
00326   {
00327     Eigen::ArrayXXd res = this->computeSiForPoint (indices_->at (i_input));
00328 
00329     // Copy into the resultant cloud
00330     for (int iRow = 0; iRow < res.rows () ; iRow++)
00331     {
00332       for (int iCol = 0; iCol < res.cols () ; iCol++)
00333       {
00334         output.points (i_input, iRow*res.cols () + iCol) = (float)res(iRow, iCol);
00335       }
00336     }   
00337   } 
00338 }
00339 
00340 
00341 #define PCL_INSTANTIATE_SpinImageEstimation(T,NT,OutT) template class PCL_EXPORTS pcl::SpinImageEstimation<T,NT,OutT>;
00342 
00343 #endif    // PCL_FEATURES_IMPL_SPIN_IMAGE_H_
00344 
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Defines