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

View File

@@ -0,0 +1,140 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* robot_line_extraction — one fitted line segment.
*
* Author: DuongTD
* Derived from laser_line_extraction (Marc Gallant, BSD), stripped of ROS.
*********************************************************************/
#ifndef ROBOT_LINE_EXTRACTION_LINE_H_
#define ROBOT_LINE_EXTRACTION_LINE_H_
#include <array>
#include <vector>
#include <robot_line_extraction/types.h>
namespace robot_line_extraction
{
/**
* @class Line
* @brief A line in polar form (`angle`, `radius`) plus the endpoints and support that produced it.
*
* Polar rather than slope-intercept because a vertical line has no finite slope, and a laser sees
* vertical walls constantly. `radius` is the perpendicular distance from the sensor origin to the
* line and is kept non-negative; `angle` is the bearing of that perpendicular, in (-pi, pi].
*
* Two fits, used in sequence. @ref endpointFit is cheap and runs during splitting, where only a
* rough line is needed to measure how far points stray from it. @ref leastSqFit is the real fit,
* weighting each point by its own covariance, and it also produces the covariance that decides
* whether two lines are the same line.
*
* @note Holds copies of the scan data it was built from. That is deliberate: a segment outlives the
* split recursion that created it, and pointing back at a buffer being rebuilt each frame is
* how a use-after-free gets written.
*/
class Line
{
public:
/// @brief Build from a run of consecutive rays. Nothing is fitted yet.
Line(const CachedData& c_data, const RangeData& r_data, const LineExtractionParams& params,
std::vector<unsigned int> indices);
/// @brief Build from already-known parameters. Used when two lines merge into one.
Line(double angle, double radius, const std::array<double, 4>& covariance,
const std::array<double, 2>& start, const std::array<double, 2>& end,
const std::vector<unsigned int>& indices);
double getAngle() const
{
return angle_;
}
double getRadius() const
{
return radius_;
}
/// @brief Row-major 2x2 covariance of (radius, angle). Only meaningful after @ref leastSqFit.
const std::array<double, 4>& getCovariance() const
{
return covariance_;
}
const std::array<double, 2>& getStart() const
{
return start_;
}
const std::array<double, 2>& getEnd() const
{
return end_;
}
/// @brief Ray numbers supporting this line, ascending.
const std::vector<unsigned int>& getIndices() const
{
return indices_;
}
/// @brief [m] Perpendicular distance from ray @p index to this line.
double distToPoint(unsigned int index) const;
/// @brief [m] Distance between the endpoints.
double length() const;
std::size_t numPoints() const
{
return indices_.size();
}
/// @brief Cheap fit through the first and last supporting point. Used while splitting.
void endpointFit();
/**
* @brief Weighted least-squares fit, iterated to convergence, then the covariance.
*
* @return false if it did not converge within the iteration cap, leaving the endpoint fit in
* place. Upstream looped unbounded here; a scan that makes the increment oscillate then
* hangs the control thread outright, which is worse than a line that failed to refine.
*/
bool leastSqFit();
/// @brief Slide the endpoints onto the fitted line, perpendicular to it.
void projectEndpoints();
private:
void angleFromEndpoints();
void radiusFromEndpoints();
void angleFromLeastSq();
double angleIncrement() const;
void calcCovariance();
void calcPointCovariances();
void calcPointParameters();
void calcPointScalarCovariances();
void radiusFromLeastSq();
// Declaration order is destruction and initialisation order; keep it matching the member list of
// the constructors so -Wreorder stays quiet and the two never drift apart.
CachedData c_data_;
RangeData r_data_;
LineExtractionParams params_;
std::vector<unsigned int> indices_;
PointParams p_params_;
std::vector<double> point_scalar_vars_;
std::vector<std::array<double, 4>> point_covs_;
double p_rr_ = 0.0;
double angle_ = 0.0;
double radius_ = 0.0;
std::array<double, 2> start_{ { 0.0, 0.0 } };
std::array<double, 2> end_{ { 0.0, 0.0 } };
std::array<double, 4> covariance_{ { 0.0, 0.0, 0.0, 0.0 } };
};
} // namespace robot_line_extraction
#endif // ROBOT_LINE_EXTRACTION_LINE_H_

View File

@@ -0,0 +1,117 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* robot_line_extraction — split-and-merge line extraction from an ordered range scan.
*
* Author: DuongTD
* Derived from laser_line_extraction (Marc Gallant, BSD), stripped of ROS.
*********************************************************************/
#ifndef ROBOT_LINE_EXTRACTION_LINE_EXTRACTOR_H_
#define ROBOT_LINE_EXTRACTION_LINE_EXTRACTOR_H_
#include <string>
#include <vector>
#include <robot_line_extraction/line.h>
#include <robot_line_extraction/types.h>
namespace robot_line_extraction
{
/**
* @class LineExtractor
* @brief Turns one ordered range scan into line segments.
*
* Pure geometry. It knows nothing about ROS, TF, costmaps or message types — the input is a
* @ref ScanGeometry and a vector of ranges, which is what makes it testable against synthetic
* scans with no runtime around it.
*
* The method is split-and-merge: fit a rough line through a run of rays, split it where a point
* strays too far or a gap opens, refine each surviving run by weighted least squares, then merge
* neighbouring segments whose parameters agree within their own covariance.
*
* ## Why it needs the raw scan
*
* Fitting 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 why `robot_sensor_ports` keeps readings raw.
*
* ## Cost
*
* Splitting is recursive over the run and the least-squares step iterates per segment, so this is
* not free. Run it once per new scan, never once per control cycle — a 20 Hz loop reading a 15 Hz
* sensor would otherwise redo a quarter of its work on data it already processed. The bearing
* tables are rebuilt only when the geometry changes, so a steady sensor pays for them once.
*
* @note Not thread-safe. One extractor per consumer.
*/
class LineExtractor
{
public:
LineExtractor() = default;
/**
* @brief Set the parameters. Rejected here rather than per scan.
* @param[out] error Which field is wrong, and why.
* @return false if the parameters cannot produce a sensible fit; the previous set is kept.
*/
bool configure(const LineExtractionParams& params, std::string& error);
const LineExtractionParams& params() const
{
return params_;
}
/**
* @brief Extract lines from one scan.
*
* @param geometry Ray count and angular layout. The bearing tables are rebuilt only if this
* differs from the previous call.
* @param ranges [m] One entry per ray. Non-finite entries and entries outside
* [`min_range`, `max_range`] are dropped — NaN fails both comparisons, so a
* sensor reporting misses as NaN needs no special handling from the caller.
* @param[out] lines Cleared, then filled. Empty is a normal answer, not a failure.
* @param[out] error Why the scan could not be processed at all.
* @return false only when the input is unusable: geometry invalid, or `ranges.size()` disagreeing
* with `geometry.size`. A scan that simply contains no lines returns true and no lines.
*/
bool extract(const ScanGeometry& geometry, const std::vector<double>& ranges,
std::vector<Line>& lines, std::string& error);
private:
/// @brief Rebuild the bearing tables. Only called when the geometry actually changed.
void rebuildCache(const ScanGeometry& geometry);
/// @brief Cartesian form of every ray, in the sensor frame.
void projectRanges(const std::vector<double>& ranges);
void filterCloseAndFarPoints();
void filterOutlierPoints();
void filterLines();
void mergeLines();
/**
* @brief Split a run of rays until every piece is straight enough and has no gap in it.
*
* Iterative over an explicit stack rather than recursive: the depth is bounded only by the scan,
* and this runs in the control thread where a deep recursion on a noisy scan is a stack overflow
* rather than a slow frame.
*/
void split(const std::vector<unsigned int>& indices);
double distBetweenPoints(unsigned int index_1, unsigned int index_2) const;
LineExtractionParams params_;
ScanGeometry geometry_;
bool cache_valid_ = false;
CachedData c_data_;
RangeData r_data_;
std::vector<unsigned int> filtered_indices_;
std::vector<Line> lines_;
};
} // namespace robot_line_extraction
#endif // ROBOT_LINE_EXTRACTION_LINE_EXTRACTOR_H_

View File

@@ -0,0 +1,152 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* robot_line_extraction — parameters and the per-scan data the fit works on.
*
* Author: DuongTD
* Derived from laser_line_extraction (Marc Gallant, BSD), stripped of ROS.
*********************************************************************/
#ifndef ROBOT_LINE_EXTRACTION_TYPES_H_
#define ROBOT_LINE_EXTRACTION_TYPES_H_
#include <cmath>
#include <cstddef>
#include <string>
#include <vector>
namespace robot_line_extraction
{
/// @brief Wrap an angle into (-pi, pi]. Inline because it runs per point, per iteration.
inline double piToPi(double angle)
{
angle = std::fmod(angle, 2.0 * M_PI);
if (angle >= M_PI)
{
angle -= 2.0 * M_PI;
}
else if (angle < -M_PI)
{
angle += 2.0 * M_PI;
}
return angle;
}
/**
* @struct LineExtractionParams
* @brief Everything that steers the split-and-merge fit.
*
* Every field has a default here, a unit at its declaration, and a range checked by @ref validate.
* Nothing reads a parameter this struct has not vetted.
*/
struct LineExtractionParams
{
/// [rad^2] Variance of one bearing measurement. Feeds the per-point covariance.
double bearing_var = 1e-4;
/// [m^2] Variance of one range measurement.
double range_var = 9e-4;
/// [rad] Least-squares iteration stops when the angle moves less than this.
double least_sq_angle_thresh = 1e-4;
/// [m] Least-squares iteration stops when the radius moves less than this.
double least_sq_radius_thresh = 1e-4;
/// [m] A gap wider than this between consecutive points splits the run, however straight it is.
double max_line_gap = 0.05;
/// [m] Lines shorter than this are dropped.
double min_line_length = 0.05;
/// [m] Points nearer than this are ignored. Keep at or above the sensor's own range_min.
double min_range = 0.05;
/// [m] Points further than this are ignored.
double max_range = 30.0;
/// [m] A point further than this from the fitted line splits it. The core sensitivity knob.
double min_split_dist = 0.04;
/// [m] A point this far from both neighbours is treated as an outlier and dropped.
double outlier_dist = 0.05;
/// Fewer supporting points than this and the line is dropped. Below 3 a fit is meaningless.
unsigned int min_line_points = 6;
/**
* @brief Reject a parameter set that cannot produce a sensible fit.
* @param[out] error Which field, and why.
*
* Checked at configure time rather than per scan: a bad threshold otherwise shows up as "the
* detector finds nothing", which looks identical to a sensor fault.
*/
bool validate(std::string& error) const;
};
/**
* @struct ScanGeometry
* @brief The shape of a scan: how many rays, starting where, spaced how far apart.
*
* Separate from the ranges because it almost never changes while the ranges change every frame.
* The bearing tables depend only on this, so they are rebuilt only when it differs — computing a
* thousand sines per frame for a value that has not moved is pure waste in a control loop.
*/
struct ScanGeometry
{
double angle_min = 0.0; ///< [rad] Bearing of ray 0.
double angle_increment = 0.0; ///< [rad] Bearing step between consecutive rays. Must be non-zero.
std::size_t size = 0; ///< Number of rays.
bool operator==(const ScanGeometry& other) const;
bool operator!=(const ScanGeometry& other) const
{
return !(*this == other);
}
/// @brief Reject a geometry the fit cannot use.
bool validate(std::string& error) const;
};
/**
* @struct CachedData
* @brief Bearing tables for one @ref ScanGeometry.
*
* @warning `indices` is 0..size-1 and nothing else. @ref RangeData is indexed by ray number, so the
* identity mapping is what makes `xs[i]` the Cartesian form of ray `i`. The upstream code
* relies on this without saying so; break it and every lookup silently reads another ray.
*/
struct CachedData
{
std::vector<double> bearings; ///< [rad]
std::vector<double> cos_bearings;
std::vector<double> sin_bearings;
std::vector<unsigned int> indices;
};
/// @brief One frame of ranges, plus their Cartesian form in the sensor frame.
struct RangeData
{
std::vector<double> ranges; ///< [m]
std::vector<double> xs; ///< [m]
std::vector<double> ys; ///< [m]
};
/// @brief Scratch buffers of the least-squares iteration. Kept out of Line so they can be reused.
struct PointParams
{
std::vector<double> a;
std::vector<double> ap;
std::vector<double> app;
std::vector<double> b;
std::vector<double> bp;
std::vector<double> bpp;
std::vector<double> c;
std::vector<double> s;
};
} // namespace robot_line_extraction
#endif // ROBOT_LINE_EXTRACTION_TYPES_H_