plane.cpp 19.2 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 36 37 38 39 40 41 42 43 44 45
/*
 * 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.
 *
 */

/** This is an implementation of a fast plane detection loosely inspired by
 * Fast Plane Detection and Polygonalization in noisy 3D Range Images
 * Jann Poppinga, Narunas Vaskevicius, Andreas Birk, and Kaustubh Pathak
 * and the follow-up
 * Fast Plane Detection for SLAM from Noisy Range Images in
 * Both Structured and Unstructured Environments
 * Junhao Xiao, Jianhua Zhang and Jianwei Zhang
 * Houxiang Zhang and Hans Petter Hildre
 */

46
#include "precomp.hpp"
Vincent Rabaud's avatar
Vincent Rabaud committed
47

48 49 50 51
namespace cv
{
namespace rgbd
{
Vincent Rabaud's avatar
Vincent Rabaud committed
52 53 54 55
/** Structure defining a plane. The notations are from the second paper */
class PlaneBase
{
public:
56
  PlaneBase(const Vec3f & m, const Vec3f &n_in, int index)
Vincent Rabaud's avatar
Vincent Rabaud committed
57 58 59
      :
        index_(index),
        n_(n_in),
60
        m_sum_(Vec3f(0, 0, 0)),
Vincent Rabaud's avatar
Vincent Rabaud committed
61
        m_(m),
62
        Q_(Matx33f::zeros()),
Vincent Rabaud's avatar
Vincent Rabaud committed
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
        mse_(0),
        K_(0)
  {
    UpdateD();
  }

  virtual
  ~PlaneBase()
  {
  }

  /** Compute the distance to the plane. This will be implemented by the children to take into account different
   * sensor models
   * @param p_j
   * @return
   */
  virtual
  float
81
  distance(const Vec3f& p_j) const = 0;
Vincent Rabaud's avatar
Vincent Rabaud committed
82 83 84 85 86 87 88 89 90 91 92 93 94

  /** The d coefficient in the plane equation ax+by+cz+d = 0
   * @return
   */
  inline float
  d() const
  {
    return d_;
  }

  /** The normal to the plane
   * @return the normal to the plane
   */
95
  const Vec3f &
Vincent Rabaud's avatar
Vincent Rabaud committed
96 97 98 99 100 101 102 103 104 105 106 107 108 109
  n() const
  {
    return n_;
  }

  /** Update the different coefficients of the plane, based on the new statistics
   */
  void
  UpdateParameters()
  {
    if (empty())
      return;
    m_ = m_sum_ / K_;
    // Compute C
110
    Matx33f C = Q_ - m_sum_ * m_.t();
Vincent Rabaud's avatar
Vincent Rabaud committed
111 112

    // Compute n
113 114
    SVD svd(C);
    n_ = Vec3f(svd.vt.at<float>(2, 0), svd.vt.at<float>(2, 1), svd.vt.at<float>(2, 2));
Vincent Rabaud's avatar
Vincent Rabaud committed
115 116 117 118 119 120 121 122
    mse_ = svd.w.at<float>(2) / K_;

    UpdateD();
  }

  /** Update the different sum of point and sum of point*point.t()
   */
  void
123
  UpdateStatistics(const Vec3f & point, const Matx33f & Q_local)
Vincent Rabaud's avatar
Vincent Rabaud committed
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
  {
    m_sum_ += point;
    Q_ += Q_local;
    ++K_;
  }

  inline size_t
  empty() const
  {
    return K_ == 0;
  }

  inline int
  K() const
  {
    return K_;
  }
/** The index of the plane */
  int index_;
protected:
  /** The 4th coefficient in the plane equation ax+by+cz+d = 0 */
  float d_;
  /** Normal of the plane */
147
  Vec3f n_;
Vincent Rabaud's avatar
Vincent Rabaud committed
148 149 150 151 152 153 154
private:
  inline void
  UpdateD()
  {
    d_ = -m_.dot(n_);
  }
  /** The sum of the points */
155
  Vec3f m_sum_;
Vincent Rabaud's avatar
Vincent Rabaud committed
156
  /** The mean of the points */
157
  Vec3f m_;
Vincent Rabaud's avatar
Vincent Rabaud committed
158
  /** The sum of pi * pi^\top */
159
  Matx33f Q_;
Vincent Rabaud's avatar
Vincent Rabaud committed
160
  /** The different matrices we need to update */
161
  Matx33f C_;
Vincent Rabaud's avatar
Vincent Rabaud committed
162 163 164 165 166 167 168 169 170 171 172 173
  float mse_;
  /** the number of points that form the plane */
  int K_;
};

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

/** Basic planar child, with no sensor error model
 */
class Plane: public PlaneBase
{
public:
174
  Plane(const Vec3f & m, const Vec3f &n_in, int index)
Vincent Rabaud's avatar
Vincent Rabaud committed
175 176 177 178 179 180 181 182 183 184
      :
        PlaneBase(m, n_in, index)
  {
  }

  /** The computed distance is perfect in that case
   * @param p_j the point to compute its distance to
   * @return
   */
  float
185
  distance(const Vec3f& p_j) const CV_OVERRIDE
Vincent Rabaud's avatar
Vincent Rabaud committed
186 187 188 189 190 191 192 193 194 195
  {
    return std::abs(float(p_j.dot(n_) + d_));
  }
};

/** Planar child with a quadratic error model
 */
class PlaneABC: public PlaneBase
{
public:
196
  PlaneABC(const Vec3f & m, const Vec3f &n_in, int index, float sensor_error_a, float sensor_error_b,
Vincent Rabaud's avatar
Vincent Rabaud committed
197 198 199 200 201 202 203 204 205 206 207 208
           float sensor_error_c)
      :
        PlaneBase(m, n_in, index),
        sensor_error_a_(sensor_error_a),
        sensor_error_b_(sensor_error_b),
        sensor_error_c_(sensor_error_c)
  {
  }

  /** The distance is now computed by taking the sensor error into account */
  inline
  float
209
  distance(const Vec3f& p_j) const CV_OVERRIDE
Vincent Rabaud's avatar
Vincent Rabaud committed
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
  {
    float cst = p_j.dot(n_) + d_;
    float err = sensor_error_a_ * p_j[2] * p_j[2] + sensor_error_b_ * p_j[2] + sensor_error_c_;
    if (((cst - n_[2] * err <= 0) && (cst + n_[2] * err >= 0)) || ((cst + n_[2] * err <= 0) && (cst - n_[2] * err >= 0)))
      return 0;
    return std::min(std::abs(cst - err), std::abs(cst + err));
  }
private:
  float sensor_error_a_;
  float sensor_error_b_;
  float sensor_error_c_;
};

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

/** The PlaneGrid contains statistic about the individual tiles
 */
class PlaneGrid
{
public:
230
  PlaneGrid(const Mat_<Vec3f> & points3d, int block_size)
Vincent Rabaud's avatar
Vincent Rabaud committed
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
      :
        block_size_(block_size)
  {
    // Figure out some dimensions
    int mini_rows = points3d.rows / block_size;
    if (points3d.rows % block_size != 0)
      ++mini_rows;

    int mini_cols = points3d.cols / block_size;
    if (points3d.cols % block_size != 0)
      ++mini_cols;

    // Compute all the interesting quantities
    m_.create(mini_rows, mini_cols);
    n_.create(mini_rows, mini_cols);
    Q_.create(points3d.rows, points3d.cols);
    mse_.create(mini_rows, mini_cols);
    for (int y = 0; y < mini_rows; ++y)
      for (int x = 0; x < mini_cols; ++x)
      {
        // Update the tiles
252 253
        Matx33f Q = Matx33f::zeros();
        Vec3f m = Vec3f(0, 0, 0);
Vincent Rabaud's avatar
Vincent Rabaud committed
254 255 256
        int K = 0;
        for (int j = y * block_size; j < std::min((y + 1) * block_size, points3d.rows); ++j)
        {
257 258
          const Vec3f * vec = points3d.ptr < Vec3f > (j, x * block_size), *vec_end;
          float * pointpointt = reinterpret_cast<float*>(Q_.ptr < Vec<float, 9> > (j, x * block_size));
Vincent Rabaud's avatar
Vincent Rabaud committed
259
          if (x == mini_cols - 1)
260
            vec_end = points3d.ptr < Vec3f > (j, points3d.cols - 1) + 1;
Vincent Rabaud's avatar
Vincent Rabaud committed
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
          else
            vec_end = vec + block_size;
          for (; vec != vec_end; ++vec, pointpointt += 9)
          {
            if (cvIsNaN(vec->val[0]))
              continue;
            // Fill point*point.t()
            *pointpointt = vec->val[0] * vec->val[0];
            *(pointpointt + 1) = vec->val[0] * vec->val[1];
            *(pointpointt + 2) = vec->val[0] * vec->val[2];
            *(pointpointt + 3) = *(pointpointt + 1);
            *(pointpointt + 4) = vec->val[1] * vec->val[1];
            *(pointpointt + 5) = vec->val[1] * vec->val[2];
            *(pointpointt + 6) = *(pointpointt + 2);
            *(pointpointt + 7) = *(pointpointt + 5);
            *(pointpointt + 8) = vec->val[2] * vec->val[2];

278
            Q += *reinterpret_cast<Matx33f*>(pointpointt);
Vincent Rabaud's avatar
Vincent Rabaud committed
279 280 281 282 283 284 285 286 287 288 289 290 291 292
            m += (*vec);
            ++K;
          }
        }
        if (K == 0)
        {
          mse_(y, x) = std::numeric_limits<float>::max();
          continue;
        }

        m /= K;
        m_(y, x) = m;

        // Compute C
293
        Matx33f C = Q - K * m * m.t();
Vincent Rabaud's avatar
Vincent Rabaud committed
294 295

        // Compute n
296 297
        SVD svd(C);
        n_(y, x) = Vec3f(svd.vt.at<float>(2, 0), svd.vt.at<float>(2, 1), svd.vt.at<float>(2, 2));
Vincent Rabaud's avatar
Vincent Rabaud committed
298 299 300 301 302 303
        mse_(y, x) = svd.w.at<float>(2) / K;
      }
  }

  /** The size of the block */
  int block_size_;
304 305 306 307
  Mat_<Vec3f> m_;
  Mat_<Vec3f> n_;
  Mat_<Vec<float, 9> > Q_;
  Mat_<float> mse_;
Vincent Rabaud's avatar
Vincent Rabaud committed
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
};

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

class TileQueue
{
public:
  struct PlaneTile
  {
    PlaneTile(int x, int y, float mse)
        :
          x_(x),
          y_(y),
          mse_(mse)
    {
    }

    bool
    operator<(const PlaneTile &tile2) const
    {
      return mse_ < tile2.mse_;
    }

    int x_;
    int y_;
    float mse_;
  };

  TileQueue(const PlaneGrid &plane_grid)
  {
338
    done_tiles_ = Mat_<unsigned char>::zeros(plane_grid.mse_.rows, plane_grid.mse_.cols);
Vincent Rabaud's avatar
Vincent Rabaud committed
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
    tiles_.clear();
    for (int y = 0; y < plane_grid.mse_.rows; ++y)
      for (int x = 0; x < plane_grid.mse_.cols; ++x)
        if (plane_grid.mse_(y, x) != std::numeric_limits<float>::max())
          // Update the tiles
          tiles_.push_back(PlaneTile(x, y, plane_grid.mse_(y, x)));
    // Sort tiles by MSE
    tiles_.sort();
  }

  bool
  empty()
  {
    while (!tiles_.empty())
    {
      const PlaneTile & tile = tiles_.front();
      if (done_tiles_(tile.y_, tile.x_))
        tiles_.pop_front();
      else
        break;
    }
    return tiles_.empty();
  }

  const PlaneTile &
  front() const
  {
    return tiles_.front();
  }

  void
  remove(int y, int x)
  {
    done_tiles_(y, x) = 1;
  }
private:
  /** The list of tiles ordered from most planar to least */
  std::list<PlaneTile> tiles_;
  /** contains 1 when the tiles has been studied, 0 otherwise */
378
  Mat_<unsigned char> done_tiles_;
Vincent Rabaud's avatar
Vincent Rabaud committed
379 380 381 382 383 384 385
};

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

class InlierFinder
{
public:
386
  InlierFinder(float err, const Mat_<Vec3f> & points3d, const Mat_<Vec3f> & normals,
Vincent Rabaud's avatar
Vincent Rabaud committed
387 388 389 390 391 392 393 394 395 396 397
               unsigned char plane_index, int block_size)
      :
        err_(err),
        points3d_(points3d),
        normals_(normals),
        plane_index_(plane_index),
        block_size_(block_size)
  {
  }

  void
398 399 400
  Find(const PlaneGrid &plane_grid, Ptr<PlaneBase> & plane, TileQueue & tile_queue,
       std::set<TileQueue::PlaneTile> & neighboring_tiles, Mat_<unsigned char> & overall_mask,
       Mat_<unsigned char> & plane_mask)
Vincent Rabaud's avatar
Vincent Rabaud committed
401 402 403 404 405
  {
    // Do not use reference as we pop the from later on
    TileQueue::PlaneTile tile = *(neighboring_tiles.begin());

    // Figure the part of the image to look at
406
    Range range_x, range_y;
Vincent Rabaud's avatar
Vincent Rabaud committed
407 408 409
    int x = tile.x_ * block_size_, y = tile.y_ * block_size_;

    if (tile.x_ == plane_mask.cols - 1)
410
      range_x = Range(x, overall_mask.cols);
Vincent Rabaud's avatar
Vincent Rabaud committed
411
    else
412
      range_x = Range(x, x + block_size_);
Vincent Rabaud's avatar
Vincent Rabaud committed
413 414

    if (tile.y_ == plane_mask.rows - 1)
415
      range_y = Range(y, overall_mask.rows);
Vincent Rabaud's avatar
Vincent Rabaud committed
416
    else
417
      range_y = Range(y, y + block_size_);
Vincent Rabaud's avatar
Vincent Rabaud committed
418 419 420 421 422

    int n_valid_points = 0;
    for (int yy = range_y.start; yy != range_y.end; ++yy)
    {
      uchar* data = overall_mask.ptr(yy, range_x.start), *data_end = data + range_x.size();
423 424
      const Vec3f* point = points3d_.ptr < Vec3f > (yy, range_x.start);
      const Matx33f* Q_local = reinterpret_cast<const Matx33f *>(plane_grid.Q_.ptr < Vec<float, 9>
Vincent Rabaud's avatar
Vincent Rabaud committed
425 426 427 428 429
          > (yy, range_x.start));

      // Depending on whether you have a normal, check it
      if (!normals_.empty())
      {
430
        const Vec3f* normal = normals_.ptr < Vec3f > (yy, range_x.start);
Vincent Rabaud's avatar
Vincent Rabaud committed
431 432 433 434 435 436 437 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 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 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
        for (; data != data_end; ++data, ++point, ++normal, ++Q_local)
        {
          // Don't do anything if the point already belongs to another plane
          if (cvIsNaN(point->val[0]) || ((*data) != 255))
            continue;

          // If the point is close enough to the plane
          if (plane->distance(*point) < err_)
          {
            // make sure the normals are similar to the plane
            if (std::abs(plane->n().dot(*normal)) > 0.3)
            {
              // The point now belongs to the plane
              plane->UpdateStatistics(*point, *Q_local);
              *data = plane_index_;
              ++n_valid_points;
            }
          }
        }
      }
      else
      {
        for (; data != data_end; ++data, ++point, ++Q_local)
        {
          // Don't do anything if the point already belongs to another plane
          if (cvIsNaN(point->val[0]) || ((*data) != 255))
            continue;

          // If the point is close enough to the plane
          if (plane->distance(*point) < err_)
          {
            // The point now belongs to the plane
            plane->UpdateStatistics(*point, *Q_local);
            *data = plane_index_;
            ++n_valid_points;
          }
        }
      }
    }

    plane->UpdateParameters();

    // Mark the front as being done and pop it
    if (n_valid_points > (range_x.size() * range_y.size()) / 2)
      tile_queue.remove(tile.y_, tile.x_);
    plane_mask(tile.y_, tile.x_) = 1;
    neighboring_tiles.erase(neighboring_tiles.begin());

    // Add potential neighbors of the tile
    std::vector<std::pair<int, int> > pairs;
    if (tile.x_ > 0)
      for (unsigned char * val = overall_mask.ptr<unsigned char>(range_y.start, range_x.start), *val_end = val
          + range_y.size() * overall_mask.step; val != val_end; val += overall_mask.step)
        if (*val == plane_index_)
        {
          pairs.push_back(std::pair<int, int>(tile.x_ - 1, tile.y_));
          break;
        }
    if (tile.x_ < plane_mask.cols - 1)
      for (unsigned char * val = overall_mask.ptr<unsigned char>(range_y.start, range_x.end - 1), *val_end = val
          + range_y.size() * overall_mask.step; val != val_end; val += overall_mask.step)
        if (*val == plane_index_)
        {
          pairs.push_back(std::pair<int, int>(tile.x_ + 1, tile.y_));
          break;
        }
    if (tile.y_ > 0)
      for (unsigned char * val = overall_mask.ptr<unsigned char>(range_y.start, range_x.start), *val_end = val
          + range_x.size(); val != val_end; ++val)
        if (*val == plane_index_)
        {
          pairs.push_back(std::pair<int, int>(tile.x_, tile.y_ - 1));
          break;
        }
    if (tile.y_ < plane_mask.rows - 1)
      for (unsigned char * val = overall_mask.ptr<unsigned char>(range_y.end - 1, range_x.start), *val_end = val
          + range_x.size(); val != val_end; ++val)
        if (*val == plane_index_)
        {
          pairs.push_back(std::pair<int, int>(tile.x_, tile.y_ + 1));
          break;
        }

    for (unsigned char i = 0; i < pairs.size(); ++i)
      if (!plane_mask(pairs[i].second, pairs[i].first))
        neighboring_tiles.insert(
            TileQueue::PlaneTile(pairs[i].first, pairs[i].second, plane_grid.mse_(pairs[i].second, pairs[i].first)));
  }

private:
  float err_;
522 523
  const Mat_<Vec3f> & points3d_;
  const Mat_<Vec3f> & normals_;
Vincent Rabaud's avatar
Vincent Rabaud committed
524 525 526
  unsigned char plane_index_;
  /** THe block size as defined in the main algorithm */
  int block_size_;
527

Ilya Lavrenov's avatar
Ilya Lavrenov committed
528
  const InlierFinder & operator = (const InlierFinder &);
529
};
Vincent Rabaud's avatar
Vincent Rabaud committed
530 531 532 533 534 535

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

  void
  RgbdPlane::operator()(InputArray points3d_in, OutputArray mask_out, OutputArray plane_coefficients)
  {
536
    this->operator()(points3d_in, Mat(), mask_out, plane_coefficients);
Vincent Rabaud's avatar
Vincent Rabaud committed
537 538 539 540 541 542
  }

  void
  RgbdPlane::operator()(InputArray points3d_in, InputArray normals_in, OutputArray mask_out,
                        OutputArray plane_coefficients_out)
  {
543
    Mat_<Vec3f> points3d, normals;
Vincent Rabaud's avatar
Vincent Rabaud committed
544 545 546 547 548 549 550 551 552 553 554 555 556 557
    if (points3d_in.depth() == CV_32F)
      points3d = points3d_in.getMat();
    else
      points3d_in.getMat().convertTo(points3d, CV_32F);
    if (!normals_in.empty())
    {
      if (normals_in.depth() == CV_32F)
        normals = normals_in.getMat();
      else
        normals_in.getMat().convertTo(normals, CV_32F);
    }

    // Pre-computations
    mask_out.create(points3d.size(), CV_8U);
558 559
    Mat mask_out_mat = mask_out.getMat();
    Mat_<unsigned char> mask_out_uc = (Mat_<unsigned char>&) mask_out_mat;
Vincent Rabaud's avatar
Vincent Rabaud committed
560 561 562 563 564
    mask_out_uc.setTo(255);
    PlaneGrid plane_grid(points3d, block_size_);
    TileQueue plane_queue(plane_grid);
    size_t index_plane = 0;

565
    std::vector<Vec4f> plane_coefficients;
Ilya Lavrenov's avatar
Ilya Lavrenov committed
566
    float mse_min = (float)(threshold_ * threshold_);
Vincent Rabaud's avatar
Vincent Rabaud committed
567 568 569 570 571 572 573 574

    while (!plane_queue.empty())
    {
      // Get the first tile if it's good enough
      const TileQueue::PlaneTile front_tile = plane_queue.front();
      if (front_tile.mse_ > mse_min)
        break;

Ilya Lavrenov's avatar
Ilya Lavrenov committed
575
      InlierFinder inlier_finder((float)threshold_, points3d, normals, (unsigned char)index_plane, block_size_);
Vincent Rabaud's avatar
Vincent Rabaud committed
576 577 578

      // Construct the plane for the first tile
      int x = front_tile.x_, y = front_tile.y_;
579 580
      const Vec3f & n = plane_grid.n_(y, x);
      Ptr<PlaneBase> plane;
Vincent Rabaud's avatar
Vincent Rabaud committed
581
      if ((sensor_error_a_ == 0) && (sensor_error_b_ == 0) && (sensor_error_c_ == 0))
582
        plane = Ptr<PlaneBase>(new Plane(plane_grid.m_(y, x), n, (int)index_plane));
Vincent Rabaud's avatar
Vincent Rabaud committed
583
      else
584
        plane = Ptr<PlaneBase>(new PlaneABC(plane_grid.m_(y, x), n, (int)index_plane,
Ilya Lavrenov's avatar
Ilya Lavrenov committed
585
			(float)sensor_error_a_, (float)sensor_error_b_, (float)sensor_error_c_));
Vincent Rabaud's avatar
Vincent Rabaud committed
586

587
      Mat_<unsigned char> plane_mask = Mat_<unsigned char>::zeros(points3d.rows / block_size_,
Vincent Rabaud's avatar
Vincent Rabaud committed
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
                                                                          points3d.cols / block_size_);
      std::set<TileQueue::PlaneTile> neighboring_tiles;
      neighboring_tiles.insert(front_tile);
      plane_queue.remove(front_tile.y_, front_tile.x_);

      // Process all the neighboring tiles
      while (!neighboring_tiles.empty())
        inlier_finder.Find(plane_grid, plane, plane_queue, neighboring_tiles, mask_out_uc, plane_mask);

      // Don't record the plane if it's empty
      if (plane->empty())
        continue;
      // Don't record the plane if it's smaller than asked
      if (plane->K() < min_size_) {
        // Reset the plane index in the mask
        for (y = 0; y < plane_mask.rows; ++y)
          for (x = 0; x < plane_mask.cols; ++x) {
            if (!plane_mask(y, x))
              continue;
            // Go over the tile
            for (int yy = y * block_size_;
                yy < std::min((y + 1) * block_size_, mask_out_uc.rows); ++yy) {
              uchar* data = mask_out_uc.ptr(yy, x * block_size_);
              uchar* data_end = data
                  + std::min(block_size_,
                      mask_out_uc.cols - x * block_size_);
              for (; data != data_end; ++data) {
                if (*data == index_plane)
                  *data = 255;
              }
            }
          }
        continue;
      }

      ++index_plane;
      if (index_plane >= 255)
        break;
626
      Vec4f coeffs(plane->n()[0], plane->n()[1], plane->n()[2], plane->d());
Vincent Rabaud's avatar
Vincent Rabaud committed
627 628 629 630 631 632 633 634
      if (coeffs(2) > 0)
        coeffs = -coeffs;
      plane_coefficients.push_back(coeffs);
    };

    // Fill the plane coefficients
    if (plane_coefficients.empty())
      return;
Ilya Lavrenov's avatar
Ilya Lavrenov committed
635
    plane_coefficients_out.create((int)plane_coefficients.size(), 1, CV_32FC4);
636
    Mat plane_coefficients_mat = plane_coefficients_out.getMat();
Vincent Rabaud's avatar
Vincent Rabaud committed
637 638 639 640 641 642
    float* data = plane_coefficients_mat.ptr<float>(0);
    for(size_t i=0; i<plane_coefficients.size(); ++i)
      for(uchar j=0; j<4; ++j, ++data)
        *data = plane_coefficients[i][j];
  }
}
643
}