Extract line segments from an ordered range scan

Fitting a line needs the ranges in ray order with a known angular step. A
costmap has neither: at 0.05 m with inflation it has already destroyed ray
order and object shape, so the two 0.2 m wings of a dock plate are one blob
there. This is the consumer that robot_sensor_ports keeps readings raw for.

Pure geometry - the input is a scan layout and a vector of ranges, the output
is segments in polar form with their endpoints, supporting rays and
covariance. Eigen is the only dependency and only the merge step uses it. No
robot_cpp, no costmap, no message types, which is what makes it testable
against synthetic scans with no runtime around it: build the shape, generate
the rays, and the answer is known in advance.

Polar rather than slope-intercept because a vertical wall has no finite slope
and a laser sees vertical walls constantly. Radius is kept non-negative so one
line has one representation - otherwise the merge step sees two.

Ported from laser_line_extraction (Marc Gallant, BSD) with the ROS layer
removed, and four defects fixed, each with a test that fails without the fix:

split() sliced with &indices[i_split - 1] and &indices.back(), dropping a point
off each half at every split. Anything angular came out a ray short at both
ends of every arm.

mergeLines() called resize() and then inserted at end(), leaving the first half
of the vector zero-filled. A merged line reported twice its real support and
every index in that half pointed at ray 0.

The least-squares loop had no iteration cap. The increment is a ratio of two
sums that can both approach zero on a degenerate run, and when it oscillates
the loop never exits - in a control thread that is a stopped robot, not a slow
frame. Segments that will not converge are now dropped, since their covariance
would be meaningless and the merge step decides by covariance.

Merging compared line parameters and nothing else, so two halves of a wall
either side of a doorway - perfectly collinear - were rejoined into one segment
spanning the doorway, undoing the split that had just separated them for that
exact reason. Merging now also requires the facing endpoints to be within
max_line_gap, so split and merge agree on what one surface means.

The corner point at a distance split now belongs to both halves. It is the last
point of one surface and the first of the next; giving it to one side shortens
the other arm by a ray and tilts its fit.

split() is iterative over an explicit stack rather than recursive: depth is
bounded only by the ray count, and a noisy scan that splits at nearly every
point would recurse a thousand deep in the control thread.

Parameters are validated at configure time rather than per scan. A threshold
that can never produce a fit otherwise shows up as "the detector finds
nothing", which is indistinguishable from a sensor fault.
This commit is contained in:
duongtd
2026-08-26 12:09:28 +07:00
commit 1d38e77afa
10 changed files with 2027 additions and 0 deletions

408
src/line_extractor.cpp Normal file
View File

@@ -0,0 +1,408 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* robot_line_extraction — split-and-merge over one ordered range scan.
*
* Author: DuongTD
* Derived from laser_line_extraction (Marc Gallant, BSD), stripped of ROS.
*********************************************************************/
#include <robot_line_extraction/line_extractor.h>
#include <algorithm>
#include <cmath>
#include <Eigen/Dense>
namespace robot_line_extraction
{
namespace
{
/// @brief Mahalanobis-style distance between two lines, given their covariances.
double chiSquared(const Eigen::Vector2d& dL, const Eigen::Matrix2d& P_1, const Eigen::Matrix2d& P_2)
{
return dL.transpose() * (P_1 + P_2).inverse() * dL;
}
/// Two segments merge when their parameters agree this closely relative to their own uncertainty.
/// 3 is roughly the 78% ellipse for two degrees of freedom: loose enough to rejoin one wall broken
/// by a passing reflection, tight enough to leave the two arms of a dock plate apart.
constexpr double kMergeChiSquaredThresh = 3.0;
Eigen::Matrix2d toMatrix(const std::array<double, 4>& covariance)
{
Eigen::Matrix2d P;
P << covariance[0], covariance[1], covariance[2], covariance[3];
return P;
}
} // namespace
bool LineExtractor::configure(const LineExtractionParams& params, std::string& error)
{
if (!params.validate(error))
{
return false; // Keep the previous set; a half-applied parameter block is worse than none.
}
params_ = params;
return true;
}
bool LineExtractor::extract(const ScanGeometry& geometry, const std::vector<double>& ranges,
std::vector<Line>& lines, std::string& error)
{
lines.clear();
if (!geometry.validate(error))
{
return false;
}
if (ranges.size() != geometry.size)
{
error = "ranges.size() (" + std::to_string(ranges.size()) + ") does not match geometry.size (" +
std::to_string(geometry.size) + ")";
return false;
}
// The bearing tables depend only on the layout, which a sensor repeats frame after frame.
// Recomputing a thousand sines every cycle for a constant is exactly the kind of waste a control
// loop cannot afford.
if (!cache_valid_ || geometry_ != geometry)
{
rebuildCache(geometry);
}
projectRanges(ranges);
filtered_indices_ = c_data_.indices;
lines_.clear();
filterCloseAndFarPoints();
filterOutlierPoints();
// Nothing left to fit is a normal answer — an empty room, or a sensor pointed at open space.
if (filtered_indices_.size() <= std::max<std::size_t>(params_.min_line_points, 3))
{
return true;
}
split(filtered_indices_);
filterLines();
// Refine every surviving run, dropping the ones that will not converge. A segment whose fit blew
// up carries a meaningless covariance, and the merge step decides by covariance.
std::vector<Line> refined;
refined.reserve(lines_.size());
for (Line& line : lines_)
{
if (line.leastSqFit())
{
refined.push_back(line);
}
}
lines_ = refined;
if (lines_.size() > 1)
{
mergeLines();
}
lines = lines_;
return true;
}
// ================================================================================================
// Per-scan preparation
// ================================================================================================
void LineExtractor::rebuildCache(const ScanGeometry& geometry)
{
geometry_ = geometry;
cache_valid_ = true;
const std::size_t n = geometry.size;
c_data_.bearings.resize(n);
c_data_.cos_bearings.resize(n);
c_data_.sin_bearings.resize(n);
c_data_.indices.resize(n);
for (std::size_t i = 0; i < n; ++i)
{
const double bearing = geometry.angle_min + static_cast<double>(i) * geometry.angle_increment;
c_data_.bearings[i] = bearing;
c_data_.cos_bearings[i] = std::cos(bearing);
c_data_.sin_bearings[i] = std::sin(bearing);
// Identity mapping, and everything downstream depends on it: RangeData is indexed by ray
// number, so xs[i] is only the Cartesian form of ray i while this holds.
c_data_.indices[i] = static_cast<unsigned int>(i);
}
}
void LineExtractor::projectRanges(const std::vector<double>& ranges)
{
r_data_.ranges = ranges;
r_data_.xs.resize(ranges.size());
r_data_.ys.resize(ranges.size());
for (std::size_t i = 0; i < ranges.size(); ++i)
{
r_data_.xs[i] = c_data_.cos_bearings[i] * ranges[i];
r_data_.ys[i] = c_data_.sin_bearings[i] * ranges[i];
}
}
double LineExtractor::distBetweenPoints(unsigned int index_1, unsigned int index_2) const
{
return std::hypot(r_data_.xs[index_1] - r_data_.xs[index_2],
r_data_.ys[index_1] - r_data_.ys[index_2]);
}
// ================================================================================================
// Point filtering
// ================================================================================================
void LineExtractor::filterCloseAndFarPoints()
{
std::vector<unsigned int> output;
output.reserve(filtered_indices_.size());
for (const unsigned int index : filtered_indices_)
{
const double range = r_data_.ranges[index];
// NaN fails both comparisons and is dropped here, which is why a sensor that reports misses as
// NaN needs no special case anywhere else. Infinity fails the upper bound the same way.
if (range >= params_.min_range && range <= params_.max_range)
{
output.push_back(index);
}
}
filtered_indices_ = output;
}
void LineExtractor::filterOutlierPoints()
{
if (filtered_indices_.size() < 3)
{
return;
}
std::vector<unsigned int> output;
output.reserve(filtered_indices_.size());
for (std::size_t i = 0; i < filtered_indices_.size(); ++i)
{
const unsigned int p_i = filtered_indices_[i];
unsigned int p_j = 0;
unsigned int p_k = 0;
if (i == 0)
{
p_j = filtered_indices_[i + 1];
p_k = filtered_indices_[i + 2];
}
else if (i == filtered_indices_.size() - 1)
{
p_j = filtered_indices_[i - 1];
p_k = filtered_indices_[i - 2];
}
else
{
p_j = filtered_indices_[i - 1];
p_k = filtered_indices_[i + 1];
}
if (std::fabs(r_data_.ranges[p_i] - r_data_.ranges[p_j]) > params_.outlier_dist &&
std::fabs(r_data_.ranges[p_i] - r_data_.ranges[p_k]) > params_.outlier_dist)
{
// Far from both neighbours in range. That is still not enough to call it an outlier: a real
// corner looks the same. Only drop it if it also sits off the line joining those neighbours.
Line line(c_data_, r_data_, params_, { p_j, p_k });
line.endpointFit();
if (line.distToPoint(p_i) > params_.min_split_dist)
{
continue;
}
}
output.push_back(p_i);
}
filtered_indices_ = output;
}
// ================================================================================================
// Splitting
// ================================================================================================
void LineExtractor::split(const std::vector<unsigned int>& indices)
{
// Explicit stack rather than recursion. Depth is bounded only by the ray count, and a noisy scan
// that splits at nearly every point would recurse a thousand deep in the control thread — a
// stack overflow, not a slow frame. Pushing the right half first keeps the output in scan order,
// which mergeLines depends on since it only ever compares neighbours.
std::vector<std::vector<unsigned int>> pending;
pending.push_back(indices);
while (!pending.empty())
{
const std::vector<unsigned int> run = std::move(pending.back());
pending.pop_back();
// A single point is not a line. It reaches here when a gap orphans it, and dropping it is the
// right answer rather than emitting a zero-length segment.
if (run.size() < 2)
{
continue;
}
Line line(c_data_, r_data_, params_, run);
line.endpointFit();
double dist_max = 0.0;
std::size_t i_dist = 0;
bool have_dist = false;
double gap_max = 0.0;
std::size_t i_gap = 0;
bool have_gap = false;
// Interior points only: the endpoints are on the fitted line by construction, so splitting at
// one of them would produce a one-point half and make no progress.
for (std::size_t i = 1; i + 1 < run.size(); ++i)
{
const double dist = line.distToPoint(run[i]);
if (dist > dist_max)
{
dist_max = dist;
i_dist = i;
have_dist = true;
}
}
for (std::size_t i = 0; i + 1 < run.size(); ++i)
{
const double gap = distBetweenPoints(run[i], run[i + 1]);
if (gap > gap_max)
{
gap_max = gap;
i_gap = i;
have_gap = true;
}
}
const bool split_on_dist = have_dist && dist_max >= params_.min_split_dist;
const bool split_on_gap = have_gap && gap_max >= params_.max_line_gap;
if (!split_on_dist && !split_on_gap)
{
lines_.push_back(line);
continue;
}
std::vector<unsigned int> first;
std::vector<unsigned int> second;
if (split_on_dist)
{
// The corner point belongs to BOTH halves. It is the last point of one wall and the first of
// the next, and a dock plate needs each arm to keep its apex endpoint — giving it to one side
// shortens the other arm by a ray and tilts its fit.
first.assign(run.begin(), run.begin() + static_cast<std::ptrdiff_t>(i_dist) + 1);
second.assign(run.begin() + static_cast<std::ptrdiff_t>(i_dist), run.end());
}
else
{
// A gap means the two sides are not the same surface, so nothing is shared across it.
first.assign(run.begin(), run.begin() + static_cast<std::ptrdiff_t>(i_gap) + 1);
second.assign(run.begin() + static_cast<std::ptrdiff_t>(i_gap) + 1, run.end());
}
// Both halves are strictly shorter than the run, so this always terminates. Upstream sliced
// with `&indices[i_split - 1]` and `&indices.back()`, which silently dropped a point off each
// half at every split — the arms of anything angular came out a ray short on both ends.
pending.push_back(std::move(second));
pending.push_back(std::move(first));
}
}
// ================================================================================================
// Line filtering and merging
// ================================================================================================
void LineExtractor::filterLines()
{
std::vector<Line> output;
output.reserve(lines_.size());
for (const Line& line : lines_)
{
if (line.length() >= params_.min_line_length && line.numPoints() >= params_.min_line_points)
{
output.push_back(line);
}
}
lines_ = output;
}
void LineExtractor::mergeLines()
{
std::vector<Line> merged_lines;
merged_lines.reserve(lines_.size());
for (std::size_t i = 1; i < lines_.size(); ++i)
{
const Eigen::Vector2d L_1(lines_[i - 1].getRadius(), lines_[i - 1].getAngle());
const Eigen::Vector2d L_2(lines_[i].getRadius(), lines_[i].getAngle());
const Eigen::Matrix2d P_1 = toMatrix(lines_[i - 1].getCovariance());
const Eigen::Matrix2d P_2 = toMatrix(lines_[i].getCovariance());
// Two conditions, and the second is not upstream's. Merging on line parameters alone rejoins
// anything collinear no matter how far apart, so a wall either side of a doorway comes back as
// one segment spanning the doorway — and split had already separated them for exactly that
// reason. Requiring the facing endpoints to be within max_line_gap makes split and merge agree
// on what "one surface" means, so a gap that forced a split cannot be undone here. It also
// stops a later consumer measuring a bridged segment: a dock detector checking wing length
// would otherwise accept one.
const double endpoint_gap = std::hypot(lines_[i].getStart()[0] - lines_[i - 1].getEnd()[0],
lines_[i].getStart()[1] - lines_[i - 1].getEnd()[1]);
if (endpoint_gap <= params_.max_line_gap &&
chiSquared(L_1 - L_2, P_1, P_2) < kMergeChiSquaredThresh)
{
const Eigen::Matrix2d P_m = (P_1.inverse() + P_2.inverse()).inverse();
const Eigen::Vector2d L_m = P_m * (P_1.inverse() * L_1 + P_2.inverse() * L_2);
const std::array<double, 4> cov{ { P_m(0, 0), P_m(0, 1), P_m(1, 0), P_m(1, 1) } };
// Concatenate the support of both. Upstream called resize() and then inserted at end(),
// which left the first half of the vector zero-filled and doubled numPoints() — a merged
// line then reported twice its real support, and every index in the first half read ray 0.
const std::vector<unsigned int>& ind_1 = lines_[i - 1].getIndices();
const std::vector<unsigned int>& ind_2 = lines_[i].getIndices();
std::vector<unsigned int> indices;
indices.reserve(ind_1.size() + ind_2.size());
indices.insert(indices.end(), ind_1.begin(), ind_1.end());
indices.insert(indices.end(), ind_2.begin(), ind_2.end());
Line merged_line(L_m[1], L_m[0], cov, lines_[i - 1].getStart(), lines_[i].getEnd(), indices);
merged_line.projectEndpoints();
lines_[i] = merged_line;
}
else
{
merged_lines.push_back(lines_[i - 1]);
}
if (i == lines_.size() - 1)
{
merged_lines.push_back(lines_[i]);
}
}
lines_ = merged_lines;
}
} // namespace robot_line_extraction