feat(depth_layer): add occlusion_guard and attach_distance

occlusion_guard (default false): keep a stored point when a nearer object blocks the ray to it, clear a point the camera sees through. attach_distance (default 0.12 m, as before) is now read per source. Both keys are forwarded from the parent costmap parameters. README, params YAML and tests updated.
This commit is contained in:
2026-10-27 13:09:31 +07:00
parent 9b93a45b45
commit 757b381659
6 changed files with 447 additions and 24 deletions

View File

@@ -66,13 +66,26 @@ namespace robot_costmap_2d
{
namespace
{
// Distance of the "attach" band around each frustum face, hard-coded in the source [m].
constexpr float kAttachDistance = 0.12f;
// Stored columns farther than this from the robot are not tested for clearing [m].
constexpr double kClearingSkipDistance = 10.0;
// VoxelGrid leaf of the combined observation, hard-coded in the source [m].
constexpr float kObservationLeaf = 0.05f;
// Occlusion guard. The values were checked on 10 KIT robot bags (22-23/10/2026) with an offline
// replay of this layer; change them only with a new replay.
// Ray bin in tangent units: 0.01 is ~0.57 deg, ~1.7 px of the D410 at fx = 300.
constexpr float kRangeBin = 0.01f;
// Returns and stored points closer than this along the viewing axis carry no evidence [m].
constexpr float kRangeMinDepth = 0.1f;
// Depth noise band around a stored point at range r: kRangeMargin + kRangeMarginPerSqM * r^2 [m].
// Stereo depth error grows with r^2.
constexpr float kRangeMargin = 0.05f;
constexpr float kRangeMarginPerSqM = 0.02f;
// Of the 3 x 3 bins around the ray: this many nearer bins hide the point...
constexpr int kOccludingBins = 2;
// ...and this many farther bins, the centre one among them, show that the camera sees past it.
constexpr int kSeeThroughBins = 6;
Eigen::Isometry3d toIsometry(const tf3::TransformStampedMsg& t)
{
const auto& q = t.transform.rotation;
@@ -95,9 +108,10 @@ void requireRange(bool ok, const std::string& what)
// ---------------------------------------------------------------------------------------------
void DepthCameraFrustum::build(const Eigen::Isometry3d& T_global_sensor, double fov_w, double fov_v,
double min_d, double max_d, bool optical)
double min_d, double max_d, bool optical, double attach_d)
{
max_detect_distance = max_d;
attach_distance = static_cast<float>(attach_d);
const double tw = std::tan(fov_w / 2.0);
const double tv = std::tan(fov_v / 2.0);
// findFrustumVertex(): X forward, +Y left, +Z up. TL = +Y +Z, BR = -Y -Z.
@@ -164,7 +178,7 @@ bool DepthCameraFrustum::nearFace(const Eigen::Vector3f& p) const
{
const float dis = std::fabs(pl[0] * p.x() + pl[1] * p.y() + pl[2] * p.z() + pl[3]) /
std::sqrt(pl[0] * pl[0] + pl[1] * pl[1] + pl[2] * pl[2]);
if (dis <= kAttachDistance &&
if (dis <= attach_distance &&
std::hypot(p.x() - origin.x(), p.y() - origin.y()) < max_detect_distance + 0.5)
return true;
}
@@ -194,6 +208,84 @@ bool attachedToFrustums(const std::vector<DepthCameraFrustum>& frustums, const E
return false;
}
// ---------------------------------------------------------------------------------------------
// Range image (occlusion guard, an addition of this port)
// ---------------------------------------------------------------------------------------------
void DepthCameraRangeImage::reset(const Eigen::Isometry3d& T_global_sensor, double fov_w, double fov_v,
bool optical)
{
sensor_from_global_ = T_global_sensor.inverse().cast<float>();
optical_ = optical;
// One spare bin on each side: a ray on the frustum edge still has all its 3 x 3 neighbours.
half_u_ = static_cast<int>(std::ceil(std::tan(fov_w / 2.0) / kRangeBin)) + 1;
half_v_ = static_cast<int>(std::ceil(std::tan(fov_v / 2.0) / kRangeBin)) + 1;
min_range_.assign(static_cast<std::size_t>(2 * half_u_ + 1) * static_cast<std::size_t>(2 * half_v_ + 1),
std::numeric_limits<float>::infinity());
}
Eigen::Vector3f DepthCameraRangeImage::toOptical(const Eigen::Vector3f& p) const
{
// Same axes as DepthCameraFrustum::build: camera_link X forward, Y left, Z up.
return optical_ ? p : Eigen::Vector3f(-p.y(), -p.z(), p.x());
}
bool DepthCameraRangeImage::bin(const Eigen::Vector3f& q, int& u, int& v) const
{
if (min_range_.empty() || !(q.z() > kRangeMinDepth))
return false;
const float fu = q.x() / q.z() / kRangeBin;
const float fv = q.y() / q.z() / kRangeBin;
if (!(std::fabs(fu) <= half_u_ + 0.5f) || !(std::fabs(fv) <= half_v_ + 0.5f))
return false;
u = static_cast<int>(std::lround(fu));
v = static_cast<int>(std::lround(fv));
return std::abs(u) <= half_u_ && std::abs(v) <= half_v_;
}
void DepthCameraRangeImage::addSensorPoint(const Eigen::Vector3f& p)
{
const Eigen::Vector3f q = toOptical(p);
int u, v;
if (!bin(q, u, v))
return;
float& slot = min_range_[index(u, v)];
slot = std::min(slot, q.norm());
}
DepthCameraRangeImage::Evidence DepthCameraRangeImage::test(const Eigen::Vector3f& p_global) const
{
const Eigen::Vector3f q = toOptical(sensor_from_global_ * p_global);
int u, v;
if (!bin(q, u, v))
return Evidence::kNone;
const float r = q.norm();
const float margin = kRangeMargin + kRangeMarginPerSqM * r * r;
int nearer = 0, farther = 0;
for (int du = -1; du <= 1; ++du)
{
for (int dv = -1; dv <= 1; ++dv)
{
const int a = u + du, b = v + dv;
if (std::abs(a) > half_u_ || std::abs(b) > half_v_)
continue;
// Only the nearest return of a bin counts: a bin that grazes the floor spans tens of
// centimetres of range, so its farthest return says nothing. +inf (no return) counts for neither.
const float m = min_range_[index(a, b)];
if (m < r - margin)
++nearer;
else if (std::isfinite(m) && m > r + margin)
++farther;
}
}
const float centre = min_range_[index(u, v)];
if (nearer >= kOccludingBins || centre < r - margin)
return Evidence::kOccluded;
if (farther >= kSeeThroughBins && std::isfinite(centre) && centre > r + margin)
return Evidence::kSeenThrough;
return Evidence::kNone;
}
// ---------------------------------------------------------------------------------------------
// Layer
// ---------------------------------------------------------------------------------------------
@@ -258,6 +350,7 @@ void DepthCameraObstacleLayer::loadParameters()
std::string topics_string = loadParam(layer, "observation_sources", std::string(""));
debug_stats_ = loadParam(layer["debug"], "stats", true);
debug_stats_period_ = loadParam(layer["debug"], "stats_period", 5.0);
occlusion_guard_ = loadParam(layer, "occlusion_guard", false);
// ===== 2. Override from "<costmap>/<plugin>", which copyParentParameters() filled from the
// shared "<plugin>:" block (only when the key exists) =====
@@ -306,6 +399,8 @@ void DepthCameraObstacleLayer::loadParameters()
priv_nh.getParam("debug/stats", debug_stats_, debug_stats_);
if (priv_nh.hasParam("debug/stats_period"))
priv_nh.getParam("debug/stats_period", debug_stats_period_, debug_stats_period_);
if (priv_nh.hasParam("occlusion_guard"))
priv_nh.getParam("occlusion_guard", occlusion_guard_, occlusion_guard_);
default_value_ = track_unknown_space ? NO_INFORMATION : FREE_SPACE;
if (layer["clear_touches_bounds"] || priv_nh.hasParam("clear_touches_bounds"))
@@ -350,6 +445,7 @@ void DepthCameraObstacleLayer::loadParameters()
src->fov_w = loadParam(layer[name], "FOV_W", 1.5);
src->min_detect_distance = loadParam(layer[name], "min_detect_distance", 0.15);
src->max_detect_distance = loadParam(layer[name], "max_detect_distance", 2.5);
src->attach_distance = loadParam(layer[name], "attach_distance", 0.12);
bool inf_is_valid = loadParam(layer[name], "inf_is_valid", false);
// ===== 2. Override from "<costmap>/<plugin>/<source>" =====
@@ -378,6 +474,8 @@ void DepthCameraObstacleLayer::loadParameters()
source_nh.getParam("min_detect_distance", src->min_detect_distance, src->min_detect_distance);
if (source_nh.hasParam("max_detect_distance"))
source_nh.getParam("max_detect_distance", src->max_detect_distance, src->max_detect_distance);
if (source_nh.hasParam("attach_distance"))
source_nh.getParam("attach_distance", src->attach_distance, src->attach_distance);
if (source_nh.hasParam("inf_is_valid"))
source_nh.getParam("inf_is_valid", inf_is_valid, inf_is_valid);
if (inf_is_valid)
@@ -388,6 +486,10 @@ void DepthCameraObstacleLayer::loadParameters()
requireRange(src->fov_v > 0.0 && src->fov_v < M_PI, what + "FOV_V must be in (0, pi) [rad]");
requireRange(src->min_detect_distance >= 0.0 && src->max_detect_distance > src->min_detect_distance,
what + "need 0 <= min_detect_distance < max_detect_distance [m]");
// At half the frustum depth the near and far bands meet and nothing along the axis is marked.
requireRange(src->attach_distance >= 0.0 &&
src->attach_distance < (src->max_detect_distance - src->min_detect_distance) / 2.0,
what + "attach_distance must be in [0, (max_detect_distance - min_detect_distance) / 2) [m]");
requireRange(src->min_obstacle_height <= src->max_obstacle_height,
what + "min_obstacle_height must be <= max_obstacle_height [m]");
requireRange(src->observation_keep_time >= 0.0 && src->expected_update_rate >= 0.0,
@@ -399,14 +501,14 @@ void DepthCameraObstacleLayer::loadParameters()
src->last_updated = robot::Time::now();
robot::log_info("DepthCameraObstacleLayer %s: source %s topic=%s sensor_frame=%s optical=%s "
"FOV_W=%.3f FOV_V=%.3f rad detect=[%.2f, %.2f] m height=[%.2f, %.2f] m "
"FOV_W=%.3f FOV_V=%.3f rad detect=[%.2f, %.2f] m height=[%.2f, %.2f] m attach=%.3f m "
"persistence=%.2f s expected_update_rate=%.2f s marking=%s\n",
name_.c_str(), name.c_str(), src->topic.c_str(),
src->sensor_frame.empty() ? "(cloud frame)" : src->sensor_frame.c_str(),
src->sensor_frame_is_optical ? "true" : "false", src->fov_w, src->fov_v,
src->min_detect_distance, src->max_detect_distance, src->min_obstacle_height,
src->max_obstacle_height, src->observation_keep_time, src->expected_update_rate,
src->marking ? "true" : "false");
src->max_obstacle_height, src->attach_distance, src->observation_keep_time,
src->expected_update_rate, src->marking ? "true" : "false");
sources_.push_back(std::move(src));
}
if (sources_.empty())
@@ -418,7 +520,7 @@ void DepthCameraObstacleLayer::loadParameters()
"ec_seg_distance=%.2f m ec_cluster_min_size=%d size_of_cluster_rejection=%d "
"forced_clearing_distance=%.2f m near_blocked_protection=%s (%d pts) "
"voxelized_observation=%s transform_tolerance=%.2f s combination_method=%d "
"footprint_clearing=%s marking_height=[%.2f, %.2f] m debug/stats=%s\n",
"footprint_clearing=%s marking_height=[%.2f, %.2f] m occlusion_guard=%s debug/stats=%s\n",
name_.c_str(), global_frame_.c_str(), rolling_window_ ? "true" : "false",
track_unknown_space ? "true" : "false", voxel_resolution_, check_radius_,
number_clearing_threshold_, ec_seg_distance_, ec_cluster_min_size_,
@@ -426,7 +528,8 @@ void DepthCameraObstacleLayer::loadParameters()
enable_near_blocked_protection_ ? "true" : "false", number_points_considered_as_blocked_,
use_voxelized_observation_ ? "true" : "false", transform_tolerance_, combination_method_,
footprint_clearing_enabled_ ? "true" : "false",
marking_height_under_ground_, marking_height_above_ground_, debug_stats_ ? "on" : "off");
marking_height_under_ground_, marking_height_above_ground_,
occlusion_guard_ ? "true" : "false", debug_stats_ ? "on" : "off");
}
void DepthCameraObstacleLayer::handleImpl(const void* data, const std::type_info& type,
@@ -513,7 +616,14 @@ bool DepthCameraObstacleLayer::bufferCloud(Source& source, const robot_sensor_ms
obs.stamp = cloud.header.stamp;
// Frustum vertices are given in the sensor frame, then everything is in the global frame.
obs.frustum.build(T_origin, source.fov_w, source.fov_v, source.min_detect_distance,
source.max_detect_distance, source.sensor_frame_is_optical);
source.max_detect_distance, source.sensor_frame_is_optical, source.attach_distance);
// Occlusion guard: nearest return per ray from every point, before the height gate below.
Eigen::Isometry3f T_sensor_cloud = Eigen::Isometry3f::Identity();
if (occlusion_guard_)
{
obs.range.reset(T_origin, source.fov_w, source.fov_v, source.sensor_frame_is_optical);
T_sensor_cloud = (T_origin.inverse() * T_cloud).cast<float>();
}
const std::size_t size = static_cast<std::size_t>(cloud.width) * cloud.height;
obs.points.reserve(size);
@@ -525,6 +635,8 @@ bool DepthCameraObstacleLayer::bufferCloud(Source& source, const robot_sensor_ms
// The source relies on dense clouds; NaN would only disappear later in PCL. Drop it here.
if (!std::isfinite(*iter_x) || !std::isfinite(*iter_y) || !std::isfinite(*iter_z))
continue;
if (occlusion_guard_)
obs.range.addSensorPoint(T_sensor_cloud * Eigen::Vector3f(*iter_x, *iter_y, *iter_z));
const Eigen::Vector3d g = T_cloud * Eigen::Vector3d(*iter_x, *iter_y, *iter_z);
if (g.z() <= source.max_obstacle_height && g.z() >= source.min_obstacle_height)
obs.points.push_back(g.cast<float>());
@@ -584,6 +696,8 @@ void DepthCameraObstacleLayer::updateBounds(double robot_x, double robot_y, doub
bool current = true;
std::vector<DepthCameraFrustum> frustums;
// Points into source->observations, which nothing changes until the end of this cycle.
std::vector<const DepthCameraRangeImage*> range_images;
std::vector<Eigen::Vector3f> combined;
for (const auto& source : sources_)
{
@@ -594,6 +708,7 @@ void DepthCameraObstacleLayer::updateBounds(double robot_x, double robot_y, doub
for (const Observation& obs : source->observations)
{
frustums.push_back(obs.frustum);
range_images.push_back(obs.range.empty() ? nullptr : &obs.range);
combined.insert(combined.end(), obs.points.begin(), obs.points.end());
}
current = sourceIsCurrent(*source) && current;
@@ -631,7 +746,7 @@ void DepthCameraObstacleLayer::updateBounds(double robot_x, double robot_y, doub
points.emplace_back(pt.x, pt.y, pt.z);
stats_.cloud_points += points.size();
clearMarkingByKdtree(points, frustums, robot_x, robot_y, min_x, min_y, max_x, max_y);
clearMarkingByKdtree(points, frustums, range_images, robot_x, robot_y, min_x, min_y, max_x, max_y);
if (cloud->points.size() > 5)
{
@@ -668,6 +783,7 @@ void DepthCameraObstacleLayer::updateBounds(double robot_x, double robot_y, doub
void DepthCameraObstacleLayer::clearMarkingByKdtree(const std::vector<Eigen::Vector3f>& cloud,
const std::vector<DepthCameraFrustum>& frustums,
const std::vector<const DepthCameraRangeImage*>& range_images,
double robot_x, double robot_y, double* min_x,
double* min_y, double* max_x, double* max_y)
{
@@ -745,6 +861,34 @@ void DepthCameraObstacleLayer::clearMarkingByKdtree(const std::vector<Eigen::Vec
q.z = search.z();
erase = kdtree.radiusSearch(q, check_radius_, indices, sq_distances) < number_clearing_threshold_;
}
// The kd-tree test cannot tell "gone" from "hidden by something nearer": a person walking in
// front of a box cleared the box. With the guard, the depth rays decide where they can.
if (occlusion_guard_ && !bypass_clearing)
{
// The middle of the cell, not its corner: indices are truncated toward zero, so the corner
// can lie outside a small object and its ray would see the floor behind it.
const Eigen::Vector3f centre(static_cast<float>(wx + std::copysign(0.5 * resolution, wx)),
static_cast<float>(wy + std::copysign(0.5 * resolution, wy)), search.z());
bool occluded = false, seen_through = false;
for (std::size_t i = 0; i < frustums.size() && i < range_images.size(); ++i)
{
if (range_images[i] == nullptr || !frustums[i].inside(search))
continue;
const DepthCameraRangeImage::Evidence evidence = range_images[i]->test(centre);
occluded = occluded || evidence == DepthCameraRangeImage::Evidence::kOccluded;
seen_through = seen_through || evidence == DepthCameraRangeImage::Evidence::kSeenThrough;
}
if (erase && occluded)
{
erase = false;
++stats_.kept_occluded;
}
else if (!erase && seen_through && !occluded)
{
erase = true;
++stats_.cleared_seen_through;
}
}
if (!erase)
continue;
heights.erase(it);
@@ -937,11 +1081,13 @@ void DepthCameraObstacleLayer::logStats()
if (debug_stats_ && stats_.cycles > 0)
robot::log_info("[debug/stats] DepthCameraObstacleLayer %s: cycles=%zu cloud_pts/cycle=%.0f stored=%zu "
"columns=%zu marked=%zu cleared=%zu footprint_cleared=%zu clear_all_cycles=%zu bypass_cycles=%zu "
"tf_wait=%zu tf_drop=%zu out_of_window=%zu bounds_ms avg=%.1f max=%.1f\n",
"tf_wait=%zu tf_drop=%zu out_of_window=%zu kept_occluded=%zu cleared_seen_through=%zu "
"bounds_ms avg=%.1f max=%.1f\n",
name_.c_str(), stats_.cycles, static_cast<double>(stats_.cloud_points) / stats_.cycles,
storedPoints(), pc_3d_map_global_.size(), stats_.marked, stats_.cleared, stats_.footprint_cleared,
stats_.cleared_all_frames, stats_.bypassed_frames, stats_.tf_waits, stats_.tf_drops,
stats_.dropped_out_of_window, stats_.bounds_ms_sum / stats_.cycles, stats_.bounds_ms_max);
stats_.dropped_out_of_window, stats_.kept_occluded, stats_.cleared_seen_through,
stats_.bounds_ms_sum / stats_.cycles, stats_.bounds_ms_max);
stats_ = Stats();
}