11 Commits
Author SHA1 Message Date
janzon eeff4f404a docs: update README with comprehensive system architecture and feature documentation 2026-07-30 11:07:39 +00:00
janzon 4fec030fbf feat: introduce class-specific match and merge thresholds for object fusion 2026-07-08 13:53:35 +00:00
janzon c66fe85b07 refactor: remove YOLO point cloud subscription and buffer in favor of direct message processing 2026-07-08 10:22:16 +00:00
janzon 449c187d6f feat: add TensorRT engine support and upgrade to ROI-based batch inference for improved object localization performance 2026-07-08 10:00:17 +00:00
janzon 058aa60687 feat: optimize inference with half-precision support, device-specific configuration, and torch.no_grad wrappers for object detection and localization 2026-07-03 11:15:10 +00:00
janzon 14637c2141 feat: propagate pipeline start timestamp through frame_id to track end-to-end latency in logs 2026-07-03 11:06:27 +00:00
janzon 6b144fca2a feat: add parameter and logic to filter small occupied regions as clutter during room segmentation 2026-07-03 10:54:36 +00:00
janzon 92db7492ef feat: add visualization support for segmented room boundaries and labels via MarkerArray publisher 2026-07-03 10:41:29 +00:00
janzon 899cc874c9 refactor: rename ROS 2 package from scene_graph_room_classification to scene_graph_generation_pipeline 2026-07-03 10:19:02 +00:00
janzon a8fb53d03a Merge branch 'extra_schicht' 2026-07-03 10:06:00 +00:00
janzon 4762b087de chore: add .vscode/ directory to gitignore 2026-07-03 10:05:00 +00:00
33 changed files with 837 additions and 270 deletions
+304 -66
View File
@@ -1,94 +1,332 @@
# A ROS Package for the Creation of a 3D Scene Graphs Utilizing Room Classification
# Scene Graph Generation Pipeline for ROS 2
<img src="images/live.png" alt="drawing" width="600"/>
A ROS 2 package for real-time creation, fusion, and visualization of dynamic hierarchical **3D Scene Graphs** integrating 3D object localization, room segmentation, and room classification.
## Description
This ROS packages enables the creation of a hierarchical 3D scene graph during runtime. In contrast to other solutions, rooms are segmented, classified and added as nodes as well.
A robot using this package has to be equipped with a camera that provides an RGB stream, as well as a depth stream. Optimally, the robot is equipped with a 360° laser scanner.
The package generates a 3D scene graph and comes with tools to visualize it using RViz.
<p center="align">
<img src="images/live.png" alt="Scene Graph Live RViz Visualization" width="700"/>
</p>
![Caption for the picture.](images/overview.png?raw=true)
---
### Image Segmentation Module
Segments the current image from the RGB stream using YOLOv9 after synchronizing and publishes 2D object bounding boxes.
## Overview
#### Subscribers
- RGB input stream: `/camera/color/image_raw` using `sensor_msgs/Image` messages
- Depth input stream: `/camera/depth/points` using `sensor_msgs/PointCloud2` messages
- Odometry input: `/camera/color/odom` using `nav_msgs/Odometry` messages
This repository provides a complete ROS 2 pipeline for generating a 3D hierarchical scene graph during robot navigation. Unlike traditional mapping solutions, this pipeline segments and classifies rooms in real time, placing 3D objects, rooms, and structural relationships into a unified graph representation.
#### Publishers
- Synchronized RGB stream: `/scene_graph/color/image_raw` using `sensor_msgs/Image` messages
- Synchronized depth stream: `/scene_graph/depth/points` using `sensor_msgs/PointCloud2` messages
- Synchronized odometry stream: `/scene_graph/odom` using `nav_msgs/Odometry` messages
- Detected objects in current frame: `/scene_graph/detected_objects` using `scene_graph/DetectedObjects` messages
The scene graph hierarchy consists of:
1. **Building Node (Root)**: Represents the overall structure / environment centroid.
2. **Room Nodes (Intermediate)**: Polygon-bounded spaces classified by functional usage (e.g., kitchen, office, bedroom, bathroom).
3. **Object Nodes (Leaf)**: 3D bounding boxes and point clouds of localized objects (e.g., chair, table, monitor, sink).
### Object Localization Module
Places the detected objects in 3D global space using the robot's odometry.
<p center="align">
<img src="images/overview.png" alt="Pipeline Overview Architecture" width="750"/>
</p>
#### Subscribers
- Synchronized RGB stream: `/scene_graph/color/image_raw` using `sensor_msgs/Image` messages
- Synchronized depth stream: `/scene_graph/depth/points` using `sensor_msgs/PointCloud2` messages
- Synchronized odometry stream: `/scene_graph/odom` using `nav_msgs/Odometry` messages
- Detected objects in current frame: `/scene_graph/detected_objects` using `scene_graph/DetectedObjects` messages
---
#### Publishers
- Synchronized RGB stream: `/scene_graph/seen_graph_objects` using `scene_graph/GraphObjects` messages
## Features
### Room Classification Module
Classifies a single room utilizing a Random Forest Classifier on the base of given objects in that room.
- **Open-Vocabulary 2D Object Detection**: Powered by [YOLO-World](https://docs.ultralytics.com/models/yolo-world/) for zero-shot object recognition from RGB camera streams.
- **Fast 3D Object Localization**: Combines [FastSAM](https://docs.ultralytics.com/models/fast-sam/) instance segmentation with depth imagery, camera intrinsics, and TF transforms to construct accurate 3D object bounding boxes and point clouds.
- **Occupancy-Based Room Segmentation**: Uses distance-transform and watershed segmentation algorithms on 2D occupancy maps (`/rtabmap/map`) to extract room polygon boundaries.
- **Object-Based Room Classification**: Applies a pre-trained Random Forest model (`rf_classifier.pkl` mapped to MPcat40 categories) to predict room labels based on object composition within each room.
- **Real-Time Graph Fusion & Tracking**: Backed by NetworkX, maintaining 3D IoU data association, room containment reasoning, and dynamic graph updates upon RTAB-Map SLAM loop closure events.
- **RTAB-Map SLAM Integration**: Works out-of-the-box with RTAB-Map SLAM for real-time localization and global map graph optimization.
- **RViz2 Visualization**: Real-time rendering of graph nodes (building, rooms, objects), relationships (edges), object bounding boxes, trajectories, and text labels.
#### Subscribers
- Objects in give room: `/scene/graph/room_with_objects` using `scene_graph/RoomWithObjects` messages
---
#### Publishers
- Classified room label: `/scene_graph/classified_room` using `scene_graph/ClassifiedRoom` messages
## Pipeline Architecture & Nodes
### Graph Management Module
Iteratively generates a 3D scene graph at runtime. Publishes messages to visualize the graph
The pipeline consists of six primary ROS 2 nodes:
#### Subscribers
- 3D bounding boxes of seen objects in the frame: `/scene_graph/seen_graph_objects` using `scene_graph/GraphObjects` messages
- Polygons of segmented rooms: `/scene_graph/rooms` using `scene_graph/RoomPolygonList` messages
- Label of classified room: `/scene_graph/classified_room` using `scene_graph/ClassifiedRoom` messages
```
+-------------------------+
| Sensors / SLAM |
| (RGB-D, Odom, /scan) |
+------------+------------+
|
+----------------------+----------------------+
| | |
v v v
+--------------------+ +------------------+ +-------------------+
| object_detection | | RTAB-Map SLAM | | odom_vizualization|
| _node (YOLO-World) | | (/rtabmap/map) | | _node (TF Filter) |
+---------+----------+ +--------+---------+ +-------------------+
| |
v v
+--------------------+ +------------------+
|object_localization | |room_segmentation |
| _node (FastSAM) | | _node |
+---------+----------+ +--------+---------+
| |
+-----------+-----------+
|
v
+--------------------------+
| scene_graph_fusion_node |
| (NetworkX 3D Graph) |
+------------+-------------+
|
v
+--------------------------+
| room_classification_node |
| (Random Forest / MPcat) |
+--------------------------+
```
#### Publishers
- Objects in the graph: `scene_graph/graph_objects` using `scene_graph/GraphObjects` messages
- Objects in a given room to be classified: `/scene/graph/room_with_objects` using `scene_graph/RoomWithObjects` messages
- Visualization of object bounding boxes: `/scene_graph/viz/object_bbox_marker` using `visualization_msgs/MarkerArray` messages
- Visualization of room nodes: `/scene_graph/viz/room_markers` using `visualization_msgs/MarkerArray` messages
- Visualization of building nodes: `/scene_graph/viz/building_markers` using `visualization_msgs/MarkerArray` messages
- Visualization of edges: `/scene_graph/viz/line_markers` using `visualization_msgs/MarkerArray` messages
- Visualization of node labels: `/scene_graph/viz/text_markers` using `visualization_msgs/MarkerArray` messages
### 1. Object Detection Node (`object_detection_node`)
Performs open-vocabulary object detection on incoming RGB camera frames using YOLO-World.
- **Subscribers**:
- `/camera/color/image_raw` (`sensor_msgs/msg/Image`)
- `/camera/depth/image_raw` (`sensor_msgs/msg/Image`)
- `/odom` (`nav_msgs/msg/Odometry`)
- **Publishers**:
- `/scene_graph/sync/color/image_raw` (`sensor_msgs/msg/Image`)
- `/scene_graph/sync/depth/image_raw` (`sensor_msgs/msg/Image`)
- `/scene_graph/sync/odom` (`nav_msgs/msg/Odometry`)
- `/scene_graph/yolo` (`scene_graph_interfaces/msg/ObjectList`)
- `/scene_graph/debug/yolo` (`sensor_msgs/msg/Image`)
### 2. Object Localization Node (`object_localization_node`)
Computes 3D global bounding boxes and extracts object point clouds using FastSAM segmentation and camera intrinsics.
- **Subscribers**:
- `/camera/depth/camera_info` (`sensor_msgs/msg/CameraInfo`)
- `/scene_graph/sync/color/image_raw` (`sensor_msgs/msg/Image`)
- `/scene_graph/sync/depth/image_raw` (`sensor_msgs/msg/Image`)
- `/scene_graph/yolo` (`scene_graph_interfaces/msg/ObjectList`)
- **Publishers**:
- `/bounding_boxes_3d/yolo` (`scene_graph_interfaces/msg/Object3DBoundingBoxList`)
- `/object_clouds/yolo` (`sensor_msgs/msg/PointCloud2`)
- `/scene_graph/viz/current_bounding_boxes_3d` (`visualization_msgs/msg/MarkerArray`)
- `/bounding_boxes_3d/point_cloud_markers` (`visualization_msgs/msg/MarkerArray`)
- `/scene_graph/debug/depth_colored`, `/scene_graph/debug/segmented_rgb`, `/scene_graph/debug/segments_overlay` (`sensor_msgs/msg/Image`)
### 3. Room Segmentation Node (`room_segmentation_node`)
Segments 2D occupancy grid maps generated by SLAM into distinct room polygons.
- **Subscribers**:
- `/rtabmap/map` (`nav_msgs/msg/OccupancyGrid`)
- **Publishers**:
- `/scene_graph/rooms` (`scene_graph_interfaces/msg/RoomPolygonList`)
- `/scene_graph/viz/rooms` (`visualization_msgs/msg/MarkerArray`)
### 4. Room Classification Node (`room_classification_node`)
Classifies room functionality based on object types inside each segmented room boundary using a Random Forest classifier.
- **Subscribers**:
- `/scene/graph/room_with_objects` (`scene_graph_interfaces/msg/RoomWithObjects`)
- **Publishers**:
- `/scene_graph/classified_room` (`scene_graph_interfaces/msg/ClassifiedRoom`)
### 5. Scene Graph Fusion Node (`scene_graph_fusion_node`)
Maintains the hierarchical graph structure, handles object fusion and tracking (3D IoU), processes SLAM loop closure updates, and assigns objects to room nodes.
- **Subscribers**:
- `/bounding_boxes_3d/yolo` (`scene_graph_interfaces/msg/Object3DBoundingBoxList`)
- `/scene_graph/rooms` (`scene_graph_interfaces/msg/RoomPolygonList`)
- `/scene_graph/classified_room` (`scene_graph_interfaces/msg/ClassifiedRoom`)
- `/rtabmap/info` (`rtabmap_msgs/msg/Info`)
- `/rtabmap/mapGraph` (`rtabmap_msgs/msg/MapGraph`)
- **Publishers**:
- `/scene/graph/room_with_objects` (`scene_graph_interfaces/msg/RoomWithObjects`)
- `/scene_graph/viz/object_bbox_marker` (`visualization_msgs/msg/MarkerArray`)
- `/scene_graph/viz/room_markers` (`visualization_msgs/msg/MarkerArray`)
- `/scene_graph/viz/building_markers` (`visualization_msgs/msg/MarkerArray`)
- `/scene_graph/viz/line_markers` (`visualization_msgs/msg/MarkerArray`)
- `/scene_graph/viz/text_markers` (`visualization_msgs/msg/MarkerArray`)
### 6. Odom Visualization & TF Node (`odom_vizualization_node`)
Handles coordinate transform filtering, forwards static TFs with TRANSIENT_LOCAL durability, and publishes trajectory visualization markers.
- **Subscribers**: `/tf_old`, `/tf_static_old`, `/rtabmap/info`, `/rtabmap/mapGraph`
- **Publishers**: `/tf`, `/tf_static`, `/scene_graph/viz/robot_pose`, `/scene_graph/viz/trajectory`
---
## Prerequisites
- ROS Noetic on Ubuntu 20.04 LTS
- Camera that provides RGB- and depth-streams (e.g. Orbbec Astra)
- High-FOV laser scanner
- Robot compatible with ROS that comes with an IMU
- **Operating System**: Ubuntu 22.04 LTS
- **ROS Version**: ROS 2 Humble Hawksbill
- **Python**: Python 3.10+
- **Hardware**:
- RGB-D Camera (e.g., Orbbec Astra, Intel RealSense, or Gazebo simulated RGB-D stream)
- 2D Laser Scanner (`/scan`)
- Mobile Robot / Odometry source (`/odom`)
- CUDA-capable GPU (recommended for real-time object detection and FastSAM segmentation)
---
## Installation
To install this package, install the [CGAL](https://www.cgal.org/) library and the [ultralytics](https://docs.ultralytics.com/models/yolov9/) package first. After that, clone and build this package.
```
pip install ultralytics
sudo apt-get install libcgal-dev
cd <your_catkin_workspace>/src
git clone https://github.com/sijanz/scene_graph
cd .. && catkin_make
Follow these step-by-step instructions to set up the workspace, install system dependencies, build RTAB-Map, and install Python dependencies.
### Step 1: Install ROS 2 Humble & Core Build Tools
Ensure ROS 2 Humble is installed and properly sourced:
```bash
source /opt/ros/humble/setup.bash
sudo apt-get update && sudo apt-get install -y \
python3-colcon-common-extensions \
python3-rosdep \
python3-pip \
git
```
### Step 2: Install RTAB-Map & RTAB-Map ROS 2
RTAB-Map is required for SLAM, occupancy grid map generation (`/rtabmap/map`), and map graph updates (`/rtabmap/info`, `/rtabmap/mapGraph`).
#### Option A: Binary Package Installation (Recommended)
Install pre-compiled RTAB-Map packages for ROS 2 Humble via `apt`:
```bash
sudo apt-get update && sudo apt-get install -y \
ros-humble-rtabmap \
ros-humble-rtabmap-ros \
ros-humble-rtabmap-msgs \
ros-humble-rtabmap-launch \
ros-humble-rtabmap-conversions \
ros-humble-rtabmap-util
```
#### Option B: Source Installation (For Custom RTAB-Map Builds)
If you require building RTAB-Map from source inside your ROS 2 workspace:
```bash
cd ~/ros2_ws/src
# Clone RTAB-Map standalone library and ROS 2 package
git clone https://github.com/introlab/rtabmap.git
git clone --branch humble-devel https://github.com/introlab/rtabmap_ros.git
# Install build dependencies for RTAB-Map
sudo apt-get install -y \
ros-humble-rtabmap-otb \
libpcl-dev \
libopencv-dev \
liboctomap-dev
```
### Step 3: Set Up Workspace & Clone Repositories
Create a ROS 2 workspace (if not already created) and clone `scene_graph_generation_pipeline` along with its custom interface package `scene_graph_interfaces`:
```bash
mkdir -p ~/ros2_ws/src
cd ~/ros2_ws/src
# Clone custom message definitions and pipeline
git clone https://github.com/sijanz/scene_graph_interfaces.git
git clone https://github.com/sijanz/scene_graph_generation_pipeline.git
```
### Step 4: Install System Dependencies & Python Requirements
Install required ROS 2 libraries:
```bash
sudo apt-get update && sudo apt-get install -y \
ros-humble-cv-bridge \
ros-humble-tf2-ros \
ros-humble-message-filters \
ros-humble-visualization-msgs \
ros-humble-nav-msgs \
ros-humble-sensor-msgs \
ros-humble-geometry-msgs
```
Install Python package requirements for object detection, segmentation, geometry processing, and graph management:
```bash
cd ~/ros2_ws/src/scene_graph_generation_pipeline
pip3 install -r requirements.txt
```
*Note: `requirements.txt` installs packages including `ultralytics>=8.2.0`, `opencv-python`, `networkx`, `scipy`, `shapely`, `open3d`, `huggingface-hub`, and `clip`.*
### Step 5: Build and Source the Workspace
Initialize `rosdep`, resolve any remaining dependencies, and build the workspace using `colcon`:
```bash
cd ~/ros2_ws
# Update rosdep and install missing package dependencies
rosdep update
rosdep install --from-paths src --ignore-src -r -y
# Build workspace
colcon build --symlink-install
# Source workspace setup
source install/setup.bash
```
---
## Usage
Run the whole scene graph creation pipeline as follows. Use a new terminal window for each command.
### 1. Complete Pipeline with RTAB-Map SLAM & RViz2
Launch RTAB-Map SLAM, all six scene graph pipeline nodes, and pre-configured RViz2 visualization in a single command:
```bash
ros2 launch scene_graph_generation_pipeline scene_graph_rtabmap_launch.py use_sim_time:=true
```
rosrun scene_graph ros_yolo_node.py
### 2. Standalone Pipeline (With Existing SLAM / Bag Playback)
If RTAB-Map or another SLAM node is already running or playing back a ROS 2 bag file:
```bash
ros2 launch scene_graph_generation_pipeline scene_graph_launch.py use_sim_time:=true
```
### 3. Running Nodes Individually
Alternatively, launch each node separately in individual terminal windows:
```bash
# Sourcing workspace in each terminal
source ~/ros2_ws/install/setup.bash
# Terminal 1: 2D Object Detection (YOLO-World)
ros2 run scene_graph_generation_pipeline object_detection_node
# Terminal 2: 3D Object Localization (FastSAM)
ros2 run scene_graph_generation_pipeline object_localization_node
# Terminal 3: Room Segmentation (Distance-Transform / Watershed)
ros2 run scene_graph_generation_pipeline room_segmentation_node
# Terminal 4: Room Classification (Random Forest)
ros2 run scene_graph_generation_pipeline room_classification_node
# Terminal 5: Scene Graph Fusion Core
ros2 run scene_graph_generation_pipeline scene_graph_fusion_node
# Terminal 6: Odom Visualization & TF Filter
ros2 run scene_graph_generation_pipeline odom_vizualization_node
```
rosrun scene_graph object_localization_node
---
## Custom Messages (`scene_graph_interfaces`)
The pipeline relies on custom ROS 2 messages defined in `scene_graph_interfaces`:
- `ObjectList.msg`: 2D bounding boxes and class labels from object detection.
- `Object3DBoundingBox.msg` / `Object3DBoundingBoxList.msg`: 3D bounding box coordinates, extents, and spatial centroids.
- `RoomPolygon.msg` / `RoomPolygonList.msg`: Vertices of segmented room boundaries.
- `RoomWithObjects.msg`: Association list mapping room polygons to contained 3D objects.
- `ClassifiedRoom.msg`: Predicted room classification label and probability scores.
---
## Testing & Verification
To run unit and lint tests for the pipeline:
```bash
cd ~/ros2_ws
colcon test --packages-select scene_graph_generation_pipeline
colcon test-result --all
```
```
rosrun scene_graph room_classification_node
```
```
rosrun scene_graph graph_management_node
Or run Python tests directly with PyTest:
```bash
cd ~/ros2_ws/src/scene_graph_generation_pipeline
pytest test/
```
+6 -6
View File
@@ -19,7 +19,7 @@ def generate_launch_description():
# Object Detection Node
object_detection_node = Node(
package='scene_graph_room_classification',
package='scene_graph_generation_pipeline',
executable='object_detection_node',
name='object_detection_node',
output='screen',
@@ -29,7 +29,7 @@ def generate_launch_description():
# Object Localization Node
object_localization_node = Node(
package='scene_graph_room_classification',
package='scene_graph_generation_pipeline',
executable='object_localization_node',
name='object_localization_node',
output='screen',
@@ -39,7 +39,7 @@ def generate_launch_description():
# Scene Graph Fusion Node
scene_graph_fusion_node = Node(
package='scene_graph_room_classification',
package='scene_graph_generation_pipeline',
executable='scene_graph_fusion_node',
name='scene_graph_fusion_node',
output='screen',
@@ -49,7 +49,7 @@ def generate_launch_description():
# Odom Vizualization Node
odom_vizualization_node = Node(
package='scene_graph_room_classification',
package='scene_graph_generation_pipeline',
executable='odom_vizualization_node',
name='odom_vizualization_node',
output='screen',
@@ -59,7 +59,7 @@ def generate_launch_description():
# Room Classification Node
room_classification_node = Node(
package='scene_graph_room_classification',
package='scene_graph_generation_pipeline',
executable='room_classification_node',
name='room_classification_node',
output='screen',
@@ -69,7 +69,7 @@ def generate_launch_description():
# Room Segmentation Node
room_segmentation_node = Node(
package='scene_graph_room_classification',
package='scene_graph_generation_pipeline',
executable='room_segmentation_node',
name='room_segmentation_node',
output='screen',
+7 -7
View File
@@ -39,7 +39,7 @@ def generate_launch_description():
# Object Detection Node
object_detection_node = Node(
package='scene_graph_room_classification',
package='scene_graph_generation_pipeline',
executable='object_detection_node',
name='object_detection_node',
output='screen',
@@ -49,7 +49,7 @@ def generate_launch_description():
# Object Localization Node
object_localization_node = Node(
package='scene_graph_room_classification',
package='scene_graph_generation_pipeline',
executable='object_localization_node',
name='object_localization_node',
output='screen',
@@ -59,7 +59,7 @@ def generate_launch_description():
# Scene Graph Fusion Node
scene_graph_fusion_node = Node(
package='scene_graph_room_classification',
package='scene_graph_generation_pipeline',
executable='scene_graph_fusion_node',
name='scene_graph_fusion_node',
output='screen',
@@ -69,7 +69,7 @@ def generate_launch_description():
# Odom Visualization Node
odom_vizualization_node = Node(
package='scene_graph_room_classification',
package='scene_graph_generation_pipeline',
executable='odom_vizualization_node',
name='odom_vizualization_node',
output='screen',
@@ -79,7 +79,7 @@ def generate_launch_description():
# Room Classification Node
room_classification_node = Node(
package='scene_graph_room_classification',
package='scene_graph_generation_pipeline',
executable='room_classification_node',
name='room_classification_node',
output='screen',
@@ -89,7 +89,7 @@ def generate_launch_description():
# Room Segmentation Node
room_segmentation_node = Node(
package='scene_graph_room_classification',
package='scene_graph_generation_pipeline',
executable='room_segmentation_node',
name='room_segmentation_node',
output='screen',
@@ -102,7 +102,7 @@ def generate_launch_description():
package='rviz2',
executable='rviz2',
name='rviz2',
arguments=['-d', '/home/developer/workspace/ros2_ws/src/scene_graph_room_classification/rviz/graph_video.rviz'],
arguments=['-d', '/home/developer/workspace/ros2_ws/src/scene_graph_generation_pipeline/rviz/graph_video.rviz'],
parameters=[{'use_sim_time': True}],
additional_env={'DISPLAY': ':1'}
)
+1 -1
View File
@@ -1,7 +1,7 @@
<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
<name>scene_graph_room_classification</name>
<name>scene_graph_generation_pipeline</name>
<version>0.0.0</version>
<description>TODO: Package description</description>
<maintainer email="root@todo.todo">root</maintainer>
@@ -115,6 +115,8 @@ class ObjectDetectionNode(Node):
depth_msg (sensor_msgs/Image): Depth image
odom_msg (nav_msgs/Odometry): Robot odometry/pose information
"""
pipeline_start_wall = time.time()
# Convert ROS Image message to OpenCV format (BGR color space)
try:
cv_image = self.bridge.imgmsg_to_cv2(ros_image, desired_encoding='bgr8')
@@ -147,6 +149,7 @@ class ObjectDetectionNode(Node):
yolo_objects_msg = ObjectList()
yolo_objects_msg.objects = yolo_detected_objects
yolo_objects_msg.header.stamp = current_time
yolo_objects_msg.header.frame_id = f"{ros_image.header.frame_id}|{pipeline_start_wall}"
self.yolo_detected_objects_pub.publish(yolo_objects_msg)
def _detect_with_yolo(self, cv_image):
@@ -84,6 +84,7 @@ class ObjectLocalizationNode(Node):
self.pub_pc_markers_yolo = self.create_publisher(MarkerArray, '/bounding_boxes_3d/point_cloud_markers', 10)
self.pub_debug_depth_colored = self.create_publisher(Image, '/scene_graph/debug/depth_colored', 10)
self.pub_debug_segmented_rgb = self.create_publisher(Image, '/scene_graph/debug/segmented_rgb', 10)
self.pub_debug_segments_overlay = self.create_publisher(Image, '/scene_graph/debug/segments_overlay', 10)
self.get_logger().info("Object Localization Node Initialized. Waiting for data...")
@@ -168,10 +169,16 @@ class ObjectLocalizationNode(Node):
try:
objects = yolo_msg.objects
pipeline_start_wall = ""
frame_parts = yolo_msg.header.frame_id.split('|')
if len(frame_parts) > 1:
pipeline_start_wall = frame_parts[1]
self.process_segmentation_pipeline(
rgb_msg, depth_msg, objects,
self.pub_bbox_yolo, self.pub_cloud_yolo, self.pub_markers_yolo, self.pub_pc_markers_yolo, source_name="YOLO",
target_list_class=Object3DBoundingBoxList, target_item_class=Object3DBoundingBox)
target_list_class=Object3DBoundingBoxList, target_item_class=Object3DBoundingBox,
pipeline_start_wall=pipeline_start_wall)
finally:
with self.lock:
self.is_processing = False
@@ -180,7 +187,7 @@ class ObjectLocalizationNode(Node):
def process_segmentation_pipeline(self, rgb_msg, depth_msg, objects,
pub_bbox, pub_cloud, pub_markers, pub_pc_markers, source_name,
target_list_class, target_item_class):
target_list_class, target_item_class, pipeline_start_wall=""):
if self.intrinsics is None:
self.get_logger().warn(f"[{source_name}] Waiting for Camera Info...", throttle_duration_sec=2.0)
return
@@ -286,7 +293,10 @@ class ObjectLocalizationNode(Node):
# --- STEP 4: GEOMETRY PROCESSING ---
bbox_list_msg = target_list_class()
bbox_list_msg.header = rgb_msg.header
bbox_list_msg.header.frame_id = "map"
if pipeline_start_wall:
bbox_list_msg.header.frame_id = f"map|{pipeline_start_wall}"
else:
bbox_list_msg.header.frame_id = "map"
marker_array_msg = MarkerArray()
pc_marker_array_msg = MarkerArray()
@@ -552,6 +562,11 @@ class ObjectLocalizationNode(Node):
segmented_msg = self.bridge.cv2_to_imgmsg(segmented_bgr, encoding='bgr8')
segmented_msg.header = rgb_msg.header
self.pub_debug_segmented_rgb.publish(segmented_msg)
# Publish segments overlay debug image
overlay_msg = self.bridge.cv2_to_imgmsg(segmented_bgr, encoding='bgr8')
overlay_msg.header = rgb_msg.header
self.pub_debug_segments_overlay.publish(overlay_msg)
except Exception as e:
self.get_logger().error(f"Failed to publish debug images: {e}")
@@ -0,0 +1,133 @@
import torch
import numpy as np
import os
from ultralytics import SAM, FastSAM
class SamWrapper:
"""Wrapper for Ultralytics SAM/SAM2/FastSAM to handle prompted segmentation via bounding boxes."""
def __init__(self, model_name):
"""
Initializes segmenter model.
Args:
model_name (str): Model name / path (e.g. 'FastSAM-s.pt', 'sam2_b.pt', etc.)
"""
self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
# Auto-resolve / override with pre-compiled local TensorRT engine if present
dir_path = os.path.dirname(os.path.realpath(__file__))
engine_path = os.path.join(dir_path, 'FastSAM-s.engine')
if os.path.exists(engine_path) and "FastSAM" in model_name:
print(f"[SamWrapper] Found local TensorRT engine at {engine_path}. Overriding model {model_name}.")
model_name = engine_path
print(f"[SamWrapper] Loading {model_name} on {self.device}...")
try:
if "FastSAM" in model_name:
self.model = FastSAM(model_name)
else:
self.model = SAM(model_name)
if not str(model_name).endswith('.engine'):
self.model.to(self.device)
print("[SamWrapper] Model loaded successfully.")
except Exception as e:
print(f"[SamWrapper] Error loading model: {e}")
raise e
def predict(self, image, bboxes):
"""Generates segmentation masks based on bounding box prompts using cropped ROI batch inference."""
if not bboxes or len(bboxes) == 0:
return []
img_h, img_w = image.shape[:2]
crops = []
local_bboxes = []
crop_offsets = []
# 1. Generate crops around bounding boxes with a 10% margin
for bbox in bboxes:
x1, y1, x2, y2 = bbox
margin_x = int(0.1 * (x2 - x1))
margin_y = int(0.1 * (y2 - y1))
cx1 = max(0, int(round(x1 - margin_x)))
cy1 = max(0, int(round(y1 - margin_y)))
cx2 = min(img_w, int(round(x2 + margin_x)))
cy2 = min(img_h, int(round(y2 + margin_y)))
if cx2 - cx1 <= 0 or cy2 - cy1 <= 0:
# Handle edge cases with a dummy crop to keep batch size aligned
crop = np.zeros((32, 32, 3), dtype=np.uint8)
local_bbox = [0, 0, 32, 32]
cx1, cy1, cx2, cy2 = 0, 0, 0, 0
else:
crop = image[cy1:cy2, cx1:cx2]
local_bbox = [
x1 - cx1,
y1 - cy1,
x2 - cx1,
y2 - cy1
]
crops.append(crop)
local_bboxes.append(local_bbox)
crop_offsets.append((cx1, cy1, cx2, cy2))
results = []
try:
# 2. Run inference (segment everything) on cropped regions sequentially
# Sequential inference bypasses the TensorRT engine profile batch size limit of 1
for crop in crops:
res = self.model(crop, verbose=False, imgsz=256, retina_masks=True)
results.extend(res)
except Exception as e:
print(f"[SamWrapper] Inference failed: {e}")
return [None] * len(bboxes)
matched_masks = [None] * len(bboxes)
# 3. Filter candidate masks manually per crop using local IoU matching
for i, result in enumerate(results):
cx1, cy1, cx2, cy2 = crop_offsets[i]
if cx2 - cx1 <= 0 or cy2 - cy1 <= 0:
continue
if result.masks is None or len(result.masks) == 0:
continue
masks_tensor = result.masks.data # shape (M, crop_h, crop_w)
local_bbox = local_bboxes[i]
bbox_area = (local_bbox[2] - local_bbox[0]) * (local_bbox[3] - local_bbox[1])
if bbox_area <= 0:
continue
lx1 = max(0, int(round(local_bbox[0])))
ly1 = max(0, int(round(local_bbox[1])))
lx2 = min(result.orig_shape[1], int(round(local_bbox[2])))
ly2 = min(result.orig_shape[0], int(round(local_bbox[3])))
if lx2 <= lx1 or ly2 <= ly1:
continue
# Intersect candidates with bbox prompt region and match via IoU
mask_areas = masks_tensor[:, ly1:ly2, lx1:lx2].sum(dim=(1, 2))
full_mask_areas = masks_tensor.sum(dim=(1, 2))
union = bbox_area + full_mask_areas - mask_areas
iou = mask_areas / (union + 1e-6)
best_idx = torch.argmax(iou).item()
best_iou = iou[best_idx].item()
if best_iou > 0.3:
mask_np = masks_tensor[best_idx].cpu().numpy().astype(bool)
# Map mask back to the original full image coordinates
full_mask = np.zeros((img_h, img_w), dtype=bool)
full_mask[cy1:cy2, cx1:cx2] = mask_np
matched_masks[i] = full_mask
return matched_masks
@@ -410,7 +410,7 @@ class OdomVisualizationNode(Node):
marker.scale.y = 1.0
marker.scale.z = 1.0
marker.mesh_resource = "package://scene_graph_room_classification/meshes/panther/base.dae"
marker.mesh_resource = "package://scene_graph_generation_pipeline/meshes/panther/base.dae"
marker.mesh_use_embedded_materials = True
marker.color.r = 1.0
@@ -456,7 +456,7 @@ class OdomVisualizationNode(Node):
marker.scale.y = 1.0
marker.scale.z = 1.0
marker.mesh_resource = f"package://scene_graph_room_classification/meshes/{wheel_type}/{prefix}_wheel.dae"
marker.mesh_resource = f"package://scene_graph_generation_pipeline/meshes/{wheel_type}/{prefix}_wheel.dae"
marker.mesh_use_embedded_materials = True
marker.color.r = 0.8
@@ -37,7 +37,7 @@ class RoomClassificationNode(Node):
# Load the classifier model
try:
package_share_dir = get_package_share_directory('scene_graph_room_classification')
package_share_dir = get_package_share_directory('scene_graph_generation_pipeline')
model_path = os.path.join(package_share_dir, 'model', 'rf_classifier.pkl')
if not os.path.exists(model_path):
model_path = os.path.join(os.path.dirname(__file__), 'rf_classifier.pkl')
@@ -168,6 +168,7 @@ class RoomClassificationNode(Node):
input_vector = [0] * len(classification_utils.get_filtered_mpcat40_list())
for do in detected_objects:
do = do.lower()
if do in self.mpcat40_mapping:
do = self.mpcat40_mapping[do]
@@ -10,10 +10,13 @@ from rclpy.parameter import Parameter
from nav_msgs.msg import OccupancyGrid
from geometry_msgs.msg import Point
from scene_graph_interfaces.msg import RoomPolygon, RoomPolygonList
from visualization_msgs.msg import Marker, MarkerArray
class RoomSegmentationNode(Node):
"""
ROS2 Node for room segmentation from an occupancy grid map.
It subscribes to rtabmap's grid map topic, runs a distance transform and watershed
based segmentation algorithm, and publishes room polygons to the scene graph.
"""
@@ -26,20 +29,60 @@ class RoomSegmentationNode(Node):
# Declare and read parameters
self.declare_parameter('map_topic', '/rtabmap/map')
self.declare_parameter('rooms_topic', '/scene_graph/rooms')
self.declare_parameter('min_room_area', 2.0) # Minimum room area in square meters
self.declare_parameter('min_room_radius', 0.8) # Expected room radius in meters
self.declare_parameter('simplification_tolerance', 0.1) # Polygon simplification tolerance in meters
self.declare_parameter('process_min_interval', 2.0) # Rate limit in seconds
self.declare_parameter('rooms_viz_topic', '/scene_graph/viz/rooms')
self.declare_parameter('min_room_area', 2.0) # Min area (sq meters)
self.declare_parameter('min_room_radius', 0.8) # Min radius (meters)
self.declare_parameter('max_clutter_size', 1.0) # Max clutter (sq m)
# Polygon simplification tolerance in meters:
self.declare_parameter('simplification_tolerance', 0.1)
self.declare_parameter('process_min_interval', 2.0) # Rate limit (sec)
self.map_topic = self.get_parameter('map_topic').get_parameter_value().string_value
self.rooms_topic = self.get_parameter('rooms_topic').get_parameter_value().string_value
self.min_room_area = self.get_parameter('min_room_area').get_parameter_value().double_value
self.min_room_radius = self.get_parameter('min_room_radius').get_parameter_value().double_value
self.simplification_tolerance = self.get_parameter('simplification_tolerance').get_parameter_value().double_value
self.process_min_interval = self.get_parameter('process_min_interval').get_parameter_value().double_value
self.map_topic = (
self.get_parameter('map_topic')
.get_parameter_value()
.string_value
)
self.rooms_topic = (
self.get_parameter('rooms_topic')
.get_parameter_value()
.string_value
)
self.rooms_viz_topic = (
self.get_parameter('rooms_viz_topic')
.get_parameter_value()
.string_value
)
self.min_room_area = (
self.get_parameter('min_room_area')
.get_parameter_value()
.double_value
)
self.min_room_radius = (
self.get_parameter('min_room_radius')
.get_parameter_value()
.double_value
)
self.max_clutter_size = (
self.get_parameter('max_clutter_size')
.get_parameter_value()
.double_value
)
self.simplification_tolerance = (
self.get_parameter('simplification_tolerance')
.get_parameter_value()
.double_value
)
self.process_min_interval = (
self.get_parameter('process_min_interval')
.get_parameter_value()
.double_value
)
self.get_logger().info(f"Subscribing to map topic: {self.map_topic}")
self.get_logger().info(f"Publishing rooms to: {self.rooms_topic}")
self.get_logger().info(
f"Publishing room markers to: {self.rooms_viz_topic}"
)
# Subscribe to occupancy grid
self.map_sub = self.create_subscription(
@@ -56,6 +99,13 @@ class RoomSegmentationNode(Node):
10
)
# Publisher for room visualization markers
self.rooms_viz_pub = self.create_publisher(
MarkerArray,
self.rooms_viz_topic,
10
)
self.last_process_time = 0.0
def map_callback(self, msg: OccupancyGrid) -> None:
@@ -70,19 +120,33 @@ class RoomSegmentationNode(Node):
self.get_logger().warn("Received empty occupancy grid, skipping.")
return
self.get_logger().info(f"Received map of size {msg.info.width}x{msg.info.height} (resolution: {msg.info.resolution} m/px)")
self.get_logger().info(
f"Received map of size {msg.info.width}x{msg.info.height} "
f"(resolution: {msg.info.resolution} m/px)"
)
# Convert to 2D numpy array
width = msg.info.width
height = msg.info.height
resolution = msg.info.resolution
# OccupancyGrid values: 0=free, 100=occupied, -1=unknown
grid = np.array(msg.data, dtype=np.int8).reshape((height, width))
# Create binary mask representing free space (value == 0)
free_mask = (grid == 0).astype(np.uint8) * 255
# Identify and fill small isolated occupied space (clutter/objects)
non_free_mask = cv2.bitwise_not(free_mask)
num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(
non_free_mask
)
max_clutter_size_px = self.max_clutter_size / (resolution ** 2)
for i in range(1, num_labels):
area = stats[i, cv2.CC_STAT_AREA]
if area < max_clutter_size_px:
free_mask[labels == i] = 255
# Morphological clean up to fill minor noise/gaps in walls without bridging doors
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
free_cleaned = cv2.morphologyEx(free_mask, cv2.MORPH_CLOSE, kernel)
@@ -136,7 +200,7 @@ class RoomSegmentationNode(Node):
rooms_list_msg = RoomPolygonList()
rooms_list_msg.header = msg.header
min_room_area_px = self.min_room_area / (resolution ** 2)
epsilon = self.simplification_tolerance / resolution
@@ -176,7 +240,89 @@ class RoomSegmentationNode(Node):
rooms_list_msg.rooms.append(room_poly)
self.rooms_pub.publish(rooms_list_msg)
self.get_logger().info(f"Successfully segmented and published {len(rooms_list_msg.rooms)} rooms.")
# Publish visualization markers for the segmented rooms
marker_array = MarkerArray()
# Add a DELETEALL marker to clear previous markers in RViz
delete_marker = Marker()
delete_marker.header = msg.header
delete_marker.action = Marker.DELETEALL
marker_array.markers.append(delete_marker)
# Curated beautiful color palette (RGBA)
curated_colors = [
(0.12, 0.53, 0.90, 0.8), # Sleek Blue
(0.90, 0.22, 0.27, 0.8), # Vibrant Coral/Red
(0.18, 0.80, 0.44, 0.8), # Emerald Green
(0.95, 0.77, 0.06, 0.8), # Sun Yellow
(0.61, 0.35, 0.71, 0.8), # Amethyst Purple
(0.98, 0.50, 0.15, 0.8), # Bright Orange
(0.08, 0.75, 0.75, 0.8), # Turquoise/Teal
(0.92, 0.40, 0.60, 0.8), # Rose Pink
]
for idx, room in enumerate(rooms_list_msg.rooms):
if not room.points:
continue
color = curated_colors[idx % len(curated_colors)]
# 1. Boundary Marker (LINE_STRIP)
boundary_marker = Marker()
boundary_marker.header = msg.header
boundary_marker.ns = "room_boundaries"
boundary_marker.id = idx
boundary_marker.type = Marker.LINE_STRIP
boundary_marker.action = Marker.ADD
boundary_marker.pose.orientation.w = 1.0
boundary_marker.scale.x = 0.05 # Line thickness
boundary_marker.color.r = color[0]
boundary_marker.color.g = color[1]
boundary_marker.color.b = color[2]
boundary_marker.color.a = color[3]
# Copy all points and close the loop by appending the first point at the end
for pt in room.points:
boundary_marker.points.append(pt)
boundary_marker.points.append(room.points[0])
marker_array.markers.append(boundary_marker)
# 2. Centroid Label (TEXT_VIEW_FACING)
cx = sum(p.x for p in room.points) / len(room.points)
cy = sum(p.y for p in room.points) / len(room.points)
label_marker = Marker()
label_marker.header = msg.header
label_marker.ns = "room_labels"
label_marker.id = idx
label_marker.type = Marker.TEXT_VIEW_FACING
label_marker.action = Marker.ADD
label_marker.pose.position.x = cx
label_marker.pose.position.y = cy
label_marker.pose.position.z = 0.2 # Elevate text slightly above the map floor
label_marker.pose.orientation.w = 1.0
label_marker.scale.z = 0.4 # Text height
label_marker.color.r = 1.0
label_marker.color.g = 1.0
label_marker.color.b = 1.0
label_marker.color.a = 1.0
label_marker.text = f"Room {idx}"
marker_array.markers.append(label_marker)
self.rooms_viz_pub.publish(marker_array)
self.get_logger().info(
f"Successfully segmented and published "
f"{len(rooms_list_msg.rooms)} rooms."
)
def main(args=None) -> None:
rclpy.init(args=args)
@@ -189,5 +335,6 @@ def main(args=None) -> None:
node.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
@@ -38,7 +38,7 @@ from scipy.spatial.transform import Rotation as R
from shapely.geometry import Point as ShapelyPoint, Polygon as ShapelyPolygon
from sensor_msgs_py import point_cloud2
from sensor_msgs.msg import PointCloud2
from scene_graph_room_classification.object_localization.geometry_utils import GeometryUtils
from scene_graph_generation_pipeline.object_localization.geometry_utils import GeometryUtils
@@ -177,10 +177,6 @@ class GraphManagementNode(Node):
self.create_subscription(Object3DBoundingBoxList, '/bounding_boxes_3d/yolo',
self.yolo_bboxes_callback, 10)
# Subscribe to YOLO Object Clouds
self.create_subscription(PointCloud2, '/object_clouds/yolo',
self.yolo_cloud_callback, 10)
# Subscrive to RT-DETR Bounding Boxes and Attributes
self.create_subscription(FunObject3DBoundingBoxList, '/bounding_boxes_3d/rtdetr',
self.rtdetr_bboxes_callback, 10)
@@ -308,8 +304,6 @@ class GraphManagementNode(Node):
self.keyframe_poses_cache = {} # Cached map of keyframe_id -> 4x4 numpy matrix
# Buffer-Helper (Queues for synchronization)
self.yolo_bboxes_buffer = {} # maps timestamp (float) to msg
self.yolo_clouds_buffer = {} # maps timestamp (float) to cloud_np
self.rtdetr_bboxes_buffer = {} # maps timestamp (float) to msg
self.rtdetr_clouds_buffer = {} # maps timestamp (float) to cloud_np
@@ -324,6 +318,79 @@ class GraphManagementNode(Node):
self.functional_parent_threshold = 0.5
self.object_node_merge_threshold = 1.2
# Class-specific match and merge thresholds: (match_threshold, merge_threshold)
self.class_threshold_configs = {
# SMALL ITEMS (Match: 0.2m, Merge: 0.3m)
"cup": (0.2, 0.3),
"bottle": (0.2, 0.3),
"mug": (0.2, 0.3),
"glass": (0.2, 0.3),
"bowl": (0.2, 0.3),
"plate": (0.2, 0.3),
"mouse": (0.2, 0.3),
"light switch": (0.2, 0.3),
"power outlet": (0.2, 0.3),
"book": (0.2, 0.3),
"shoe": (0.2, 0.3),
"folder": (0.2, 0.3),
"notebook": (0.2, 0.3),
"dish": (0.2, 0.3),
"vase": (0.2, 0.3),
# MEDIUM ITEMS (Match: 0.4m, Merge: 0.6m)
"keyboard": (0.4, 0.6),
"laptop": (0.4, 0.6),
"desk lamp": (0.4, 0.6),
"lamp": (0.4, 0.6),
"trash can": (0.4, 0.6),
"recycling bin": (0.4, 0.6),
"box": (0.4, 0.6),
"bag": (0.4, 0.6),
"backpack": (0.4, 0.6),
"printer": (0.4, 0.6),
"coffee machine": (0.4, 0.6),
"coffee pot": (0.4, 0.6),
"monitor": (0.4, 0.6),
"microwave": (0.4, 0.6),
"plant": (0.4, 0.6),
"plant pot": (0.4, 0.6),
"fire extinguisher": (0.4, 0.6),
"telephone": (0.4, 0.6),
"speaker": (0.4, 0.6),
# LARGE ITEMS / FURNITURE / INFRASTRUCTURE (Match: 0.8m, Merge: 1.5m)
"table": (0.8, 1.5),
"desk": (0.8, 1.5),
"conference table": (0.8, 1.5),
"reception desk": (0.8, 1.5),
"chair": (0.8, 1.5),
"office chair": (0.8, 1.5),
"couch": (0.8, 1.5),
"cabinet": (0.8, 1.5),
"shelf": (0.8, 1.5),
"cupboard": (0.8, 1.5),
"dresser": (0.8, 1.5),
"wardrobe": (0.8, 1.5),
"closet": (0.8, 1.5),
"drawer": (0.8, 1.5),
"refrigerator": (0.8, 1.5),
"freezer": (0.8, 1.5),
"oven": (0.8, 1.5),
"stove": (0.8, 1.5),
"washing machine": (0.8, 1.5),
"dryer": (0.8, 1.5),
"dishwasher": (0.8, 1.5),
"sink": (0.8, 1.5),
"door": (0.8, 1.5),
"window": (0.8, 1.5),
"stairs": (0.8, 1.5),
"whiteboard": (0.8, 1.5),
"painting": (0.8, 1.5),
"television": (0.8, 1.5),
"radiator": (0.8, 1.5),
"heater": (0.8, 1.5)
}
# Sync / Pairing
self.max_sync_dt_sec = 0.20 # Tolerance between BBoxes and PC msg
self.process_only_if_synced = True
@@ -568,31 +635,9 @@ class GraphManagementNode(Node):
def yolo_bboxes_callback(self, msg):
if len(msg.bbox) == 0:
return
t = GraphManagementNode.stamp_to_sec(msg.header.stamp)
self.yolo_bboxes_buffer[t] = msg
if len(self.yolo_bboxes_buffer) > 20:
oldest = min(self.yolo_bboxes_buffer.keys())
self.yolo_bboxes_buffer.pop(oldest)
self._try_process_yolo()
def yolo_cloud_callback(self, msg: PointCloud2):
"""
Stores the latest YOLO point cloud as an Nx3 NumPy array in the buffer.
"""
try:
cloud_np = GraphManagementNode.pointcloud2_to_xyz_array(msg) # Nx3
if cloud_np.size == 0:
return
t = GraphManagementNode.stamp_to_sec(msg.header.stamp)
self.yolo_clouds_buffer[t] = cloud_np
if len(self.yolo_clouds_buffer) > 20:
oldest = min(self.yolo_clouds_buffer.keys())
self.yolo_clouds_buffer.pop(oldest)
self._try_process_yolo()
except Exception as e:
self.get_logger().warn(f"Error processing the YOLO cloud: {e}")
if not self.graph_updates_allowed:
return
self._process_yolo_bboxes(msg)
def rtdetr_bboxes_callback(self, msg):
if len(msg.bbox) == 0:
@@ -636,23 +681,7 @@ class GraphManagementNode(Node):
return t_bbox, best_t_cloud
return None
def _try_process_yolo(self):
# Cancel if Graph Updates are paused
if not self.graph_updates_allowed:
self.yolo_bboxes_buffer.clear()
self.yolo_clouds_buffer.clear()
return
pair = self._find_matching_pair(self.yolo_bboxes_buffer, self.yolo_clouds_buffer, self.max_sync_dt_sec)
if pair is None:
return
t_bbox, t_cloud = pair
msg = self.yolo_bboxes_buffer.pop(t_bbox)
cloud_np = self.yolo_clouds_buffer.pop(t_cloud)
# Delegate to the actual processing routine
self._process_yolo_bboxes(msg, cloud_np)
def _try_process_rtdetr(self):
# Cancel if Graph Updates are paused
@@ -685,7 +714,7 @@ class GraphManagementNode(Node):
return False
return abs(self.stamp_to_sec(stamp_a) - self.stamp_to_sec(stamp_b)) <= max_dt
def _process_yolo_bboxes(self, msg: Object3DBoundingBoxList, cloud_np):
def _process_yolo_bboxes(self, msg: Object3DBoundingBoxList):
# TIMER FOR LATENCY
proc_start_time = time.perf_counter()
@@ -693,6 +722,16 @@ class GraphManagementNode(Node):
now_timestamp = self.get_current_ros_time_sec()
input_lag = now_timestamp - img_timestamp
# Extract pipeline start wall time from msg.header.frame_id
# if available
pipeline_start_wall = None
frame_id_parts = msg.header.frame_id.split('|')
if len(frame_id_parts) > 1:
try:
pipeline_start_wall = float(frame_id_parts[1])
except ValueError:
pass
# No detections -> nothing to do
if not msg.bbox:
return
@@ -714,11 +753,8 @@ class GraphManagementNode(Node):
# Get AABB projection for cloud cutting / filtering
pmin, pmax = self.get_aabb(entry.bounding_box)
# 4) Crop points inside the AABB (object-specific sub cloud)
obj_cloud = self.cut_points_in_aabb(
cloud_np, pmin, pmax,
margin=self.bbox_margin_m
)
# 4) Extract object-specific point cloud directly from the consolidated message
obj_cloud = GraphManagementNode.pointcloud2_to_xyz_array(entry.point_cloud)
# Skip tiny clouds (unstable centroids / noisy detections)
if obj_cloud.shape[0] < self.min_points_yolo:
@@ -731,10 +767,11 @@ class GraphManagementNode(Node):
closest_k_id = self.get_closest_keyframe_id(detection_time)
# 5) Find a matching object node (by label + spatial proximity + 3D IoU)
match_threshold, _ = self.get_class_thresholds(label)
match_id = self._find_closest_object_node(
centroid,
label=label,
threshold=self.object_match_threshold,
threshold=match_threshold,
query_bbox=[pmin, pmax]
)
@@ -751,10 +788,21 @@ class GraphManagementNode(Node):
obj_node.point_cloud = self.merge_point_clouds(obj_node.point_cloud, obj_cloud)
dt = time.perf_counter() - t0
total_latency_ros = (
self.get_current_ros_time_sec() - img_timestamp
)
wall_str = ""
if pipeline_start_wall is not None:
wall_dt = time.time() - pipeline_start_wall
wall_str = f", Wall={wall_dt:.3f} s"
self.get_logger().info(
f"Merged Point Clouds (NON-FUNCTIONAL) → Object: {obj_node.class_id} (ID {obj_node.id}) "
f"+{obj_cloud.shape[0]} pts "
f"+ -> Merge took {dt*1000:.1f} ms"
f"Merged Point Clouds (NON-FUNCTIONAL) → "
f"Object: {obj_node.class_id} "
f"(ID {obj_node.id}) "
f"+{obj_cloud.shape[0]} pts | "
f"Merge took {dt*1000:.1f} ms | "
f"Latency: ROS={total_latency_ros:.3f} s"
f"{wall_str}"
)
self._merge_nearby_object_nodes(match_id)
@@ -790,9 +838,20 @@ class GraphManagementNode(Node):
# Update bounding box from downsampled / clean point cloud
self._update_bounding_box_from_point_cloud(new_obj)
total_latency_ros = (
self.get_current_ros_time_sec() - img_timestamp
)
wall_str = ""
if pipeline_start_wall is not None:
wall_dt = time.time() - pipeline_start_wall
wall_str = f", Wall={wall_dt:.3f} s"
self.get_logger().info(
f"Created Object Node → Object: {new_obj.class_id} (ID {new_obj.id}) "
f"{obj_cloud.shape[0]} pts"
f"Created Object Node → "
f"Object: {new_obj.class_id} "
f"(ID {new_obj.id}) "
f"{obj_cloud.shape[0]} pts | "
f"Latency: ROS={total_latency_ros:.3f} s"
f"{wall_str}"
)
self.scene_graph.add_node(new_id, data=new_obj)
@@ -822,6 +881,16 @@ class GraphManagementNode(Node):
img_timestamp = self.stamp_to_sec(msg.header.stamp)
now_timestamp = self.get_current_ros_time_sec()
input_lag = now_timestamp - img_timestamp
# Extract pipeline start wall time from msg.header.frame_id
# if available
pipeline_start_wall = None
frame_id_parts = msg.header.frame_id.split('|')
if len(frame_id_parts) > 1:
try:
pipeline_start_wall = float(frame_id_parts[1])
except ValueError:
pass
# 0) No detections -> nothing to do
if not msg.bbox:
@@ -877,9 +946,21 @@ class GraphManagementNode(Node):
fn_node.point_cloud = self.merge_point_clouds(fn_node.point_cloud, func_cloud)
total_latency_ros = (
self.get_current_ros_time_sec() - img_timestamp
)
wall_str = ""
if pipeline_start_wall is not None:
wall_dt = time.time() - pipeline_start_wall
wall_str = f", Wall={wall_dt:.3f} s"
self.get_logger().info(
f"Merged Point Clouds (FUNCTIONAL) → Functional: {getattr(fn_node, 'class_id', aff)} "
f"(ID {getattr(fn_node, 'id', match_id)}) +{func_cloud.shape[0]} pts"
f"Merged Point Clouds (FUNCTIONAL) → "
f"Functional: "
f"{getattr(fn_node, 'class_id', aff)} "
f"(ID {getattr(fn_node, 'id', match_id)}) "
f"+{func_cloud.shape[0]} pts | "
f"Latency: ROS={total_latency_ros:.3f} s"
f"{wall_str}"
)
# Keep affordances as a set
@@ -906,9 +987,21 @@ class GraphManagementNode(Node):
# Initialize point cloud via merge helper
new_fn.point_cloud = self.merge_point_clouds(new_fn.point_cloud, func_cloud)
total_latency_ros = (
self.get_current_ros_time_sec() - img_timestamp
)
wall_str = ""
if pipeline_start_wall is not None:
wall_dt = time.time() - pipeline_start_wall
wall_str = f", Wall={wall_dt:.3f} s"
self.get_logger().info(
f"Created New Functional Node → Functional: {getattr(new_fn, 'class_id', aff)} "
f"(ID {new_fn.id}) {func_cloud.shape[0]} pts"
f"Created New Functional Node → "
f"Functional: "
f"{getattr(new_fn, 'class_id', aff)} "
f"(ID {new_fn.id}) "
f"{func_cloud.shape[0]} pts | "
f"Latency: ROS={total_latency_ros:.3f} s"
f"{wall_str}"
)
self.scene_graph.add_node(new_id, data=new_fn)
@@ -1169,6 +1262,15 @@ class GraphManagementNode(Node):
Point32(x=pt[0], y=pt[1], z=pt[2]) for pt in bbox_data['corners']
]
def get_class_thresholds(self, class_id):
"""
Get the (match_threshold, merge_threshold) for a given class ID.
If class_id is not in the configuration, falls back to the default thresholds.
"""
if class_id in self.class_threshold_configs:
return self.class_threshold_configs[class_id]
return (self.object_match_threshold, self.object_node_merge_threshold)
def _find_closest_object_node(self, centroid, label=None, threshold=1, query_bbox=None):
"""
Helper function: Finds the ObjectNode closest to the given centroid or with the highest 3D IoU.
@@ -1270,9 +1372,6 @@ class GraphManagementNode(Node):
Returns:
int: Number of merged/removed nodes
"""
if merge_threshold is None:
merge_threshold = getattr(self, "object_node_merge_threshold", 1.2)
if base_id not in self.scene_graph:
return 0
@@ -1285,6 +1384,9 @@ class GraphManagementNode(Node):
return 0
base_label = getattr(base_data, "class_id", None)
if merge_threshold is None:
_, class_merge_threshold = self.get_class_thresholds(base_label)
merge_threshold = class_merge_threshold
merged_count = 0
candidates = []
@@ -1,80 +0,0 @@
import torch
from ultralytics import SAM, FastSAM
class SamWrapper:
"""Wrapper for Ultralytics SAM/SAM2/FastSAM to handle prompted segmentation via bounding boxes."""
def __init__(self, model_name):
"""
Initializes segmenter model.
Args:
model_name (str): Model name / path (e.g. 'FastSAM-s.pt', 'sam2_b.pt', etc.)
"""
self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
print(f"[SamWrapper] Loading {model_name} on {self.device}...")
try:
if "FastSAM" in model_name:
self.model = FastSAM(model_name)
else:
self.model = SAM(model_name)
self.model.to(self.device)
print("[SamWrapper] Model loaded successfully.")
except Exception as e:
print(f"[SamWrapper] Error loading model: {e}")
raise e
def predict(self, image, bboxes):
"""Generates segmentation masks based on bounding box prompts."""
if not bboxes or len(bboxes) == 0:
return []
try:
# Run inference with bbox prompts
results = self.model(image, bboxes=bboxes, verbose=False)
except Exception as e:
print(f"[SamWrapper] Inference failed: {e}")
return [None] * len(bboxes)
if not results or results[0].masks is None:
return [None] * len(bboxes)
# Extract masks, move to CPU, and convert to numpy
masks_tensor = results[0].masks.data
masks_np = masks_tensor.cpu().numpy().astype(bool)
# Get bounding boxes corresponding to the detected masks
detected_boxes = results[0].boxes.xyxy.cpu().numpy()
def bbox_iou(box1, box2):
x1 = max(box1[0], box2[0])
y1 = max(box1[1], box2[1])
x2 = min(box1[2], box2[2])
y2 = min(box1[3], box2[3])
intersection = max(0.0, x2 - x1) * max(0.0, y2 - y1)
area1 = (box1[2] - box1[0]) * (box1[3] - box1[1])
area2 = (box2[2] - box2[0]) * (box2[3] - box2[1])
union = area1 + area2 - intersection
if union == 0:
return 0.0
return intersection / union
# Match each input bbox to a returned mask using IoU
matched_masks = [None] * len(bboxes)
for i, input_bbox in enumerate(bboxes):
best_iou = 0.0
best_idx = -1
for j, det_box in enumerate(detected_boxes):
iou = bbox_iou(input_bbox, det_box)
if iou > best_iou:
best_iou = iou
best_idx = j
if best_idx != -1 and best_iou > 0.3:
matched_masks[i] = masks_np[best_idx]
return matched_masks
+2 -2
View File
@@ -1,4 +1,4 @@
[develop]
script_dir=$base/lib/scene_graph_room_classification
script_dir=$base/lib/scene_graph_generation_pipeline
[install]
install_scripts=$base/lib/scene_graph_room_classification
install_scripts=$base/lib/scene_graph_generation_pipeline
+8 -8
View File
@@ -2,7 +2,7 @@ from setuptools import find_packages, setup
import os
from glob import glob
package_name = 'scene_graph_room_classification'
package_name = 'scene_graph_generation_pipeline'
setup(
name=package_name,
@@ -19,7 +19,7 @@ setup(
(os.path.join('share', package_name, 'meshes', 'WH01'),
glob('meshes/WH01/*')),
(os.path.join('share', package_name, 'model'),
['scene_graph_room_classification/room_classification/rf_classifier.pkl']),
['scene_graph_generation_pipeline/room_classification/rf_classifier.pkl']),
],
install_requires=['setuptools', 'open3d', 'shapely', "huggingface_hub"],
zip_safe=True,
@@ -34,12 +34,12 @@ setup(
},
entry_points={
'console_scripts': [
'object_detection_node = scene_graph_room_classification.object_detection.object_detection_node:main',
'object_localization_node = scene_graph_room_classification.object_localization.object_localization_node:main',
'scene_graph_fusion_node = scene_graph_room_classification.scene_graph_fusion.scene_graph_fusion_node:main',
'odom_vizualization_node = scene_graph_room_classification.odom_vizualization.odom_vizualization_node:main',
'room_classification_node = scene_graph_room_classification.room_classification.room_classification_node:main',
'room_segmentation_node = scene_graph_room_classification.room_segmentation.room_segmentation_node:main'
'object_detection_node = scene_graph_generation_pipeline.object_detection.object_detection_node:main',
'object_localization_node = scene_graph_generation_pipeline.object_localization.object_localization_node:main',
'scene_graph_fusion_node = scene_graph_generation_pipeline.scene_graph_fusion.scene_graph_fusion_node:main',
'odom_vizualization_node = scene_graph_generation_pipeline.odom_vizualization.odom_vizualization_node:main',
'room_classification_node = scene_graph_generation_pipeline.room_classification.room_classification_node:main',
'room_segmentation_node = scene_graph_generation_pipeline.room_segmentation.room_segmentation_node:main'
],
},
)
+1 -1
View File
@@ -1,7 +1,7 @@
import numpy as np
import pytest
from geometry_msgs.msg import Pose, Point, Quaternion
from scene_graph_room_classification.object_localization.geometry_utils import GeometryUtils
from scene_graph_generation_pipeline.object_localization.geometry_utils import GeometryUtils
def test_project_mask_to_3d():
# Setup test inputs
+7 -7
View File
@@ -3,18 +3,18 @@ from unittest.mock import MagicMock, patch
from rclpy.parameter import Parameter
# Mock the SamWrapper and tf2_ros before importing the node to prevent loading actual weights and running background TF threads
with patch('scene_graph_room_classification.object_localization.sam_wrapper.SamWrapper'), \
patch('scene_graph_room_classification.object_localization.object_localization_node.Buffer'), \
patch('scene_graph_room_classification.object_localization.object_localization_node.TransformListener'):
from scene_graph_room_classification.object_localization.object_localization_node import ObjectLocalizationNode
with patch('scene_graph_generation_pipeline.object_localization.sam_wrapper.SamWrapper'), \
patch('scene_graph_generation_pipeline.object_localization.object_localization_node.Buffer'), \
patch('scene_graph_generation_pipeline.object_localization.object_localization_node.TransformListener'):
from scene_graph_generation_pipeline.object_localization.object_localization_node import ObjectLocalizationNode
def test_node_parameter():
if not rclpy.ok():
rclpy.init()
with patch('scene_graph_room_classification.object_localization.sam_wrapper.SamWrapper'), \
patch('scene_graph_room_classification.object_localization.object_localization_node.Buffer'), \
patch('scene_graph_room_classification.object_localization.object_localization_node.TransformListener'):
with patch('scene_graph_generation_pipeline.object_localization.sam_wrapper.SamWrapper'), \
patch('scene_graph_generation_pipeline.object_localization.object_localization_node.Buffer'), \
patch('scene_graph_generation_pipeline.object_localization.object_localization_node.TransformListener'):
node = ObjectLocalizationNode()
+12 -4
View File
@@ -7,7 +7,7 @@ from unittest.mock import MagicMock, patch
import pytest
import rclpy
from scene_graph_room_classification.room_classification.room_classification_node import ( # noqa: E501
from scene_graph_generation_pipeline.room_classification.room_classification_node import ( # noqa: E501
RoomClassificationNode
)
@@ -24,8 +24,16 @@ def ros_init():
def test_room_classification(ros_init):
"""Test room classification rules for kitchen vs office."""
mock_classifier = MagicMock()
def predict_side_effect(input_vector):
# Index of 'appliances' (from refrigerator) is 37 in the mpcat40 list
if input_vector[0][37] > 0:
return [10] # kitchen
return [14] # office
mock_classifier.predict = MagicMock(side_effect=predict_side_effect)
with patch('builtins.open', MagicMock()), \
patch('pickle.load', return_value=MagicMock()):
patch('pickle.load', return_value=mock_classifier):
node = RoomClassificationNode()
# Test case 1: room containing a refrigerator returns "kitchen"
@@ -44,8 +52,8 @@ def test_room_classification(ros_init):
room_label_office = node.classify_room(['chair', 'table', 'laptop'])
assert room_label_office == 'office'
# Test case 4: room with unknown objects returns "office"
# Test case 4: room with unknown objects returns None
room_label_unknown = node.classify_room(['random_unknown_object'])
assert room_label_unknown == 'office'
assert room_label_unknown is None
node.destroy_node()
+1 -1
View File
@@ -8,7 +8,7 @@ import numpy as np
import pytest
from geometry_msgs.msg import Point
from scene_graph_interfaces.msg import RoomPolygonList, RoomPolygon
from scene_graph_room_classification.scene_graph_fusion.scene_graph_fusion_node import ( # noqa: E501
from scene_graph_generation_pipeline.scene_graph_fusion.scene_graph_fusion_node import ( # noqa: E501
GraphManagementNode, ObjectNode, RoomNode, FunctionalElementNode
)