feat(depth): certify evidence points instead of whole voxels (phase 1)

The whole-voxel rule never clears a voxel whose box crosses the image edge.
A person bending over to lift an object leaves high voxels at the top edge
of the image: in the 2026-10-15 lift bag 0 of 54 phantom cells cleared.

- DepthEvidenceStore keeps, per marked voxel, the 6 per-axis extreme points
  plus the most recent ones, keyed by a window-independent cell index.
- DepthVisibilityChecker::classifyPoints: Free only when every evidence
  point projects with a full patch inside the usable image and sees valid
  depth behind it; any surface in front keeps it, invalid depth keeps it.
- Paired marking drops points within depth_marking_border_px of the image
  edge, so every kept point can be re-checked from the pose that saw it.
- Voxels without evidence keep the whole-voxel rule; evidence is erased on
  clear, pruned on rolling shift and every 50 frames.
- New keys depth_evidence_points_enabled (default false),
  depth_evidence_points_per_voxel (8, 6..16), depth_marking_border_px
  (must be > depth_projection_margin_px when enabled); startup log and
  counters (by_evidence, border_dropped_points, evidence_voxels).
- Tests: depth_evidence_store_test; checker and layer tests for the image
  top cut, border drop, rolling shift and a still-visible object.
This commit is contained in:
2026-10-15 13:22:28 +07:00
parent 2ca0bcc1c1
commit 5e38857e48
11 changed files with 608 additions and 15 deletions

View File

@@ -109,6 +109,7 @@ add_library(robot_costmap_2d SHARED
src/costmap_2d.cpp
src/observation_buffer.cpp
src/depth_visibility.cpp
src/depth_evidence_store.cpp
src/layer.cpp
src/layered_costmap.cpp
src/costmap_math.cpp
@@ -297,6 +298,9 @@ if(BUILD_DEPTH_MARKING_TESTS)
add_executable(depth_visibility_test test/depth_visibility_test.cpp)
target_link_libraries(depth_visibility_test PRIVATE
plugins robot_costmap_2d GTest::GTest GTest::Main)
add_executable(depth_evidence_store_test test/depth_evidence_store_test.cpp)
target_link_libraries(depth_evidence_store_test PRIVATE
robot_costmap_2d GTest::GTest GTest::Main)
endif()
if(BUILD_COSTMAP_TESTS)

View File

@@ -0,0 +1,86 @@
#ifndef ROBOT_COSTMAP_2D_DEPTH_EVIDENCE_STORE_H_
#define ROBOT_COSTMAP_2D_DEPTH_EVIDENCE_STORE_H_
#include <Eigen/Core>
#include <array>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <unordered_map>
#include <vector>
namespace robot_costmap_2d
{
/**
* @brief Measured points that marked each voxel of a depth-only VoxelLayer.
*
* The observed_volume clearing certifies these points instead of the whole voxel box:
* the occupancy of a depth-only layer is exactly what the camera saw, so the part of a
* voxel the camera never saw carries no occupancy of its own. Keys use a
* window-independent cell index, so a rolling origin shift needs no copy; callers drop
* keys that left the window with eraseIf().
*
* Per voxel it keeps the 6 per-axis extreme points (min/max x, y, z) and fills the
* remaining slots with the most recent points.
*/
class DepthEvidenceStore
{
public:
static constexpr unsigned int kExtremeSlots = 6;
static constexpr unsigned int kMaxPoints = 16;
struct VoxelKey
{
int x;
int y;
unsigned int z;
bool operator==(const VoxelKey& other) const
{
return x == other.x && y == other.y && z == other.z;
}
};
explicit DepthEvidenceStore(unsigned int points_per_voxel = 8);
/// Clamped to [kExtremeSlots, kMaxPoints]; drops all stored evidence.
void setPointsPerVoxel(unsigned int points_per_voxel);
unsigned int pointsPerVoxel() const { return points_per_voxel_; }
/// Records a marking point [global frame, m]. fresh = true drops points left over from
/// an earlier occupancy of the voxel (it was not MARKED before this point).
void add(const VoxelKey& key, const Eigen::Vector3f& point, bool fresh);
/// Distinct evidence points of one voxel. Returns false when the voxel has none.
bool points(const VoxelKey& key, std::vector<Eigen::Vector3d>& out) const;
void erase(const VoxelKey& key);
void eraseIf(const std::function<bool(const VoxelKey&)>& predicate);
void clear();
std::size_t size() const { return entries_.size(); }
private:
struct KeyHash
{
std::size_t operator()(const VoxelKey& key) const noexcept
{
return (static_cast<std::size_t>(static_cast<uint32_t>(key.x)) * 73856093u) ^
(static_cast<std::size_t>(static_cast<uint32_t>(key.y)) * 19349663u) ^
(static_cast<std::size_t>(key.z) * 83492791u);
}
};
struct Entry
{
std::array<Eigen::Vector3f, kMaxPoints> points;
unsigned char count = 0; ///< valid slots, extremes included
unsigned char next_recent = 0; ///< ring position among the recent slots
};
unsigned int points_per_voxel_;
std::unordered_map<VoxelKey, Entry, KeyHash> entries_;
};
} // namespace robot_costmap_2d
#endif // ROBOT_COSTMAP_2D_DEPTH_EVIDENCE_STORE_H_

View File

@@ -25,7 +25,24 @@ public:
DepthVisibilityResult classify(const Eigen::Vector3d& lower,
const Eigen::Vector3d& upper) const;
/**
* @brief Certifies the measured evidence points of one voxel [global frame, m].
*
* Free only when every point projects with its projection_margin_px patch fully inside
* the usable image, every patch pixel holds valid depth, and that depth lies behind the
* point by more than free_margin_m. Any pixel in front keeps the voxel (Surface); an
* invalid pixel or a point out of view keeps it as Unknown. An empty list is Unknown.
*/
DepthVisibilityResult classifyPoints(const std::vector<Eigen::Vector3d>& points) const;
/// True when a global-frame point projects at least border_px inside the usable image
/// (the clear_left/right border strips are not usable). Used to gate evidence marking.
bool projectsInside(const Eigen::Vector3d& point, unsigned int border_px) const;
private:
/// Raw depth at a pixel [m]; NaN for an unsupported encoding. Caller checks bounds.
double depthAt(int u, int v) const;
robot_sensor_msgs::DepthCameraData::ConstPtr data_;
Eigen::Isometry3d camera_from_global_{Eigen::Isometry3d::Identity()};
double min_height_{0}, max_height_{0};

View File

@@ -92,6 +92,15 @@ struct DepthFrustumConfig
double valid_max_z_m = 3.0;
double free_margin_m = 0.02;
unsigned int projection_margin_px = 1;
/// Certify the measured evidence points of each marked voxel instead of the whole
/// voxel box. A box cut by the image edge can never be certified, while the points
/// that marked it were inside the image when they were seen.
bool evidence_points_enabled = false;
/// [points] evidence kept per voxel: 6 per-axis extremes plus the most recent ones.
unsigned int evidence_points_per_voxel = 8;
/// [px] with evidence points, marking drops points that project closer than this to
/// the usable image edge, so each kept point has a full projection patch in view.
unsigned int marking_border_px = 0;
};
class DepthCameraObservation

View File

@@ -49,6 +49,7 @@
#include <robot_sensor_msgs/PointCloud2.h>
#include <robot_sensor_msgs/point_cloud_conversion.h>
#include <robot_costmap_2d/obstacle_layer.h>
#include <robot_costmap_2d/depth_evidence_store.h>
#include <robot_voxel_grid/voxel_grid.h>
#include <limits>
@@ -57,6 +58,8 @@
namespace robot_costmap_2d
{
class DepthVisibilityChecker;
class VoxelLayer : public ObstacleLayer
{
public:
@@ -111,14 +114,35 @@ private:
double min_range, double max_range, double skip_dist,
double* min_x, double* min_y, double* max_x, double* max_y);
bool clipColumnSegment(double& sx, double& sy, double& ex, double& ey) const;
/// Paired depth marking: the checker of the same frame gates marking at the image
/// border and the store records evidence points. Null for every other source.
struct PairedMarking
{
const DepthVisibilityChecker* checker;
const DepthFrustumConfig* config;
};
void markObservation(const Observation& observation, double* min_x, double* min_y,
double* max_x, double* max_y);
double* max_x, double* max_y, const PairedMarking* paired = nullptr);
void processPairedDepth(double* min_x, double* min_y, double* max_x, double* max_y);
struct VisibilityCounts
{
uint64_t free{0}, unknown{0}, surface{0}, frames{0};
uint64_t by_evidence{0}; ///< decisions made from evidence points
uint64_t border_dropped{0}; ///< marking points dropped at the image border
} visibility_counts_;
/// Window-independent key: local cell index plus the cells the rolling origin moved.
DepthEvidenceStore::VoxelKey evidenceKey(unsigned int x, unsigned int y, unsigned int z) const
{
return {static_cast<int>(x) + evidence_offset_x_, static_cast<int>(y) + evidence_offset_y_, z};
}
/// Drops evidence of voxels that left the window or are no longer MARKED.
void pruneDepthEvidence();
DepthEvidenceStore depth_evidence_;
int evidence_offset_x_ = 0;
int evidence_offset_y_ = 0;
uint64_t frames_since_evidence_prune_ = 0;
bool publish_voxel_;
robot_voxel_grid::VoxelGrid robot_voxel_grid_;

View File

@@ -37,6 +37,7 @@
*********************************************************************/
#include <robot_costmap_2d/obstacle_layer.h>
#include <robot_costmap_2d/costmap_math.h>
#include <robot_costmap_2d/depth_evidence_store.h>
#include <robot_sensor_msgs/point_cloud2_iterator.h>
@@ -278,6 +279,26 @@ bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHa
if (frustum_config.observed_volume_clearing &&
(!std::isfinite(frustum_config.voxel_z_resolution_m) || frustum_config.voxel_z_resolution_m <= 0))
throw std::invalid_argument("observed_volume requires finite positive voxel z resolution");
int evidence_points = static_cast<int>(frustum_config.evidence_points_per_voxel);
int marking_border = static_cast<int>(frustum_config.marking_border_px);
read_depth_option("depth_evidence_points_enabled", frustum_config.evidence_points_enabled);
read_depth_option("depth_evidence_points_per_voxel", evidence_points);
read_depth_option("depth_marking_border_px", marking_border);
if (evidence_points < static_cast<int>(DepthEvidenceStore::kExtremeSlots) ||
evidence_points > static_cast<int>(DepthEvidenceStore::kMaxPoints) ||
marking_border < 0 || marking_border > 64)
throw std::invalid_argument("depth_evidence_points_per_voxel must be 6..16 and "
"depth_marking_border_px 0..64");
frustum_config.evidence_points_per_voxel = static_cast<unsigned int>(evidence_points);
frustum_config.marking_border_px = static_cast<unsigned int>(marking_border);
if (frustum_config.evidence_points_enabled && !frustum_config.observed_volume_clearing)
throw std::invalid_argument("depth_evidence_points_enabled requires depth_clearing_mode: observed_volume");
// One pixel more than the patch radius absorbs rounding of the stored float points,
// so every kept evidence point is re-checked with a full patch from its own pose.
if (frustum_config.evidence_points_enabled &&
frustum_config.marking_border_px <= frustum_config.projection_margin_px)
throw std::invalid_argument("depth_marking_border_px must be > depth_projection_margin_px "
"when depth_evidence_points_enabled is true");
frustum_config.pixel_step = static_cast<unsigned int>(std::max(1, frustum_pixel_step));
frustum_config.clear_left_border_px =
@@ -418,9 +439,13 @@ bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHa
paired_depth_sources_.push_back(paired);
marking_buffers_.erase(std::remove(marking_buffers_.begin(), marking_buffers_.end(), m.buffer), marking_buffers_.end());
robot::log_info("depth clearing observed_volume: paired %s + %s, height=[%.3f, %.3f] m; "
"unknown/occluded/outside FOV retained; queue=%u age=%.3f s; one valid free frame\n",
"unknown/occluded/outside FOV retained; queue=%u age=%.3f s; one valid free frame; "
"evidence_points=%s per_voxel=%u marking_border=%u px projection_margin=%u px\n",
paired->cloud_topic.c_str(), paired->depth_topic.c_str(), m.min_height, m.max_height,
paired->config.pair_queue_size, paired->config.observation_max_age_s);
paired->config.pair_queue_size, paired->config.observation_max_age_s,
paired->config.evidence_points_enabled ? "true" : "false",
paired->config.evidence_points_per_voxel, paired->config.marking_border_px,
paired->config.projection_margin_px);
}
}
catch (const YAML::BadFile& e) {

View File

@@ -149,6 +149,10 @@ bool VoxelLayer::getParams(const std::string& config_file_name, robot::NodeHandl
throw std::invalid_argument("observed_volume marking height band must fit its voxel grid");
robot::log_info("observed_volume grid: z_resolution=%.4f m bins=%u span=[%.3f, %.3f) m\n",
z_resolution_, size_z_, origin_z_, origin_z_ + size_z_ * z_resolution_);
depth_evidence_.setPointsPerVoxel(source->config.evidence_points_per_voxel);
robot::log_info("observed_volume evidence points: %s, points_per_voxel=%u, marking_border_px=%u px\n",
source->config.evidence_points_enabled ? "enabled" : "disabled (whole-voxel check)",
depth_evidence_.pointsPerVoxel(), source->config.marking_border_px);
}
this->matchSize();
}
@@ -164,6 +168,7 @@ void VoxelLayer::matchSize()
{
ObstacleLayer::matchSize();
robot_voxel_grid_.resize(size_x_, size_y_, size_z_);
depth_evidence_.clear();
if (!(robot_voxel_grid_.sizeX() == size_x_ && robot_voxel_grid_.sizeY() == size_y_))
{
std::cerr << "[FATAL] Voxel grid size mismatch: "
@@ -186,6 +191,7 @@ void VoxelLayer::resetMaps()
resetPairedDepth();
Costmap2D::resetMaps();
robot_voxel_grid_.reset();
depth_evidence_.clear();
}
void VoxelLayer::updateBounds(double robot_x, double robot_y, double robot_yaw, double* min_x,
@@ -237,8 +243,9 @@ void VoxelLayer::updateBounds(double robot_x, double robot_y, double robot_yaw,
}
void VoxelLayer::markObservation(const Observation& obs, double* min_x, double* min_y,
double* max_x, double* max_y)
double* max_x, double* max_y, const PairedMarking* paired)
{
const bool record_evidence = paired != nullptr && paired->config->evidence_points_enabled;
const robot_sensor_msgs::PointCloud2& cloud = *(obs.cloud_);
@@ -275,6 +282,21 @@ void VoxelLayer::markObservation(const Observation& obs, double* min_x, double*
continue;
}
bool fresh_voxel = false;
if (record_evidence)
{
// A point at the image edge could never be re-checked with a full patch from the
// pose that saw it, and would leave a voxel that only the whole-box rule judges.
const Eigen::Vector3d point(*iter_x, *iter_y, *iter_z);
if (paired->config->marking_border_px > 0 &&
!paired->checker->projectsInside(point, paired->config->marking_border_px))
{
++visibility_counts_.border_dropped;
continue;
}
fresh_voxel = robot_voxel_grid_.getVoxel(mx, my, mz) != robot_voxel_grid::MARKED;
}
// mark the cell in the voxel grid and check if we should also mark it in the costmap
if (robot_voxel_grid_.markVoxelInMap(mx, my, mz, mark_threshold_))
{
@@ -283,9 +305,25 @@ void VoxelLayer::markObservation(const Observation& obs, double* min_x, double*
costmap_[index] = LETHAL_OBSTACLE;
touch(double(*iter_x), double(*iter_y), min_x, min_y, max_x, max_y);
}
if (record_evidence)
depth_evidence_.add(evidenceKey(mx, my, mz), Eigen::Vector3f(*iter_x, *iter_y, *iter_z), fresh_voxel);
}
}
void VoxelLayer::pruneDepthEvidence()
{
if (depth_evidence_.size() == 0)
return;
depth_evidence_.eraseIf([this](const DepthEvidenceStore::VoxelKey& key) {
const int x = key.x - evidence_offset_x_;
const int y = key.y - evidence_offset_y_;
return x < 0 || y < 0 || x >= static_cast<int>(size_x_) || y >= static_cast<int>(size_y_) ||
key.z >= size_z_ ||
robot_voxel_grid_.getVoxel(static_cast<unsigned int>(x), static_cast<unsigned int>(y), key.z) !=
robot_voxel_grid::MARKED;
});
}
void VoxelLayer::processPairedDepth(double* min_x, double* min_y, double* max_x, double* max_y)
{
for (const auto& source : paired_depth_sources_)
@@ -329,6 +367,10 @@ void VoxelLayer::processPairedDepth(double* min_x, double* min_y, double* max_x,
// No occupied cache: the live voxel grid already contains rolling-window overlap.
// Plan all clears before applying this frame; both branches share exactly one pose.
// With evidence points a voxel is judged by the points that marked it; a voxel
// without evidence (marked before the mode was enabled) keeps the whole-box rule.
const bool use_evidence = source->config.evidence_points_enabled;
std::vector<Eigen::Vector3d> evidence;
std::vector<std::array<unsigned int, 3>> free_voxels;
for (unsigned int y = 0; y < size_y_; ++y)
for (unsigned int x = 0; x < size_x_; ++x)
@@ -337,10 +379,19 @@ void VoxelLayer::processPairedDepth(double* min_x, double* min_y, double* max_x,
for (unsigned int z = 0; z < size_z_; ++z)
{
if (robot_voxel_grid_.getVoxel(x, y, z) != robot_voxel_grid::MARKED) continue;
const Eigen::Vector3d lower(origin_x_ + x * resolution_,
origin_y_ + y * resolution_, origin_z_ + z * z_resolution_);
const Eigen::Vector3d upper = lower + Eigen::Vector3d(resolution_, resolution_, z_resolution_);
const auto visibility = checker.classify(lower, upper);
DepthVisibilityResult visibility;
if (use_evidence && depth_evidence_.points(evidenceKey(x, y, z), evidence))
{
visibility = checker.classifyPoints(evidence);
++visibility_counts_.by_evidence;
}
else
{
const Eigen::Vector3d lower(origin_x_ + x * resolution_,
origin_y_ + y * resolution_, origin_z_ + z * z_resolution_);
const Eigen::Vector3d upper = lower + Eigen::Vector3d(resolution_, resolution_, z_resolution_);
visibility = checker.classify(lower, upper);
}
if (visibility.state == DepthVisibility::Free)
{ free_voxels.push_back({x, y, z}); ++visibility_counts_.free; }
else if (visibility.state == DepthVisibility::Surface) ++visibility_counts_.surface;
@@ -351,6 +402,7 @@ void VoxelLayer::processPairedDepth(double* min_x, double* min_y, double* max_x,
{
const auto x = voxel[0], y = voxel[1], z = voxel[2];
robot_voxel_grid_.clearVoxel(x, y, z);
depth_evidence_.erase(evidenceKey(x, y, z));
const auto status = robot_voxel_grid_.getVoxelColumn(x, y, unknown_threshold_, mark_threshold_);
costmap_[getIndex(x, y)] = status == robot_voxel_grid::MARKED ? LETHAL_OBSTACLE :
status == robot_voxel_grid::FREE ? FREE_SPACE : NO_INFORMATION;
@@ -358,21 +410,33 @@ void VoxelLayer::processPairedDepth(double* min_x, double* min_y, double* max_x,
touch(origin_x_ + x * resolution_, origin_y_ + y * resolution_, min_x, min_y, max_x, max_y);
touch(origin_x_ + (x + 1) * resolution_, origin_y_ + (y + 1) * resolution_, min_x, min_y, max_x, max_y);
}
markObservation(observations.front(), min_x, min_y, max_x, max_y);
const PairedMarking paired_marking{&checker, &source->config};
markObservation(observations.front(), min_x, min_y, max_x, max_y, &paired_marking);
source->pairer.applied(pair.stamp);
++visibility_counts_.frames;
// Voxels cleared by other paths (footprint, recovery, legacy rays) leave stale
// evidence; a bounded sweep keeps the store at the size of the live occupancy.
constexpr uint64_t kEvidencePrunePeriodFrames = 50;
if (use_evidence && ++frames_since_evidence_prune_ >= kEvidencePrunePeriodFrames)
{
pruneDepthEvidence();
frames_since_evidence_prune_ = 0;
}
}
const auto counts = source->pairer.counts();
robot::log_info_throttle(5.0, "paired depth [%s]: applied=%llu tf_wait=%llu "
"invalid=%llu stale=%llu expired=%llu overflow=%llu duplicate=%llu; "
"voxel decisions free=%llu surface=%llu unknown=%llu (cumulative)\n",
"voxel decisions free=%llu surface=%llu unknown=%llu by_evidence=%llu; "
"border_dropped_points=%llu evidence_voxels=%zu (cumulative)\n",
name_.c_str(), static_cast<unsigned long long>(counts.applied),
static_cast<unsigned long long>(counts.tf_wait), static_cast<unsigned long long>(counts.invalid),
static_cast<unsigned long long>(counts.stale), static_cast<unsigned long long>(counts.expired),
static_cast<unsigned long long>(counts.overflow), static_cast<unsigned long long>(counts.duplicate),
static_cast<unsigned long long>(visibility_counts_.free),
static_cast<unsigned long long>(visibility_counts_.surface),
static_cast<unsigned long long>(visibility_counts_.unknown));
static_cast<unsigned long long>(visibility_counts_.unknown),
static_cast<unsigned long long>(visibility_counts_.by_evidence),
static_cast<unsigned long long>(visibility_counts_.border_dropped), depth_evidence_.size());
}
}
@@ -1132,6 +1196,10 @@ void VoxelLayer::updateOrigin(double new_origin_x, double new_origin_y)
size_x_, cell_size_x, cell_size_y);
}
// Evidence keys are window-independent: track the shift, then drop what left the window.
evidence_offset_x_ += cell_ox;
evidence_offset_y_ += cell_oy;
pruneDepthEvidence();
}
// Export factory function

View File

@@ -0,0 +1,89 @@
#include <robot_costmap_2d/depth_evidence_store.h>
#include <algorithm>
namespace robot_costmap_2d
{
DepthEvidenceStore::DepthEvidenceStore(unsigned int points_per_voxel)
: points_per_voxel_(std::clamp(points_per_voxel, kExtremeSlots, kMaxPoints)), entries_()
{
}
void DepthEvidenceStore::setPointsPerVoxel(unsigned int points_per_voxel)
{
points_per_voxel_ = std::clamp(points_per_voxel, kExtremeSlots, kMaxPoints);
entries_.clear();
}
void DepthEvidenceStore::add(const VoxelKey& key, const Eigen::Vector3f& point, bool fresh)
{
if (!point.allFinite())
return;
Entry& entry = entries_[key];
if (fresh || entry.count == 0)
{
// Slots 0..5 hold min/max of x, y, z; the first point is every extreme.
entry.points.fill(point);
entry.count = kExtremeSlots;
entry.next_recent = 0;
return;
}
for (int axis = 0; axis < 3; ++axis)
{
if (point[axis] < entry.points[2 * axis][axis])
entry.points[2 * axis] = point;
if (point[axis] > entry.points[2 * axis + 1][axis])
entry.points[2 * axis + 1] = point;
}
const unsigned int recent_slots = points_per_voxel_ - kExtremeSlots;
if (recent_slots == 0)
return;
if (entry.count < points_per_voxel_)
{
entry.points[entry.count++] = point;
return;
}
entry.points[kExtremeSlots + entry.next_recent] = point;
entry.next_recent = static_cast<unsigned char>((entry.next_recent + 1) % recent_slots);
}
bool DepthEvidenceStore::points(const VoxelKey& key, std::vector<Eigen::Vector3d>& out) const
{
out.clear();
const auto it = entries_.find(key);
if (it == entries_.end() || it->second.count == 0)
return false;
const Entry& entry = it->second;
for (unsigned int i = 0; i < entry.count; ++i)
{
const Eigen::Vector3d point = entry.points[i].cast<double>();
// Extreme slots often repeat the same point; checking it twice adds nothing.
if (std::find(out.begin(), out.end(), point) == out.end())
out.push_back(point);
}
return true;
}
void DepthEvidenceStore::erase(const VoxelKey& key)
{
entries_.erase(key);
}
void DepthEvidenceStore::eraseIf(const std::function<bool(const VoxelKey&)>& predicate)
{
for (auto it = entries_.begin(); it != entries_.end();)
{
if (predicate(it->first))
it = entries_.erase(it);
else
++it;
}
}
void DepthEvidenceStore::clear()
{
entries_.clear();
}
} // namespace robot_costmap_2d

View File

@@ -153,10 +153,7 @@ DepthVisibilityResult DepthVisibilityChecker::classify(const Eigen::Vector3d& bo
{
if (!intersectsPixel(hull, u, v, margin + .5)) continue;
any_pixel = true;
double measured_z;
const auto* pixel = image.data.data() + static_cast<size_t>(v) * image.step + u * bytes_per_pixel_;
if (bytes_per_pixel_ == 2) { uint16_t z; std::memcpy(&z, pixel, 2); measured_z = z * .001; }
else { float z; std::memcpy(&z, pixel, 4); measured_z = z; }
const double measured_z = depthAt(u, v);
if (!std::isfinite(measured_z) || measured_z < config_.valid_min_z_m || measured_z > config_.valid_max_z_m)
return {DepthVisibility::Unknown, DepthVisibilityReason::InvalidDepth};
if (measured_z <= far_z + config_.free_margin_m)
@@ -164,4 +161,92 @@ DepthVisibilityResult DepthVisibilityChecker::classify(const Eigen::Vector3d& bo
}
return any_pixel ? DepthVisibilityResult{DepthVisibility::Free, DepthVisibilityReason::Free} : DepthVisibilityResult{};
}
double DepthVisibilityChecker::depthAt(int u, int v) const
{
const auto& image = data_->depth;
const auto* pixel = image.data.data() + static_cast<size_t>(v) * image.step +
static_cast<size_t>(u) * bytes_per_pixel_;
if (bytes_per_pixel_ == 2)
{
uint16_t millimeters;
std::memcpy(&millimeters, pixel, 2);
return millimeters * .001;
}
if (bytes_per_pixel_ == 4)
{
float meters;
std::memcpy(&meters, pixel, 4);
return meters;
}
return std::numeric_limits<double>::quiet_NaN();
}
namespace
{
// Pixel index of a projection; the bounds test keeps lround() away from huge values.
bool projectToPixel(const Eigen::Vector3d& camera_point, const robot_sensor_msgs::CameraInfo& ci,
int left, int right, int top, int bottom, int& u, int& v)
{
const double pu = ci.K[0] * camera_point.x() / camera_point.z() + ci.K[2];
const double pv = ci.K[4] * camera_point.y() / camera_point.z() + ci.K[5];
// round(p) in [lo, hi] <=> p in [lo - 0.5, hi + 0.5)
if (!std::isfinite(pu) || !std::isfinite(pv) || pu < left - .5 || pu >= right + .5 ||
pv < top - .5 || pv >= bottom + .5)
return false;
u = static_cast<int>(std::lround(pu));
v = static_cast<int>(std::lround(pv));
return true;
}
} // namespace
bool DepthVisibilityChecker::projectsInside(const Eigen::Vector3d& point, unsigned int border_px) const
{
if (!data_ || !point.allFinite())
return false;
const auto& image = data_->depth;
const Eigen::Vector3d p = camera_from_global_ * point;
if (!p.allFinite() || p.z() < config_.valid_min_z_m)
return false;
const int border = static_cast<int>(border_px);
int u, v;
return projectToPixel(p, data_->camera_info,
static_cast<int>(config_.clear_left_border_px) + border,
static_cast<int>(image.width) - 1 - static_cast<int>(config_.clear_right_border_px) - border,
border, static_cast<int>(image.height) - 1 - border, u, v);
}
DepthVisibilityResult DepthVisibilityChecker::classifyPoints(const std::vector<Eigen::Vector3d>& points) const
{
if (!data_ || points.empty())
return {};
const auto& image = data_->depth;
const int r = static_cast<int>(config_.projection_margin_px);
for (const auto& point : points)
{
if (!point.allFinite())
return {};
const Eigen::Vector3d p = camera_from_global_ * point;
// Same view limits as classify(): out of the trusted optical range is not seen.
if (!p.allFinite() || p.z() < config_.valid_min_z_m || p.z() > config_.valid_max_z_m)
return {};
int u, v;
if (!projectToPixel(p, data_->camera_info,
static_cast<int>(config_.clear_left_border_px) + r,
static_cast<int>(image.width) - 1 - static_cast<int>(config_.clear_right_border_px) - r,
r, static_cast<int>(image.height) - 1 - r, u, v))
return {};
for (int dv = -r; dv <= r; ++dv)
for (int du = -r; du <= r; ++du)
{
const double measured_z = depthAt(u + du, v + dv);
if (!std::isfinite(measured_z) || measured_z < config_.valid_min_z_m ||
measured_z > config_.valid_max_z_m)
return {DepthVisibility::Unknown, DepthVisibilityReason::InvalidDepth};
if (measured_z <= p.z() + config_.free_margin_m)
return {DepthVisibility::Surface, DepthVisibilityReason::Surface};
}
}
return {DepthVisibility::Free, DepthVisibilityReason::Free};
}
} // namespace robot_costmap_2d

View File

@@ -0,0 +1,94 @@
#include <robot_costmap_2d/depth_evidence_store.h>
#include <gtest/gtest.h>
#include <algorithm>
#include <cmath>
using robot_costmap_2d::DepthEvidenceStore;
namespace
{
bool contains(const std::vector<Eigen::Vector3d>& points, const Eigen::Vector3d& point)
{
return std::any_of(points.begin(), points.end(),
[&](const Eigen::Vector3d& p) { return (p - point).norm() < 1e-6; });
}
} // namespace
TEST(DepthEvidenceStore, FirstPointIsTheOnlyEvidence)
{
DepthEvidenceStore store(8);
std::vector<Eigen::Vector3d> points;
EXPECT_FALSE(store.points({1, 2, 3}, points));
store.add({1, 2, 3}, Eigen::Vector3f(1.f, 2.f, .3f), false);
ASSERT_TRUE(store.points({1, 2, 3}, points));
ASSERT_EQ(points.size(), 1u);
EXPECT_TRUE(contains(points, Eigen::Vector3d(1.0, 2.0, 0.3)));
EXPECT_FALSE(store.points({1, 2, 4}, points));
}
TEST(DepthEvidenceStore, KeepsAxisExtremesWhenFull)
{
DepthEvidenceStore store(6); // extremes only, no recent slots
const DepthEvidenceStore::VoxelKey key{0, 0, 0};
store.add(key, Eigen::Vector3f(.02f, .02f, .02f), false);
store.add(key, Eigen::Vector3f(.00f, .03f, .03f), false); // new min x
store.add(key, Eigen::Vector3f(.04f, .01f, .01f), false); // new max x, min y, min z
store.add(key, Eigen::Vector3f(.02f, .02f, .02f), false); // inside: changes nothing
std::vector<Eigen::Vector3d> points;
ASSERT_TRUE(store.points(key, points));
EXPECT_TRUE(contains(points, Eigen::Vector3d(.00, .03, .03)));
EXPECT_TRUE(contains(points, Eigen::Vector3d(.04, .01, .01)));
EXPECT_LE(points.size(), 6u);
}
TEST(DepthEvidenceStore, RecentSlotsRotate)
{
DepthEvidenceStore store(7); // one recent slot
const DepthEvidenceStore::VoxelKey key{0, 0, 0};
store.add(key, Eigen::Vector3f(.0f, .0f, .0f), false);
store.add(key, Eigen::Vector3f(.04f, .04f, .04f), false);
store.add(key, Eigen::Vector3f(.01f, .02f, .03f), false);
store.add(key, Eigen::Vector3f(.03f, .02f, .01f), false);
std::vector<Eigen::Vector3d> points;
ASSERT_TRUE(store.points(key, points));
EXPECT_TRUE(contains(points, Eigen::Vector3d(.03, .02, .01)));
EXPECT_FALSE(contains(points, Eigen::Vector3d(.01, .02, .03)));
}
TEST(DepthEvidenceStore, FreshVoxelDropsOldEvidence)
{
DepthEvidenceStore store(8);
const DepthEvidenceStore::VoxelKey key{5, -3, 2};
store.add(key, Eigen::Vector3f(1.f, 1.f, .2f), false);
store.add(key, Eigen::Vector3f(1.04f, 1.04f, .24f), true);
std::vector<Eigen::Vector3d> points;
ASSERT_TRUE(store.points(key, points));
ASSERT_EQ(points.size(), 1u);
EXPECT_TRUE(contains(points, Eigen::Vector3d(1.04, 1.04, .24)));
}
TEST(DepthEvidenceStore, EraseEraseIfClearAndNonFinite)
{
DepthEvidenceStore store(8);
store.add({0, 0, 0}, Eigen::Vector3f(0.f, 0.f, 0.f), false);
store.add({1, 0, 0}, Eigen::Vector3f(.05f, 0.f, 0.f), false);
store.add({2, 0, 0}, Eigen::Vector3f(.1f, 0.f, 0.f), false);
store.add({3, 0, 0}, Eigen::Vector3f(std::nanf(""), 0.f, 0.f), false);
EXPECT_EQ(store.size(), 3u);
store.erase({0, 0, 0});
EXPECT_EQ(store.size(), 2u);
store.eraseIf([](const DepthEvidenceStore::VoxelKey& key) { return key.x == 2; });
std::vector<Eigen::Vector3d> points;
EXPECT_TRUE(store.points({1, 0, 0}, points));
EXPECT_FALSE(store.points({2, 0, 0}, points));
store.clear();
EXPECT_EQ(store.size(), 0u);
}
TEST(DepthEvidenceStore, CapacityIsClamped)
{
EXPECT_EQ(DepthEvidenceStore(2).pointsPerVoxel(), DepthEvidenceStore::kExtremeSlots);
EXPECT_EQ(DepthEvidenceStore(100).pointsPerVoxel(), DepthEvidenceStore::kMaxPoints);
}

View File

@@ -30,6 +30,13 @@ robot_sensor_msgs::PointCloud2 cloud(robot::Time stamp, bool point=true) {
*x=-.01;*y=.11;*z=.62; }
return c;
}
// One marking point given in the optical frame of the camera.
robot_sensor_msgs::PointCloud2 cloudAt(robot::Time stamp, float ox, float oy, float oz) {
robot_sensor_msgs::PointCloud2 c=cloud(stamp,true);
robot_sensor_msgs::PointCloud2Iterator<float> x(c,"x"), y(c,"y"), z(c,"z");
*x=ox;*y=oy;*z=oz;
return c;
}
tf3::TransformStampedMsg pose(robot::Time stamp, double yaw=0) {
tf3::TransformStampedMsg p; p.header.frame_id="odom";p.child_frame_id="camera";
p.header.stamp=tf3::Time(stamp.sec,stamp.nsec);
@@ -73,6 +80,41 @@ TEST(DepthVisibility, RejectsWrongStampModelAndMalformedImage) {
d=depth(2);d->depth.data.pop_back();EXPECT_FALSE(c.prepare(d,p,0,3,cfg));
d=depth(2);d->depth.is_bigendian=true;EXPECT_FALSE(c.prepare(d,p,0,3,cfg));
}
// Camera frame == global frame here. A box whose top crosses the image top can never be
// certified, while a measured point inside the image can.
TEST(DepthVisibility, EvidencePointsCertifyAVoxelCutByTheImageTop) {
DepthVisibilityChecker c; DepthFrustumConfig cfg;
tf3::TransformStampedMsg p; p.header.frame_id="odom";p.child_frame_id="camera";
p.header.stamp=tf3::Time(100,0);p.transform.rotation.w=1;
const Eigen::Vector3d lo(-.02,-.80,1),hi(.02,-.75,1.05); // v from about 0 to 5 px
const std::vector<Eigen::Vector3d> evidence{Eigen::Vector3d(0,-.77,1)}; // v = 3
auto d=depth(2);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg));
EXPECT_EQ(c.classify(lo,hi).state,DepthVisibility::Unknown);
EXPECT_EQ(c.classifyPoints(evidence).state,DepthVisibility::Free);
d=depth(.9);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg));
EXPECT_EQ(c.classifyPoints(evidence).state,DepthVisibility::Surface);
d=depth(2);uint16_t zero=0;std::memcpy(&d->depth.data[4*400+101*2],&zero,2); // inside the 3x3 patch
ASSERT_TRUE(c.prepare(d,p,-10,10,cfg));
EXPECT_EQ(c.classifyPoints(evidence).state,DepthVisibility::Unknown);
d=depth(2);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg));
EXPECT_EQ(c.classifyPoints({Eigen::Vector3d(0,-.80,1)}).state,DepthVisibility::Unknown); // v = 0
EXPECT_EQ(c.classifyPoints({Eigen::Vector3d(0,0,-1)}).state,DepthVisibility::Unknown); // behind
EXPECT_EQ(c.classifyPoints({}).state,DepthVisibility::Unknown);
// Every point must be free: one point in front of a surface keeps the voxel.
d=depth(1.5);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg));
EXPECT_EQ(c.classifyPoints({Eigen::Vector3d(0,0,1),Eigen::Vector3d(0,0,1.6)}).state,DepthVisibility::Surface);
}
TEST(DepthVisibility, ProjectsInsideHonoursBorderAndUsableStrips) {
DepthVisibilityChecker c; DepthFrustumConfig cfg;cfg.clear_left_border_px=10;
tf3::TransformStampedMsg p; p.header.frame_id="odom";p.child_frame_id="camera";
p.header.stamp=tf3::Time(100,0);p.transform.rotation.w=1;
auto d=depth(2);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg));
EXPECT_TRUE(c.projectsInside(Eigen::Vector3d(0,-.77,1),2)); // v = 3
EXPECT_FALSE(c.projectsInside(Eigen::Vector3d(0,-.79,1),2)); // v = 1
EXPECT_TRUE(c.projectsInside(Eigen::Vector3d(-.88,0,1),2)); // u = 12
EXPECT_FALSE(c.projectsInside(Eigen::Vector3d(-.89,0,1),2)); // u = 11, inside the left strip + 2
EXPECT_FALSE(c.projectsInside(Eigen::Vector3d(0,0,.05),2)); // nearer than valid_min_z
}
TEST(DepthPairer, MissingHalfExactPairAndDeduplication) {
robot::Time::setNow(robot::Time(100,0));DepthFrustumConfig cfg;DepthFramePairer p(cfg,.5);
auto c=cloud(robot::Time(100,0));p.addCloud(c);DepthFramePairer::Candidate next;
@@ -112,11 +154,22 @@ protected:
setenv("PNKX_NAV_CORE_CONFIG_DIR",runtime.c_str(),1);
YAML::Node cfg=YAML::Clone(YAML::LoadFile((runtime/"costmap_common_params.yaml").string())["obstacles"]);
cfg["observation_sources"]="pc_marking pc_clearing";cfg["footprint_clearing_enabled"]=false;cfg["enabled"]=true;
// Explicit, so the result does not depend on what the runtime YAML currently enables.
cfg["pc_clearing"]["depth_evidence_points_enabled"]=false;
configure(cfg);
robot::NodeHandle nh("~");nh.setParam("depth_test",cfg);
parent.getCostmap()->resizeMap(80,80,.05,-2,-2);layer.initialize(&parent,"depth_test",&tf);
ASSERT_TRUE(layer.isEnabled());
}
virtual void configure(YAML::Node&) {}
robot::Time now() {return robot::Time(100,++tick*10000000);}
// Marking point given in the camera optical frame; the image shows `measurement` everywhere.
void frameCloud(double measurement,float ox,float oy,float oz) {
auto stamp=now();robot::Time::setNow(stamp);ASSERT_TRUE(tf.setTransform(pose(stamp),"test"));
layer.dataCallBack(cloudAt(stamp,ox,oy,oz),"/camera/depth/points_proc");
robot_sensor_msgs::DepthCameraData::ConstPtr d=depth(measurement,stamp);
layer.dataCallBack(d,"/camera/depth/data");update();
}
void update() {double a=1e9,b=1e9,c=-1e9,d=-1e9;layer.updateBounds(0,0,0,&a,&b,&c,&d);}
void frame(double measurement,bool point=false,double yaw=0,bool hasTf=true,bool hasCloud=true,bool hasDepth=true) {
auto stamp=now();robot::Time::setNow(stamp);
@@ -205,6 +258,45 @@ TEST_F(DepthLayerTest, AStillOccludedVoxelKeepsItsColumnLethal) {
d=partial;layer.dataCallBack(d,"/camera/depth/data");update();EXPECT_EQ(at(),LETHAL_OBSTACLE);
frame(2);EXPECT_EQ(at(),FREE_SPACE);
}
// A point seen 7 px below the image top marks voxel z [0.625, 0.6875] m, whose top
// corner projects above the image. Whole-voxel rule: never certified (the person/hand
// phantom of the 2026-10-15 lift bag).
TEST_F(DepthLayerTest, WholeVoxelRuleKeepsAVoxelCutByTheImageTop) {
frameCloud(.62,-.01f,-.45f,.62f);ASSERT_EQ(at(),LETHAL_OBSTACLE);
frame(2);EXPECT_EQ(at(),LETHAL_OBSTACLE);
}
class DepthEvidenceLayerTest:public DepthLayerTest {
protected:
void configure(YAML::Node& cfg) override {
cfg["pc_clearing"]["depth_evidence_points_enabled"]=true;
cfg["pc_clearing"]["depth_marking_border_px"]=2;
}
};
TEST_F(DepthEvidenceLayerTest, EvidencePointsClearAVoxelCutByTheImageTop) {
frameCloud(.62,-.01f,-.45f,.62f);ASSERT_EQ(at(),LETHAL_OBSTACLE);
frame(2);EXPECT_EQ(at(),FREE_SPACE);
}
TEST_F(DepthEvidenceLayerTest, RetainsOutsideInvalidOccludedAndClearsOnFirstValidFrame) {
frame(.62,true);ASSERT_EQ(at(),LETHAL_OBSTACLE);
frame(2,false,1.57);EXPECT_EQ(at(),LETHAL_OBSTACLE);
frame(0);EXPECT_EQ(at(),LETHAL_OBSTACLE);
frame(.4);EXPECT_EQ(at(),LETHAL_OBSTACLE);
frame(2);EXPECT_EQ(at(),FREE_SPACE);
}
TEST_F(DepthEvidenceLayerTest, MarkingDropsPointsInTheImageBorder) {
frameCloud(.62,-.01f,-.49f,.62f);EXPECT_NE(at(),LETHAL_OBSTACLE); // v = 0.97 px
frameCloud(.62,-.01f,-.45f,.62f);EXPECT_EQ(at(),LETHAL_OBSTACLE); // v = 7.4 px
}
TEST_F(DepthEvidenceLayerTest, EvidenceSurvivesRollingShift) {
frameCloud(.62,-.01f,-.45f,.62f);ASSERT_EQ(at(),LETHAL_OBSTACLE);
layer.updateOrigin(-1.5,-2);EXPECT_EQ(at(),LETHAL_OBSTACLE);
frame(2);EXPECT_EQ(at(),FREE_SPACE);
}
TEST_F(DepthEvidenceLayerTest, AStillVisibleObjectIsNeverCertifiedFree) {
frameCloud(.62,-.01f,-.45f,.62f);ASSERT_EQ(at(),LETHAL_OBSTACLE);
for(int i=0;i<3;++i) {frameCloud(.62,-.01f,-.45f,.62f);EXPECT_EQ(at(),LETHAL_OBSTACLE);}
frame(.62);EXPECT_EQ(at(),LETHAL_OBSTACLE); // no marking this frame, surface still seen
}
}
int main(int argc,char**argv) {robot::Time::init();testing::InitGoogleTest(&argc,argv);return RUN_ALL_TESTS();}