normal.cpp 29.5 KB
Newer Older
Vincent Rabaud's avatar
Vincent Rabaud committed
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
/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2012, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions 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.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may 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
 *  COPYRIGHT OWNER 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.
 *
 */

36
#include "precomp.hpp"
Vincent Rabaud's avatar
Vincent Rabaud committed
37

38
namespace cv
Vincent Rabaud's avatar
Vincent Rabaud committed
39
{
40
namespace rgbd
41
{
Vincent Rabaud's avatar
Vincent Rabaud committed
42 43 44 45 46 47 48
  /** Just compute the norm of a vector
   * @param vec a vector of size 3 and any type T
   * @return
   */
  template<typename T>
  T
  inline
49
  norm_vec(const Vec<T, 3> &vec)
Vincent Rabaud's avatar
Vincent Rabaud committed
50 51 52 53 54 55 56 57 58
  {
    return std::sqrt(vec[0] * vec[0] + vec[1] * vec[1] + vec[2] * vec[2]);
  }

  /** Given 3d points, compute their distance to the origin
   * @param points
   * @return
   */
  template<typename T>
59 60
  Mat_<T>
  computeRadius(const Mat &points)
Vincent Rabaud's avatar
Vincent Rabaud committed
61
  {
62
    typedef Vec<T, 3> PointT;
Vincent Rabaud's avatar
Vincent Rabaud committed
63 64

    // Compute the
65 66
    Size size(points.cols, points.rows);
    Mat_<T> r(size);
Vincent Rabaud's avatar
Vincent Rabaud committed
67
    if (points.isContinuous())
68
      size = Size(points.cols * points.rows, 1);
Vincent Rabaud's avatar
Vincent Rabaud committed
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
    for (int y = 0; y < size.height; ++y)
    {
      const PointT* point = points.ptr < PointT > (y), *point_end = points.ptr < PointT > (y) + size.width;
      T * row = r[y];
      for (; point != point_end; ++point, ++row)
        *row = norm_vec(*point);
    }

    return r;
  }

  // Compute theta and phi according to equation 3 of
  // ``Fast and Accurate Computation of Surface Normals from Range Images``
  // by H. Badino, D. Huber, Y. Park and T. Kanade
  template<typename T>
  void
85 86
  computeThetaPhi(int rows, int cols, const Matx<T, 3, 3>& K, Mat &cos_theta, Mat &sin_theta,
                  Mat &cos_phi, Mat &sin_phi)
Vincent Rabaud's avatar
Vincent Rabaud committed
87 88
  {
    // Create some bogus coordinates
89 90 91
    Mat depth_image = K(0, 0) * Mat_ < T > ::ones(rows, cols);
    Mat points3d;
    depthTo3d(depth_image, Mat(K), points3d);
Vincent Rabaud's avatar
Vincent Rabaud committed
92

93
    typedef Vec<T, 3> Vec3T;
Vincent Rabaud's avatar
Vincent Rabaud committed
94

95 96 97 98 99
    cos_theta = Mat_ < T > (rows, cols);
    sin_theta = Mat_ < T > (rows, cols);
    cos_phi = Mat_ < T > (rows, cols);
    sin_phi = Mat_ < T > (rows, cols);
    Mat r = computeRadius<T>(points3d);
Vincent Rabaud's avatar
Vincent Rabaud committed
100 101 102 103 104 105 106 107 108 109 110 111 112
    for (int y = 0; y < rows; ++y)
    {
      T *row_cos_theta = cos_theta.ptr < T > (y), *row_sin_theta = sin_theta.ptr < T > (y);
      T *row_cos_phi = cos_phi.ptr < T > (y), *row_sin_phi = sin_phi.ptr < T > (y);
      const Vec3T * row_points = points3d.ptr < Vec3T > (y), *row_points_end = points3d.ptr < Vec3T
          > (y) + points3d.cols;
      const T * row_r = r.ptr < T > (y);
      for (; row_points < row_points_end;
          ++row_cos_theta, ++row_sin_theta, ++row_cos_phi, ++row_sin_phi, ++row_points, ++row_r)
      {
        // In the paper, z goes away from the camera, y goes down, x goes right
        // OpenCV has the same conventions
        // Theta goes from z to x (and actually goes from -pi/2 to pi/2, phi goes from z to y
Ilya Lavrenov's avatar
Ilya Lavrenov committed
113
        float theta = (float)std::atan2(row_points->val[0], row_points->val[2]);
Vincent Rabaud's avatar
Vincent Rabaud committed
114 115
        *row_cos_theta = std::cos(theta);
        *row_sin_theta = std::sin(theta);
Ilya Lavrenov's avatar
Ilya Lavrenov committed
116
        float phi = (float)std::asin(row_points->val[1] / (*row_r));
Vincent Rabaud's avatar
Vincent Rabaud committed
117 118 119 120 121 122 123 124 125 126 127 128
        *row_cos_phi = std::cos(phi);
        *row_sin_phi = std::sin(phi);
      }
    }
  }

  /** Modify normals to make sure they point towards the camera
   * @param normals
   */
  template<typename T>
  inline
  void
129
  signNormal(const Vec<T, 3> & normal_in, Vec<T, 3> & normal_out)
Vincent Rabaud's avatar
Vincent Rabaud committed
130
  {
131
    Vec<T, 3> res;
Vincent Rabaud's avatar
Vincent Rabaud committed
132 133 134 135
    if (normal_in[2] > 0)
      res = -normal_in / norm_vec(normal_in);
    else
      res = normal_in / norm_vec(normal_in);
136

Vincent Rabaud's avatar
Vincent Rabaud committed
137 138 139 140 141 142 143 144 145 146
    normal_out[0] = res[0];
    normal_out[1] = res[1];
    normal_out[2] = res[2];
  }
  /** Modify normals to make sure they point towards the camera
   * @param normals
   */
  template<typename T>
  inline
  void
147
  signNormal(T a, T b, T c, Vec<T, 3> & normal)
Vincent Rabaud's avatar
Vincent Rabaud committed
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
  {
    T norm = 1 / std::sqrt(a * a + b * b + c * c);
    if (c > 0)
    {
      normal[0] = -a * norm;
      normal[1] = -b * norm;
      normal[2] = -c * norm;
    }
    else
    {
      normal[0] = a * norm;
      normal[1] = b * norm;
      normal[2] = c * norm;
    }
  }
163

Vincent Rabaud's avatar
Vincent Rabaud committed
164 165 166 167 168
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  class RgbdNormalsImpl
  {
  public:
169 170
    RgbdNormalsImpl(int rows, int cols, int window_size, int depth, const Mat &K,
                    RgbdNormals::RGBD_NORMALS_METHOD method)
Vincent Rabaud's avatar
Vincent Rabaud committed
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
        :
          rows_(rows),
          cols_(cols),
          depth_(depth),
          window_size_(window_size),
          method_(method)
    {
      K.convertTo(K_, depth);
      K.copyTo(K_ori_);
    }

    virtual
    ~RgbdNormalsImpl()
    {
    }

    virtual void
    cache()=0;

    bool
191
    validate(int rows, int cols, int depth, const Mat &K_ori, int window_size, int method) const
Vincent Rabaud's avatar
Vincent Rabaud committed
192 193 194
    {
      if ((K_ori.cols != K_ori_.cols) || (K_ori.rows != K_ori_.rows) || (K_ori.type() != K_ori_.type()))
        return false;
195
      bool K_test = !(countNonZero(K_ori != K_ori_));
Ilya Lavrenov's avatar
Ilya Lavrenov committed
196
      return (rows == rows_) && (cols == cols_) && (window_size == window_size_) && (depth == depth_) && (K_test)
Vincent Rabaud's avatar
Vincent Rabaud committed
197 198 199 200
             && (method == method_);
    }
  protected:
    int rows_, cols_, depth_;
201
    Mat K_, K_ori_;
Vincent Rabaud's avatar
Vincent Rabaud committed
202
    int window_size_;
203
    RgbdNormals::RGBD_NORMALS_METHOD method_;
Vincent Rabaud's avatar
Vincent Rabaud committed
204 205 206 207 208 209 210 211 212 213 214 215 216
  };

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  /** Given a set of 3d points in a depth image, compute the normals at each point
   * using the FALS method described in
   * ``Fast and Accurate Computation of Surface Normals from Range Images``
   * by H. Badino, D. Huber, Y. Park and T. Kanade
   */
  template<typename T>
  class FALS: public RgbdNormalsImpl
  {
  public:
217 218 219
    typedef Matx<T, 3, 3> Mat33T;
    typedef Vec<T, 9> Vec9T;
    typedef Vec<T, 3> Vec3T;
Vincent Rabaud's avatar
Vincent Rabaud committed
220

221
    FALS(int rows, int cols, int window_size, int depth, const Mat &K, RgbdNormals::RGBD_NORMALS_METHOD method)
Vincent Rabaud's avatar
Vincent Rabaud committed
222 223 224 225 226 227 228 229 230 231 232 233 234 235
        :
          RgbdNormalsImpl(rows, cols, window_size, depth, K, method)
    {
    }
    ~FALS()
    {
    }

    /** Compute cached data
     */
    virtual void
    cache()
    {
      // Compute theta and phi according to equation 3
236
      Mat cos_theta, sin_theta, cos_phi, sin_phi;
Vincent Rabaud's avatar
Vincent Rabaud committed
237 238 239
      computeThetaPhi<T>(rows_, cols_, K_, cos_theta, sin_theta, cos_phi, sin_phi);

      // Compute all the v_i for every points
240
      std::vector<Mat> channels(3);
Vincent Rabaud's avatar
Vincent Rabaud committed
241 242 243
      channels[0] = sin_theta.mul(cos_phi);
      channels[1] = sin_phi;
      channels[2] = cos_theta.mul(cos_phi);
244
      merge(channels, V_);
Vincent Rabaud's avatar
Vincent Rabaud committed
245 246

      // Compute M
247
      Mat_<Vec9T> M(rows_, cols_);
Vincent Rabaud's avatar
Vincent Rabaud committed
248 249 250 251 252 253 254 255 256
      Mat33T VVt;
      const Vec3T * vec = V_[0];
      Vec9T * M_ptr = M[0], *M_ptr_end = M_ptr + rows_ * cols_;
      for (; M_ptr != M_ptr_end; ++vec, ++M_ptr)
      {
        VVt = (*vec) * vec->t();
        *M_ptr = Vec9T(VVt.val);
      }

257
      boxFilter(M, M, M.depth(), Size(window_size_, window_size_), Point(-1, -1), false);
Vincent Rabaud's avatar
Vincent Rabaud committed
258 259 260 261 262 263 264 265

      // Compute M's inverse
      Mat33T M_inv;
      M_inv_.create(rows_, cols_);
      Vec9T * M_inv_ptr = M_inv_[0];
      for (M_ptr = &M(0); M_ptr != M_ptr_end; ++M_inv_ptr, ++M_ptr)
      {
        // We have a semi-definite matrix
266
        invert(Mat33T(M_ptr->val), M_inv, DECOMP_CHOLESKY);
Vincent Rabaud's avatar
Vincent Rabaud committed
267 268 269 270 271 272 273 274 275
        *M_inv_ptr = Vec9T(M_inv.val);
      }
    }

    /** Compute the normals
     * @param r
     * @return
     */
    virtual void
276
    compute(const Mat&, const Mat &r, Mat & normals) const
Vincent Rabaud's avatar
Vincent Rabaud committed
277 278
    {
      // Compute B
279
      Mat_<Vec3T> B(rows_, cols_);
Vincent Rabaud's avatar
Vincent Rabaud committed
280 281 282 283 284 285 286 287 288 289 290 291 292

      const T* row_r = r.ptr < T > (0), *row_r_end = row_r + rows_ * cols_;
      const Vec3T *row_V = V_[0];
      Vec3T *row_B = B[0];
      for (; row_r != row_r_end; ++row_r, ++row_B, ++row_V)
      {
        if (cvIsNaN(*row_r))
          *row_B = Vec3T();
        else
          *row_B = (*row_V) / (*row_r);
      }

      // Apply a box filter to B
293
      boxFilter(B, B, B.depth(), Size(window_size_, window_size_), Point(-1, -1), false);
Vincent Rabaud's avatar
Vincent Rabaud committed
294 295 296 297 298 299 300 301 302 303 304 305 306 307

      // compute the Minv*B products
      row_r = r.ptr < T > (0);
      const Vec3T * B_vec = B[0];
      const Mat33T * M_inv = reinterpret_cast<const Mat33T *>(M_inv_.ptr(0));
      Vec3T *normal = normals.ptr<Vec3T>(0);
      for (; row_r != row_r_end; ++row_r, ++B_vec, ++normal, ++M_inv)
        if (cvIsNaN(*row_r))
        {
          (*normal)[0] = *row_r;
          (*normal)[1] = *row_r;
          (*normal)[2] = *row_r;
        }
        else
308 309 310 311 312 313 314 315
        {
            Mat33T Mr = *M_inv;
            Vec3T Br = *B_vec;
            Vec3T MBr(Mr(0, 0) * Br[0] + Mr(0, 1)*Br[1] + Mr(0, 2)*Br[2],
                      Mr(1, 0) * Br[0] + Mr(1, 1)*Br[1] + Mr(1, 2)*Br[2],
                      Mr(2, 0) * Br[0] + Mr(2, 1)*Br[1] + Mr(2, 2)*Br[2]);
           signNormal(MBr, *normal);
        }
Vincent Rabaud's avatar
Vincent Rabaud committed
316 317 318
    }

  private:
319 320
    Mat_<Vec3T> V_;
    Mat_<Vec9T> M_inv_;
Vincent Rabaud's avatar
Vincent Rabaud committed
321 322 323 324 325 326 327 328 329 330 331 332 333 334
  };

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/** Function that multiplies K_inv by a vector. It is just meant to speed up the product as we know
 * that K_inv is upper triangular and K_inv(2,2)=1
 * @param K_inv
 * @param a
 * @param b
 * @param c
 * @param res
 */
template<typename T, typename U>
void
335
multiply_by_K_inv(const Matx<T, 3, 3> & K_inv, U a, U b, U c, Vec<T, 3> &res)
Vincent Rabaud's avatar
Vincent Rabaud committed
336
{
Ilya Lavrenov's avatar
Ilya Lavrenov committed
337 338 339
  res[0] = (T)(K_inv(0, 0) * a + K_inv(0, 1) * b + K_inv(0, 2) * c);
  res[1] = (T)(K_inv(1, 1) * b + K_inv(1, 2) * c);
  res[2] = (T)c;
Vincent Rabaud's avatar
Vincent Rabaud committed
340 341 342 343 344 345 346 347 348 349
}

  /** Given a depth image, compute the normals as detailed in the LINEMOD paper
   * ``Gradient Response Maps for Real-Time Detection of Texture-Less Objects``
   * by S. Hinterstoisser, C. Cagniart, S. Ilic, P. Sturm, N. Navab, P. Fua, and V. Lepetit
   */
  template<typename T>
  class LINEMOD: public RgbdNormalsImpl
  {
  public:
350 351
    typedef Vec<T, 3> Vec3T;
    typedef Matx<T, 3, 3> Mat33T;
Vincent Rabaud's avatar
Vincent Rabaud committed
352

353 354
    LINEMOD(int rows, int cols, int window_size, int depth, const Mat &K,
            RgbdNormals::RGBD_NORMALS_METHOD method)
Vincent Rabaud's avatar
Vincent Rabaud committed
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
        :
          RgbdNormalsImpl(rows, cols, window_size, depth, K, method)
    {
    }

    /** Compute cached data
     */
    virtual void
    cache()
    {
    }

    /** Compute the normals
     * @param r
     * @param normals the output normals
     */
    void
372
    compute(const Mat& depth_in, Mat & normals) const
Vincent Rabaud's avatar
Vincent Rabaud committed
373 374 375 376 377
    {
      switch (depth_in.depth())
      {
        case CV_16U:
        {
378
          const Mat_<unsigned short> &depth(depth_in);
Vincent Rabaud's avatar
Vincent Rabaud committed
379 380 381 382 383
          computeImpl<unsigned short, long>(depth, normals);
          break;
        }
        case CV_32F:
        {
384
          const Mat_<float> &depth(depth_in);
Vincent Rabaud's avatar
Vincent Rabaud committed
385 386 387 388 389
          computeImpl<float, float>(depth, normals);
          break;
        }
        case CV_64F:
        {
390
          const Mat_<double> &depth(depth_in);
Vincent Rabaud's avatar
Vincent Rabaud committed
391 392 393 394 395 396 397 398 399 400 401 402
          computeImpl<double, double>(depth, normals);
          break;
        }
      }
    }

  private:
    /** Compute the normals
     * @param r
     * @return
     */
    template<typename DepthDepth, typename ContainerDepth>
403 404
    Mat
    computeImpl(const Mat_<DepthDepth> &depth, Mat & normals) const
Vincent Rabaud's avatar
Vincent Rabaud committed
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
    {
      const int r = 5; // used to be 7
      const int sample_step = r;
      const int square_size = ((2 * r / sample_step) + 1);
      long offsets[square_size * square_size];
      long offsets_x[square_size * square_size];
      long offsets_y[square_size * square_size];
      long offsets_x_x[square_size * square_size];
      long offsets_x_y[square_size * square_size];
      long offsets_y_y[square_size * square_size];
      for (int j = -r, index = 0; j <= r; j += sample_step)
        for (int i = -r; i <= r; i += sample_step, ++index)
        {
          offsets_x[index] = i;
          offsets_y[index] = j;
          offsets_x_x[index] = i*i;
          offsets_x_y[index] = i*j;
          offsets_y_y[index] = j*j;
          offsets[index] = j * cols_ + i;
        }

      // Define K_inv by hand, just for higher accuracy
427
      Mat33T K_inv = Matx<T, 3, 3>::eye(), K;
Vincent Rabaud's avatar
Vincent Rabaud committed
428
      K_.copyTo(K);
Ilya Lavrenov's avatar
Ilya Lavrenov committed
429
      K_inv(0, 0) = 1.0f / K(0, 0);
Vincent Rabaud's avatar
Vincent Rabaud committed
430 431 432 433 434 435 436 437
      K_inv(0, 1) = -K(0, 1) / (K(0, 0) * K(1, 1));
      K_inv(0, 2) = (K(0, 1) * K(1, 2) - K(0, 2) * K(1, 1)) / (K(0, 0) * K(1, 1));
      K_inv(1, 1) = 1 / K(1, 1);
      K_inv(1, 2) = -K(1, 2) / K(1, 1);

      Vec3T X1_minus_X, X2_minus_X;

      ContainerDepth difference_threshold = 50;
438
      normals.setTo(std::numeric_limits<DepthDepth>::quiet_NaN());
Vincent Rabaud's avatar
Vincent Rabaud committed
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 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
      for (int y = r; y < rows_ - r - 1; ++y)
      {
        const DepthDepth * p_line = reinterpret_cast<const DepthDepth*>(depth.ptr(y, r));
        Vec3T *normal = normals.ptr<Vec3T>(y, r);

        for (int x = r; x < cols_ - r - 1; ++x)
        {
          DepthDepth d = p_line[0];

          // accum
          long A[4];
          A[0] = A[1] = A[2] = A[3] = 0;
          ContainerDepth b[2];
          b[0] = b[1] = 0;
          for (unsigned int i = 0; i < square_size * square_size; ++i) {
            // We need to cast to ContainerDepth in case we have unsigned DepthDepth
            ContainerDepth delta = ContainerDepth(p_line[offsets[i]]) - ContainerDepth(d);
            if (std::abs(delta) > difference_threshold)
               continue;

             A[0] += offsets_x_x[i];
             A[1] += offsets_x_y[i];
             A[3] += offsets_y_y[i];
             b[0] += offsets_x[i] * delta;
             b[1] += offsets_y[i] * delta;
          }

          // solve for the optimal gradient D of equation (8)
          long det = A[0] * A[3] - A[1] * A[1];
          // We should divide the following two by det, but instead, we multiply
          // X1_minus_X and X2_minus_X by det (which does not matter as we normalize the normals)
          // Therefore, no division is done: this is only for speedup
          ContainerDepth dx = (A[3] * b[0] - A[1] * b[1]);
          ContainerDepth dy = (-A[1] * b[0] + A[0] * b[1]);

          // Compute the dot product
          //Vec3T X = K_inv * Vec3T(x, y, 1) * depth(y, x);
          //Vec3T X1 = K_inv * Vec3T(x + 1, y, 1) * (depth(y, x) + dx);
          //Vec3T X2 = K_inv * Vec3T(x, y + 1, 1) * (depth(y, x) + dy);
          //Vec3T nor = (X1 - X).cross(X2 - X);
          multiply_by_K_inv(K_inv, d * det + (x + 1) * dx, y * dx, dx, X1_minus_X);
          multiply_by_K_inv(K_inv, x * dy, d * det + (y + 1) * dy, dy, X2_minus_X);
          Vec3T nor = X1_minus_X.cross(X2_minus_X);
          signNormal(nor, *normal);

          ++p_line;
          ++normal;
        }
      }

      return normals;
    }
  };

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  /** Given a set of 3d points in a depth image, compute the normals at each point
   * using the SRI method described in
   * ``Fast and Accurate Computation of Surface Normals from Range Images``
   * by H. Badino, D. Huber, Y. Park and T. Kanade
   */
  template<typename T>
  class SRI: public RgbdNormalsImpl
  {
  public:
504 505 506
    typedef Matx<T, 3, 3> Mat33T;
    typedef Vec<T, 9> Vec9T;
    typedef Vec<T, 3> Vec3T;
Vincent Rabaud's avatar
Vincent Rabaud committed
507

508
    SRI(int rows, int cols, int window_size, int depth, const Mat &K, RgbdNormals::RGBD_NORMALS_METHOD method)
Vincent Rabaud's avatar
Vincent Rabaud committed
509 510 511 512 513 514 515 516 517 518 519 520
        :
          RgbdNormalsImpl(rows, cols, window_size, depth, K, method),
          phi_step_(0),
          theta_step_(0)
    {
    }

    /** Compute cached data
     */
    virtual void
    cache()
    {
521
      Mat_<T> cos_theta, sin_theta, cos_phi, sin_phi;
Vincent Rabaud's avatar
Vincent Rabaud committed
522 523 524 525 526 527 528
      computeThetaPhi<T>(rows_, cols_, K_, cos_theta, sin_theta, cos_phi, sin_phi);

      // Create the derivative kernels
      getDerivKernels(kx_dx_, ky_dx_, 1, 0, window_size_, true, depth_);
      getDerivKernels(kx_dy_, ky_dy_, 0, 1, window_size_, true, depth_);

      // Get the mapping function for SRI
Ilya Lavrenov's avatar
Ilya Lavrenov committed
529
      float min_theta = (float)std::asin(sin_theta(0, 0)), max_theta = (float)std::asin(sin_theta(0, cols_ - 1));
530
      float min_phi = (float)std::asin(sin_phi(0, cols_/2-1)), max_phi = (float)std::asin(sin_phi(rows_ - 1, cols_/2-1));
Vincent Rabaud's avatar
Vincent Rabaud committed
531

532
      std::vector<Point3f> points3d(cols_ * rows_);
Vincent Rabaud's avatar
Vincent Rabaud committed
533 534 535 536 537 538 539 540 541 542
      R_hat_.create(rows_, cols_);
      phi_step_ = float(max_phi - min_phi) / (rows_ - 1);
      theta_step_ = float(max_theta - min_theta) / (cols_ - 1);
      for (int phi_int = 0, k = 0; phi_int < rows_; ++phi_int)
      {
        float phi = min_phi + phi_int * phi_step_;
        for (int theta_int = 0; theta_int < cols_; ++theta_int, ++k)
        {
          float theta = min_theta + theta_int * theta_step_;
          // Store the 3d point to project it later
543
          points3d[k] = Point3f(std::sin(theta) * std::cos(phi), std::sin(phi), std::cos(theta) * std::cos(phi));
Vincent Rabaud's avatar
Vincent Rabaud committed
544 545

          // Cache the rotation matrix and negate it
546 547
          Mat_<T> mat =
              (Mat_ < T > (3, 3) << 0, 1, 0, 0, 0, 1, 1, 0, 0) * ((Mat_ < T > (3, 3) << std::cos(theta), -std::sin(
Vincent Rabaud's avatar
Vincent Rabaud committed
548
                  theta), 0, std::sin(theta), std::cos(theta), 0, 0, 0, 1))
549
              * ((Mat_ < T > (3, 3) << std::cos(phi), 0, -std::sin(phi), 0, 1, 0, std::sin(phi), 0, std::cos(phi)));
Vincent Rabaud's avatar
Vincent Rabaud committed
550 551 552 553 554 555 556 557 558 559 560 561
          for (unsigned char i = 0; i < 3; ++i)
            mat(i, 1) = mat(i, 1) / std::cos(phi);
          // The second part of the matrix is never explained in the paper ... but look at the wikipedia normal article
          mat(0, 0) = mat(0, 0) - 2 * std::cos(phi) * std::sin(theta);
          mat(1, 0) = mat(1, 0) - 2 * std::sin(phi);
          mat(2, 0) = mat(2, 0) - 2 * std::cos(phi) * std::cos(theta);

          R_hat_(phi_int, theta_int) = Vec9T((T*) (mat.data));
        }
      }

      map_.create(rows_, cols_);
562
      projectPoints(points3d, Mat(3,1,CV_32FC1,Scalar::all(0.0f)), Mat(3,1,CV_32FC1,Scalar::all(0.0f)), K_, Mat(), map_);
Vincent Rabaud's avatar
Vincent Rabaud committed
563
      map_ = map_.reshape(2, rows_);
564
      convertMaps(map_, Mat(), xy_, fxy_, CV_16SC2);
Vincent Rabaud's avatar
Vincent Rabaud committed
565 566 567

      //map for converting from Spherical coordinate space to Euclidean space
      euclideanMap_.create(rows_,cols_);
Ilya Lavrenov's avatar
Ilya Lavrenov committed
568
      float invFx = (float)(1.0f/K_.at<T>(0,0)), cx = (float)K_.at<T>(0,2);
Vincent Rabaud's avatar
Vincent Rabaud committed
569 570 571
      double invFy = 1.0f/K_.at<T>(1,1), cy = K_.at<T>(1,2);
      for (int i = 0; i < rows_; i++)
      {
Ilya Lavrenov's avatar
Ilya Lavrenov committed
572
          float y = (float)((i - cy)*invFy);
Vincent Rabaud's avatar
Vincent Rabaud committed
573 574 575 576 577 578
          for (int j = 0; j < cols_; j++)
          {
              float x = (j - cx)*invFx;
              float theta = std::atan(x);
              float phi = std::asin(y/std::sqrt(x*x+y*y+1.0f));

579
              euclideanMap_(i,j) = Vec2f((theta-min_theta)/theta_step_,(phi-min_phi)/phi_step_);
Vincent Rabaud's avatar
Vincent Rabaud committed
580 581 582
          }
      }
      //convert map to 2 maps in short format for increasing speed in remap function
583
      convertMaps(euclideanMap_, Mat(), invxy_, invfxy_, CV_16SC2);
Vincent Rabaud's avatar
Vincent Rabaud committed
584 585 586 587 588 589 590 591 592 593 594 595

      // Update the kernels: the steps are due to the fact that derivatives will be computed on a grid where
      // the step is not 1. Only need to do it on one dimension as it computes derivatives in only one direction
      kx_dx_ /= theta_step_;
      ky_dy_ /= phi_step_;
    }

    /** Compute the normals
     * @param r
     * @return
     */
    virtual void
596
    compute(const Mat& points3d, const Mat &r, Mat & normals) const
Vincent Rabaud's avatar
Vincent Rabaud committed
597
    {
598 599
      const Mat_<T>& r_T(r);
      const Mat_<Vec3T> &points3d_T(points3d);
Vincent Rabaud's avatar
Vincent Rabaud committed
600 601 602 603 604 605 606 607
      compute(points3d_T, r_T, normals);
    }

    /** Compute the normals
     * @param r
     * @return
     */
    void
608
    compute(const Mat_<Vec3T> &, const Mat_<T> &r_non_interp, Mat & normals_out) const
Vincent Rabaud's avatar
Vincent Rabaud committed
609 610
    {
      // Interpolate the radial image to make derivatives meaningful
611
      Mat_<T> r;
Vincent Rabaud's avatar
Vincent Rabaud committed
612
      // higher quality remapping does not help here
613
      remap(r_non_interp, r, xy_, fxy_, INTER_LINEAR);
Vincent Rabaud's avatar
Vincent Rabaud committed
614 615 616

      // Compute the derivatives with respect to theta and phi
      // TODO add bilateral filtering (as done in kinfu)
617 618
      Mat_<T> r_theta, r_phi;
      sepFilter2D(r, r_theta, r.depth(), kx_dx_, ky_dx_);
Vincent Rabaud's avatar
Vincent Rabaud committed
619 620
      //current OpenCV version sometimes corrupts r matrix after second call of sepFilter2D
      //it depends on resolution, be careful
621
      sepFilter2D(r, r_phi, r.depth(), kx_dy_, ky_dy_);
Vincent Rabaud's avatar
Vincent Rabaud committed
622 623

      // Fill the result matrix
624
      Mat_<Vec3T> normals(rows_, cols_);
Vincent Rabaud's avatar
Vincent Rabaud committed
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649

      const T* r_theta_ptr = r_theta[0], *r_theta_ptr_end = r_theta_ptr + rows_ * cols_;
      const T* r_phi_ptr = r_phi[0];
      const Mat33T * R = reinterpret_cast<const Mat33T *>(R_hat_[0]);
      const T* r_ptr = r[0];
      Vec3T * normal = normals[0];
      for (; r_theta_ptr != r_theta_ptr_end; ++r_theta_ptr, ++r_phi_ptr, ++R, ++r_ptr, ++normal)
      {
        if (cvIsNaN(*r_ptr))
        {
          (*normal)[0] = *r_ptr;
          (*normal)[1] = *r_ptr;
          (*normal)[2] = *r_ptr;
        }
        else
        {
          T r_theta_over_r = (*r_theta_ptr) / (*r_ptr);
          T r_phi_over_r = (*r_phi_ptr) / (*r_ptr);
          // R(1,1) is 0
          signNormal((*R)(0, 0) + (*R)(0, 1) * r_theta_over_r + (*R)(0, 2) * r_phi_over_r,
                     (*R)(1, 0) + (*R)(1, 2) * r_phi_over_r,
                     (*R)(2, 0) + (*R)(2, 1) * r_theta_over_r + (*R)(2, 2) * r_phi_over_r, *normal);
        }
      }

650
      remap(normals, normals_out, invxy_, invfxy_, INTER_LINEAR);
Vincent Rabaud's avatar
Vincent Rabaud committed
651 652 653 654 655 656 657
      normal = normals_out.ptr<Vec3T>(0);
      Vec3T * normal_end = normal + rows_ * cols_;
      for (; normal != normal_end; ++normal)
        signNormal((*normal)[0], (*normal)[1], (*normal)[2], *normal);
    }
  private:
    /** Stores R */
658
    Mat_<Vec9T> R_hat_;
Vincent Rabaud's avatar
Vincent Rabaud committed
659 660 661
    float phi_step_, theta_step_;

    /** Derivative kernels */
662
    Mat kx_dx_, ky_dx_, kx_dy_, ky_dy_;
Vincent Rabaud's avatar
Vincent Rabaud committed
663
    /** mapping function to get an SRI image */
664 665
    Mat_<Vec2f> map_;
    Mat xy_, fxy_;
Vincent Rabaud's avatar
Vincent Rabaud committed
666

667 668
    Mat_<Vec2f> euclideanMap_;
    Mat invxy_, invfxy_;
Vincent Rabaud's avatar
Vincent Rabaud committed
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 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 721 722 723 724 725 726 727 728 729 730 731
  };

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  /** Default constructor of the Algorithm class that computes normals
   */
  RgbdNormals::RgbdNormals(int rows, int cols, int depth, InputArray K_in, int window_size, int method_in)
      :
        rows_(rows),
        cols_(cols),
        depth_(depth),
        K_(K_in.getMat()),
        window_size_(window_size),
        method_(method_in),
        rgbd_normals_impl_(0)
  {
    CV_Assert(depth == CV_32F || depth == CV_64F);
    CV_Assert(K_.cols == 3 && K_.rows == 3);
  }

  // Just to remove a warning
  void delete_normals_impl(void *rgbd_normals_impl_, int method_, int depth);
  void delete_normals_impl(void *rgbd_normals_impl_, int method_, int depth)
  {
    if (rgbd_normals_impl_ == 0)
      return;
    switch (method_)
    {
      case RgbdNormals::RGBD_NORMALS_METHOD_LINEMOD:
      {
        if (depth == CV_32F)
          delete reinterpret_cast<const LINEMOD<float> *>(rgbd_normals_impl_);
        else
          delete reinterpret_cast<const LINEMOD<double> *>(rgbd_normals_impl_);
        break;
      }
      case RgbdNormals::RGBD_NORMALS_METHOD_SRI:
      {
        if (depth == CV_32F)
          delete reinterpret_cast<const SRI<float> *>(rgbd_normals_impl_);
        else
          delete reinterpret_cast<const SRI<double> *>(rgbd_normals_impl_);
        break;
      }
      case (RgbdNormals::RGBD_NORMALS_METHOD_FALS):
      {
        if (depth == CV_32F)
          delete reinterpret_cast<const FALS<float> *>(rgbd_normals_impl_);
        else
          delete reinterpret_cast<const FALS<double> *>(rgbd_normals_impl_);
        break;
      }
    }
  }

  /** Destructor
   */
  RgbdNormals::~RgbdNormals()
  {
    delete_normals_impl(rgbd_normals_impl_, method_, depth_);
  }

  void
732
  RgbdNormals::initialize_normals_impl(int rows, int cols, int depth, const Mat & K, int window_size,
Vincent Rabaud's avatar
Vincent Rabaud committed
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
                                       int method_in) const
  {
    CV_Assert(rows > 0 && cols > 0 && (depth == CV_32F || depth == CV_64F));
    CV_Assert(window_size == 1 || window_size == 3 || window_size == 5 || window_size == 7);
    CV_Assert(K_.cols == 3 && K.rows == 3 && (K.depth() == CV_32F || K.depth() == CV_64F));
    CV_Assert(
        method_in == RGBD_NORMALS_METHOD_FALS || method_in == RGBD_NORMALS_METHOD_LINEMOD
        || method_in == RGBD_NORMALS_METHOD_SRI);
    switch (method_in)
    {
      case (RGBD_NORMALS_METHOD_FALS):
      {
        if (depth == CV_32F)
          rgbd_normals_impl_ = new FALS<float>(rows, cols, window_size, depth, K, RGBD_NORMALS_METHOD_FALS);
        else
          rgbd_normals_impl_ = new FALS<double>(rows, cols, window_size, depth, K, RGBD_NORMALS_METHOD_FALS);
        break;
      }
      case (RGBD_NORMALS_METHOD_LINEMOD):
      {
        if (depth == CV_32F)
          rgbd_normals_impl_ = new LINEMOD<float>(rows, cols, window_size, depth, K, RGBD_NORMALS_METHOD_LINEMOD);
        else
          rgbd_normals_impl_ = new LINEMOD<double>(rows, cols, window_size, depth, K, RGBD_NORMALS_METHOD_LINEMOD);
        break;
      }
      case RGBD_NORMALS_METHOD_SRI:
      {
        if (depth == CV_32F)
          rgbd_normals_impl_ = new SRI<float>(rows, cols, window_size, depth, K, RGBD_NORMALS_METHOD_SRI);
        else
          rgbd_normals_impl_ = new SRI<double>(rows, cols, window_size, depth, K, RGBD_NORMALS_METHOD_SRI);
        break;
      }
    }

    reinterpret_cast<RgbdNormalsImpl *>(rgbd_normals_impl_)->cache();
  }

  /** Initializes some data that is cached for later computation
   * If that function is not called, it will be called the first time normals are computed
   */
  void
  RgbdNormals::initialize() const
  {
    if (rgbd_normals_impl_ == 0)
      initialize_normals_impl(rows_, cols_, depth_, K_, window_size_, method_);
    else if (!reinterpret_cast<RgbdNormalsImpl *>(rgbd_normals_impl_)->validate(rows_, cols_, depth_, K_, window_size_,
                                                                                method_)) {
      delete_normals_impl(rgbd_normals_impl_, method_, depth_);
      initialize_normals_impl(rows_, cols_, depth_, K_, window_size_, method_);
    }
  }

  /** Given a set of 3d points in a depth image, compute the normals at each point
   * @param points3d_in depth a float depth image. Or it can be rows x cols x 3 is they are 3d points
   * @param normals a rows x cols x 3 matrix
   */
  void
  RgbdNormals::operator()(InputArray points3d_in, OutputArray normals_out) const
  {
794
    Mat points3d_ori = points3d_in.getMat();
Vincent Rabaud's avatar
Vincent Rabaud committed
795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822

    CV_Assert(points3d_ori.dims == 2);
    // Either we have 3d points or a depth image
    switch (method_)
    {
      case (RGBD_NORMALS_METHOD_FALS):
      {
        CV_Assert(points3d_ori.channels() == 3);
        CV_Assert(points3d_ori.depth() == CV_32F || points3d_ori.depth() == CV_64F);
        break;
      }
      case RGBD_NORMALS_METHOD_LINEMOD:
      {
        CV_Assert(
            ((points3d_ori.channels() == 3) && (points3d_ori.depth() == CV_32F || points3d_ori.depth() == CV_64F)) || ((points3d_ori.channels() == 1) && (points3d_ori.depth() == CV_16U || points3d_ori.depth() == CV_32F || points3d_ori.depth() == CV_64F)));
        break;
      }
      case RGBD_NORMALS_METHOD_SRI:
      {
        CV_Assert( ((points3d_ori.channels() == 3) && (points3d_ori.depth() == CV_32F || points3d_ori.depth() == CV_64F)));
        break;
      }
    }

    // Initialize the pimpl
    initialize();

    // Precompute something for RGBD_NORMALS_METHOD_SRI and RGBD_NORMALS_METHOD_FALS
823
    Mat points3d, radius;
Vincent Rabaud's avatar
Vincent Rabaud committed
824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
    if ((method_ == RGBD_NORMALS_METHOD_SRI) || (method_ == RGBD_NORMALS_METHOD_FALS))
    {
      // Make the points have the right depth
      if (points3d_ori.depth() == depth_)
        points3d = points3d_ori;
      else
        points3d_ori.convertTo(points3d, depth_);

      // Compute the distance to the points
      if (depth_ == CV_32F)
        radius = computeRadius<float>(points3d);
      else
        radius = computeRadius<double>(points3d);
    }

    // Get the normals
    normals_out.create(points3d_ori.size(), CV_MAKETYPE(depth_, 3));
    if (points3d_in.empty())
      return;

844
    Mat normals = normals_out.getMat();
Vincent Rabaud's avatar
Vincent Rabaud committed
845 846 847 848 849 850 851 852 853 854 855 856 857
    switch (method_)
    {
      case (RGBD_NORMALS_METHOD_FALS):
      {
        if (depth_ == CV_32F)
          reinterpret_cast<const FALS<float> *>(rgbd_normals_impl_)->compute(points3d, radius, normals);
        else
          reinterpret_cast<const FALS<double> *>(rgbd_normals_impl_)->compute(points3d, radius, normals);
        break;
      }
      case RGBD_NORMALS_METHOD_LINEMOD:
      {
        // Only focus on the depth image for LINEMOD
858
        Mat depth;
Vincent Rabaud's avatar
Vincent Rabaud committed
859 860
        if (points3d_ori.channels() == 3)
        {
861 862
          std::vector<Mat> channels;
          split(points3d, channels);
Vincent Rabaud's avatar
Vincent Rabaud committed
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
          depth = channels[2];
        }
        else
          depth = points3d_ori;

        if (depth_ == CV_32F)
          reinterpret_cast<const LINEMOD<float> *>(rgbd_normals_impl_)->compute(depth, normals);
        else
          reinterpret_cast<const LINEMOD<double> *>(rgbd_normals_impl_)->compute(depth, normals);
        break;
      }
      case RGBD_NORMALS_METHOD_SRI:
      {
        if (depth_ == CV_32F)
          reinterpret_cast<const SRI<float> *>(rgbd_normals_impl_)->compute(points3d, radius, normals);
        else
          reinterpret_cast<const SRI<double> *>(rgbd_normals_impl_)->compute(points3d, radius, normals);
        break;
      }
    }
  }
}
885 886
}