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
janzon f93011219e test: add unit tests for room classification and adjacency, and update RViz configuration for improved visualization. 2026-07-03 10:00:28 +00:00
janzon 74add73a61 feat: implement spatial room containment logic for objects and functional elements with corresponding unit tests 2026-06-26 11:16:44 +00:00
janzon 4ee096d037 feat: add distance-based object filtering parameter to localization node, include unit tests 2026-06-26 11:03:09 +00:00
janzon aef27851d6 refined indoor vocabulary for Yolo World 2026-06-26 11:02:43 +00:00
janzon a9be8192de refactor: implement buffer-based synchronization and IoU-based mask matching for object localization pipeline. 2026-06-25 15:34:47 +00:00
janzon 992afe5f4e added rviz file for easy visalization 2026-06-25 15:34:39 +00:00
janzon 47af27b686 feat: implement room classification and segmentation nodes with associated graph fusion updates 2026-06-24 14:13:35 +00:00
janzon 7d471405f4 refactor: configure simulation time and refine node lifecycle while adding vehicle mesh assets 2026-06-24 11:20:16 +00:00
42 changed files with 4983 additions and 1178 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/
```
+46 -9
View File
@@ -1,52 +1,89 @@
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node
def generate_launch_description():
"""Launch file for scene graph room classification nodes."""
# Declare the use_sim_time launch argument (defaults to true for simulation/rosbag play)
use_sim_time = LaunchConfiguration('use_sim_time', default='true')
use_sim_time_arg = DeclareLaunchArgument(
'use_sim_time',
default_value='true',
description='Use simulation (bag) clock if true'
)
common_params = [{'use_sim_time': use_sim_time}]
# 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',
parameters=[],
parameters=common_params,
remappings=[]
)
# 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',
parameters=[],
parameters=common_params,
remappings=[]
)
# 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',
parameters=[],
parameters=common_params,
remappings=[]
)
# 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',
parameters=[],
parameters=common_params,
remappings=[]
)
# Room Classification Node
room_classification_node = Node(
package='scene_graph_generation_pipeline',
executable='room_classification_node',
name='room_classification_node',
output='screen',
parameters=common_params,
remappings=[]
)
# Room Segmentation Node
room_segmentation_node = Node(
package='scene_graph_generation_pipeline',
executable='room_segmentation_node',
name='room_segmentation_node',
output='screen',
parameters=common_params,
remappings=[]
)
return LaunchDescription([
use_sim_time_arg,
object_detection_node,
object_localization_node,
scene_graph_fusion_node,
odom_vizualization_node
odom_vizualization_node,
room_classification_node,
room_segmentation_node
])
+38 -5
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,18 +69,51 @@ 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',
parameters=common_params,
remappings=[]
)
# Room Classification Node
room_classification_node = Node(
package='scene_graph_generation_pipeline',
executable='room_classification_node',
name='room_classification_node',
output='screen',
parameters=common_params,
remappings=[]
)
# Room Segmentation Node
room_segmentation_node = Node(
package='scene_graph_generation_pipeline',
executable='room_segmentation_node',
name='room_segmentation_node',
output='screen',
parameters=common_params,
remappings=[]
)
# RViz2 Node
rviz2_node = Node(
package='rviz2',
executable='rviz2',
name='rviz2',
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'}
)
return LaunchDescription([
rtabmap_slam,
object_detection_node,
object_localization_node,
scene_graph_fusion_node,
odom_vizualization_node
odom_vizualization_node,
room_classification_node,
room_segmentation_node,
rviz2_node
])
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
Binary file not shown.
+2 -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>
@@ -15,6 +15,7 @@
<!-- Execution Dependencies needed for your node -->
<exec_depend>rclpy</exec_depend>
<exec_depend>sensor_msgs</exec_depend>
<exec_depend>nav_msgs</exec_depend>
<exec_depend>cv_bridge</exec_depend>
<exec_depend>python3-opencv</exec_depend>
<exec_depend>std_msgs</exec_depend>
+483
View File
@@ -0,0 +1,483 @@
Panels:
- Class: rviz_common/Displays
Help Height: 70
Name: Displays
Property Tree Widget:
Expanded:
- /Global Options1
- /Status1
- /MapCloud1
Splitter Ratio: 0.5147058963775635
Tree Height: 224
- Class: rviz_common/Selection
Name: Selection
- Class: rviz_common/Tool Properties
Expanded:
- /2D Goal Pose1
- /Publish Point1
Name: Tool Properties
Splitter Ratio: 0.5886790156364441
- Class: rviz_common/Views
Expanded:
- /Current View1
Name: Views
Splitter Ratio: 0.5
Visualization Manager:
Class: ""
Displays:
- Alpha: 0.5
Cell Size: 1
Class: rviz_default_plugins/Grid
Color: 160; 160; 164
Enabled: true
Line Style:
Line Width: 0.029999999329447746
Value: Lines
Name: Grid
Normal Cell Count: 0
Offset:
X: 0
Y: 0
Z: 0
Plane: XY
Plane Cell Count: 10
Reference Frame: <Fixed Frame>
Value: true
- Class: rtabmap_rviz_plugins/Info
Enabled: true
Name: Info
Topic:
Depth: 5
Durability Policy: Volatile
Filter size: 10
History Policy: Keep Last
Reliability Policy: Reliable
Value: /rtabmap/info
Value: true
- Alpha: 1
Autocompute Intensity Bounds: true
Autocompute Value Bounds:
Max Value: 10
Min Value: -10
Value: true
Axis: Z
Channel Name: intensity
Class: rtabmap_rviz_plugins/MapCloud
Cloud decimation: 4
Cloud from scan: false
Cloud max depth (m): 4
Cloud min depth (m): 0
Cloud voxel size (m): 0.009999999776482582
Color: 255; 255; 255
Color Transformer: RGB8
Download graph: false
Download map: false
Download namespace: rtabmap
Enabled: true
Filter ceiling (m): 0
Filter floor (m): 0
Invert Rainbow: false
Max Color: 255; 255; 255
Max Intensity: 4096
Min Color: 0; 0; 0
Min Intensity: 0
Name: MapCloud
Node filtering angle (degrees): 30
Node filtering radius (m): 0
Position Transformer: XYZ
Size (Pixels): 3
Size (m): 0.009999999776482582
Style: Points
Topic:
Depth: 5
Durability Policy: Volatile
Filter size: 10
History Policy: Keep Last
Reliability Policy: Reliable
Value: /rtabmap/mapData
Use Fixed Frame: true
Use rainbow: true
Value: true
- Alpha: 1
Class: rtabmap_rviz_plugins/MapGraph
Enabled: true
Global loop closure: 255; 0; 0
Landmark: 0; 128; 0
Local loop closure: 255; 255; 0
Merged neighbor: 255; 170; 0
Name: MapGraph
Neighbor: 0; 0; 255
Topic:
Depth: 5
Durability Policy: Volatile
Filter size: 10
History Policy: Keep Last
Reliability Policy: Reliable
Value: /rtabmap/mapGraph
User: 255; 0; 0
Value: true
Virtual: 255; 0; 255
- Class: rviz_default_plugins/TF
Enabled: false
Frame Timeout: 15
Frames:
All Enabled: true
Marker Scale: 1
Name: TF
Show Arrows: true
Show Axes: true
Show Names: false
Tree:
{}
Update Interval: 0
Value: false
- Alpha: 0.699999988079071
Class: rviz_default_plugins/Map
Color Scheme: map
Draw Behind: false
Enabled: true
Name: Map
Topic:
Depth: 5
Durability Policy: Volatile
Filter size: 10
History Policy: Keep Last
Reliability Policy: Reliable
Value: /rtabmap/map
Update Topic:
Depth: 5
Durability Policy: Volatile
History Policy: Keep Last
Reliability Policy: Reliable
Value: /rtabmap/map_updates
Use Timestamp: false
Value: true
- Alpha: 1
Autocompute Intensity Bounds: true
Autocompute Value Bounds:
Max Value: 10
Min Value: -10
Value: true
Axis: Z
Channel Name: intensity
Class: rviz_default_plugins/PointCloud2
Color: 255; 255; 255
Color Transformer: RGB8
Decay Time: 0
Enabled: true
Invert Rainbow: false
Max Color: 255; 255; 255
Max Intensity: 4096
Min Color: 0; 0; 0
Min Intensity: 0
Name: Odom Local Map
Position Transformer: XYZ
Selectable: true
Size (Pixels): 3
Size (m): 0.009999999776482582
Style: Points
Topic:
Depth: 5
Durability Policy: Volatile
Filter size: 10
History Policy: Keep Last
Reliability Policy: Reliable
Value: /rtabmap/odom_local_map
Use Fixed Frame: true
Use rainbow: true
Value: true
- Alpha: 1
Autocompute Intensity Bounds: true
Autocompute Value Bounds:
Max Value: 10
Min Value: -10
Value: true
Axis: Z
Channel Name: intensity
Class: rviz_default_plugins/PointCloud2
Color: 255; 255; 255
Color Transformer: RGB8
Decay Time: 0
Enabled: true
Invert Rainbow: false
Max Color: 255; 255; 255
Max Intensity: 4096
Min Color: 0; 0; 0
Min Intensity: 0
Name: Camera Cloud
Position Transformer: XYZ
Selectable: true
Size (Pixels): 3
Size (m): 0.009999999776482582
Style: Points
Topic:
Depth: 5
Durability Policy: Volatile
Filter size: 10
History Policy: Keep Last
Reliability Policy: Reliable
Value: /voxel_cloud
Use Fixed Frame: true
Use rainbow: true
Value: true
- Class: rviz_default_plugins/MarkerArray
Enabled: true
Name: Robot Pose Markers
Namespaces:
robot_mesh: true
robot_wheel_fl: true
robot_wheel_fr: true
robot_wheel_rl: true
robot_wheel_rr: true
trajectory: true
Topic:
Depth: 5
Durability Policy: Volatile
History Policy: Keep Last
Reliability Policy: Reliable
Value: /scene_graph/viz/robot_pose
Value: true
- Class: rviz_default_plugins/MarkerArray
Enabled: true
Name: MarkerArray
Namespaces:
yolo_3d_pointclouds: true
Topic:
Depth: 5
Durability Policy: Volatile
History Policy: Keep Last
Reliability Policy: Reliable
Value: /bounding_boxes_3d/point_cloud_markers
Value: true
- Class: rviz_default_plugins/Image
Enabled: true
Max Value: 1
Median window: 5
Min Value: 0
Name: Image
Normalize Range: true
Topic:
Depth: 5
Durability Policy: Volatile
History Policy: Keep Last
Reliability Policy: Reliable
Value: /scene_graph/debug/yolo
Value: true
- Class: rviz_default_plugins/MarkerArray
Enabled: true
Name: MarkerArray
Namespaces:
bounding_box_points: true
Topic:
Depth: 5
Durability Policy: Volatile
History Policy: Keep Last
Reliability Policy: Reliable
Value: /scene_graph/viz/building_markers
Value: true
- Class: rviz_default_plugins/MarkerArray
Enabled: true
Name: MarkerArray
Namespaces:
lines: true
Topic:
Depth: 5
Durability Policy: Volatile
History Policy: Keep Last
Reliability Policy: Reliable
Value: /scene_graph/viz/line_markers
Value: true
- Class: rviz_default_plugins/MarkerArray
Enabled: true
Name: MarkerArray
Namespaces:
room_markers: true
Topic:
Depth: 5
Durability Policy: Volatile
History Policy: Keep Last
Reliability Policy: Reliable
Value: /scene_graph/viz/room_markers
Value: true
- Class: rviz_default_plugins/MarkerArray
Enabled: true
Name: MarkerArray
Namespaces:
labels: true
Topic:
Depth: 5
Durability Policy: Volatile
History Policy: Keep Last
Reliability Policy: Reliable
Value: /scene_graph/viz/text_markers
Value: true
- Class: rviz_default_plugins/MarkerArray
Enabled: true
Name: MarkerArray
Namespaces:
bounding_boxes: true
Topic:
Depth: 5
Durability Policy: Volatile
History Policy: Keep Last
Reliability Policy: Reliable
Value: /scene_graph/viz/object_bbox_marker
Value: true
- Alpha: 1
Autocompute Intensity Bounds: true
Autocompute Value Bounds:
Max Value: 10
Min Value: -10
Value: true
Axis: Z
Channel Name: intensity
Class: rviz_default_plugins/PointCloud2
Color: 255; 255; 255
Color Transformer: Intensity
Decay Time: 0
Enabled: true
Invert Rainbow: false
Max Color: 255; 255; 255
Max Intensity: 4096
Min Color: 0; 0; 0
Min Intensity: 0
Name: PointCloud2
Position Transformer: XYZ
Selectable: true
Size (Pixels): 3
Size (m): 0.009999999776482582
Style: Flat Squares
Topic:
Depth: 5
Durability Policy: Volatile
Filter size: 10
History Policy: Keep Last
Reliability Policy: Reliable
Value: /scene_graph/viz/object_clouds
Use Fixed Frame: true
Use rainbow: true
Value: true
- Class: rviz_default_plugins/MarkerArray
Enabled: true
Name: MarkerArray
Namespaces:
{}
Topic:
Depth: 5
Durability Policy: Volatile
History Policy: Keep Last
Reliability Policy: Reliable
Value: /scene_graph/debug/bbox_points
Value: true
- Class: rviz_default_plugins/Image
Enabled: true
Max Value: 1
Median window: 5
Min Value: 0
Name: Image
Normalize Range: true
Topic:
Depth: 5
Durability Policy: Volatile
History Policy: Keep Last
Reliability Policy: Reliable
Value: /scene_graph/sync/depth/image_raw
Value: true
- Class: rviz_default_plugins/Image
Enabled: true
Max Value: 1
Median window: 5
Min Value: 0
Name: Image
Normalize Range: true
Topic:
Depth: 5
Durability Policy: Volatile
History Policy: Keep Last
Reliability Policy: Reliable
Value: /scene_graph/sync/depth/image_raw
Value: true
Enabled: true
Global Options:
Background Color: 255; 255; 255
Fixed Frame: map
Frame Rate: 30
Name: root
Tools:
- Class: rviz_default_plugins/Interact
Hide Inactive Objects: true
- Class: rviz_default_plugins/MoveCamera
- Class: rviz_default_plugins/Select
- Class: rviz_default_plugins/FocusCamera
- Class: rviz_default_plugins/Measure
Line color: 128; 128; 0
- Class: rviz_default_plugins/SetInitialPose
Covariance x: 0.25
Covariance y: 0.25
Covariance yaw: 0.06853891909122467
Topic:
Depth: 5
Durability Policy: Volatile
History Policy: Keep Last
Reliability Policy: Reliable
Value: /initialpose
- Class: rviz_default_plugins/SetGoal
Topic:
Depth: 5
Durability Policy: Volatile
History Policy: Keep Last
Reliability Policy: Reliable
Value: /goal_pose
- Class: rviz_default_plugins/PublishPoint
Single click: true
Topic:
Depth: 5
Durability Policy: Volatile
History Policy: Keep Last
Reliability Policy: Reliable
Value: /clicked_point
Transformation:
Current:
Class: rviz_default_plugins/TF
Value: true
Views:
Current:
Class: rviz_default_plugins/Orbit
Distance: 33.26894760131836
Enable Stereo Rendering:
Stereo Eye Separation: 0.05999999865889549
Stereo Focal Distance: 1
Swap Stereo Eyes: false
Value: false
Focal Point:
X: 6.252047061920166
Y: -1.7172622680664062
Z: 0.0801977664232254
Focal Shape Fixed Size: true
Focal Shape Size: 0.05000000074505806
Invert Z Axis: false
Name: Current View
Near Clip Distance: 0.009999999776482582
Pitch: 0.8447975516319275
Target Frame: map
Value: Orbit (rviz_default_plugins)
Yaw: 1.577227234840393
Saved: ~
Window Geometry:
Displays:
collapsed: false
Height: 1029
Hide Left Dock: false
Hide Right Dock: false
Image:
collapsed: false
QMainWindow State: 000000ff00000000fd000000040000000000000215000003affc020000000efb0000001200530065006c0065006300740069006f006e00000001e10000009b0000005c00fffffffb0000001e0054006f006f006c002000500072006f007000650072007400690065007302000001ed000001df00000185000000a3fb000000120056006900650077007300200054006f006f02000001df000002110000018500000122fb000000200054006f006f006c002000500072006f0070006500720074006900650073003203000002880000011d000002210000017afb000000100044006900730070006c006100790073010000003b00000161000000c700fffffffb0000002000730065006c0065006300740069006f006e00200062007500660066006500720200000138000000aa0000023a00000294fb00000014005700690064006500530074006500720065006f02000000e6000000d2000003ee0000030bfb0000000c004b0069006e0065006300740200000186000001060000030c00000261fb0000000a0049006d00610067006501000001a2000001250000002800fffffffb0000000a0049006d0061006700650000000242000000d70000002800fffffffb0000000a0049006d00610067006501000002cd0000011d0000002800fffffffb0000000a0049006d00610067006501000002f4000000f60000000000000000fb0000000a0049006d0061006700650100000277000001730000000000000000fb0000000a0049006d006100670065010000029f0000014b0000000000000000000000010000010f00000284fc0200000003fb0000001e0054006f006f006c002000500072006f00700065007200740069006500730100000041000000780000000000000000fb0000000a00560069006500770073000000003d00000284000000a000fffffffb0000001200530065006c0065006300740069006f006e010000025a000000b200000000000000000000000200000490000000a9fc0100000001fb0000000a00560069006500770073030000004e00000080000002e10000019700000003000004420000003efc0100000002fb0000000800540069006d00650100000000000004420000000000000000fb0000000800540069006d0065010000000000000450000000000000000000000565000003af00000004000000040000000800000008fc0000000100000002000000010000000a0054006f006f006c00730100000000ffffffff0000000000000000
Selection:
collapsed: false
Tool Properties:
collapsed: false
Views:
collapsed: false
Width: 1920
X: 0
Y: 0
@@ -15,6 +15,8 @@ import message_filters
import time # For performance timing
import torch # For GPU/CUDA support
from rclpy.parameter import Parameter
# Add resource path for vocabulary configs
from .vocabulary_configs import get_vocabulary
@@ -28,7 +30,10 @@ class ObjectDetectionNode(Node):
synchronized topics along with detected object information.
"""
# Initialize the parent Node class with the node name
super().__init__('object_detection_node')
super().__init__(
'object_detection_node',
parameter_overrides=[Parameter('use_sim_time', value=True)]
)
# ==================== YOLO-World Model ====================
# Load the YOLO-World model (v8.2 for zero-shot open-vocabulary detection)
@@ -110,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')
@@ -125,8 +132,9 @@ class ObjectDetectionNode(Node):
# Run YOLO-World inference on the image
yolo_detected_objects = self._detect_with_yolo(cv_image)
# Update timestamps for all messages to the current time
current_time = self.get_clock().now().to_msg()
# Use the original synchronized timestamp of the image rather than the current time,
# to ensure that downstream TF lookups are performed at the correct time the data was captured.
current_time = ros_image.header.stamp
depth_msg.header.stamp = current_time
self.rgb_image.header.stamp = current_time
odom_msg.header.stamp = current_time
@@ -141,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):
@@ -292,9 +301,10 @@ def main(args=None):
# Allow graceful shutdown on Ctrl+C
pass
finally:
# Clean up the node and shutdown ROS2
# Clean up the node and shutdown ROS2 safely
node.destroy_node()
rclpy.shutdown()
if rclpy.ok():
rclpy.shutdown()
if __name__ == '__main__':
# Execute main function when script is run directly
@@ -0,0 +1,216 @@
"""
A vocabulary dictionary for indoor robotics object detection that are passed to the YOLO-World model.
For each label we define a boolean that indicates whether the object is typically graspable by a robot.
Structure: Each entry is (label_name, is_graspable)
- label_name (str): Object class name for YOLO detection
- is_graspable (bool): Whether a robot arm can pick/grasp this object
"""
# Vocabulary with graspability affordances
# Format: (label_name: str, is_graspable: bool)
VOCABULARY_DATA = [
#Infrastruktur / Gebäude
#alte Begriffe
("door", False),
("radiator", False),
#new
("window", False),
("stairs", False),
("elevator door", False),
("pillar", False),
("handrail", False),
("light switch", False),
("power outlet", False),
("fire alarm", False),
("smoke detector", False),
("emergency exit", False),
("exit sign", False),
("door sign", False),
("room sign", False),
("ceiling light", False),
("air conditioner", False),
("ventilation grille", False),
#Möbel
#alte Begriffe
("chair", False),
("couch", False),
("cabinet", False),
("shelf", False),
("cupboard", False),
("dresser", False),
("wardrobe", False),
("closet", False),
("drawer", False),
#new
("desk", False),
("table", False),
("office chair", False),
("conference table", False),
("reception desk", False),
#Haushaltsgeräte
#alte Begriffe
("freezer", False),
("oven", False),
("microwave", False),
("stove", False),
("washing machine", False),
("dryer", False),
("dishwasher", False),
#new
("refrigerator", False),
("coffee machine", False),
("water dispenser", False),
("sink", False),
#Büroobjekte / Elektronik
#alte Begriffe
("computer", False),
("monitor", False),
("laptop", False),
("keyboard", True),
("mouse", True),
("television", False), # False / True?
#new
("printer", False),
("telephone", False),
("projector", False),
("projector screen", False),
("server rack", False),
("network switch", False),
("router", False),
("scanner", False),
("photocopier", False),
("speaker", False), # False / True?
("webcam", False), # False / True?
#Orientierungspunkte / Landmarken
#alte Begriffe
("painting", False),
("clock", True),
#new
("whiteboard", False),
("fire extinguisher", False),
("room number", False),
("name plate", False),
("bulletin board", False),
("information board", False),
("directory board", False),
("emergency exit sign", False),
("security camera", False),
# Beleuchtung & Raumausstattung
# alte Begriffe
("lamp", False),
("light", False),
("fan", False),
("carpet", False),
("curtain", False),
# new
("floor lamp", False),
("desk lamp", False),
("heater", False),
("wall panel", False),
#Behälter & Aufbewahrung
#alte Begriffe
("trash can", True),
("box", True),
("bag", True),
("backpack", True),
#new
("filing box", False),
("mailbox", False),
("locker", False),
("recycling bin", False),
("document tray", False),
#Küchen- und Haushaltsgegenstände
#alte Begriffe
("dish", True),
("cup", True),
("bottle", True),
("vase", True),
#new
("mug", True),
("glass", True),
("bowl", True),
("plate", True),
("cutlery holder", False),
("water jug", False),
("coffee pot", False),
("thermos", False),
#Dekoration & Pflanzen
#alte Begriffe
("plant", True),
#new
("plant pot", False), # False / True?
("flower", False),
("indoor tree", False),
("artificial plant", False),
("wall decoration", False),
("sculpture", False),
("ornament", False),
#Persönliche Gegenstände
#alte Begriffe
("book", True),
("shoe", True),
#new
("notebook", False), # False / True?
("binder", False),
("folder", False), # False / True?
("briefcase", False),
("suitcase", False),
("clipboard", False),
("wallet", False), # False / True?
]
def get_vocabulary_list():
"""
Returns the list of vocabulary labels (class names) for YOLO-World.
Returns:
list: List of string labels in order
"""
return [label for label, _ in VOCABULARY_DATA]
def get_vocabulary_dict():
"""
Returns a dictionary mapping label names to graspability affordances.
Returns:
dict: {label_name: is_graspable, ...}
"""
return {label: is_graspable for label, is_graspable in VOCABULARY_DATA}
def get_vocabulary_with_affordances():
"""
Returns the complete vocabulary data with graspability affordances.
Returns:
list: List of tuples (label_name, is_graspable)
"""
return VOCABULARY_DATA
# For backward compatibility
def get_vocabulary():
"""Alias for get_vocabulary_list() for backward compatibility."""
return get_vocabulary_list()
@@ -1,5 +1,6 @@
import numpy as np
import math
import cv2
from scipy.spatial import KDTree
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import connected_components
@@ -201,6 +202,60 @@ class GeometryUtils:
'max': max_pt
}
@staticmethod
def compute_3d_obb(points):
"""
Computes the Yaw-aligned Oriented Bounding Box (OBB-Z) of a 3D point cloud.
Returns:
dict containing:
'center': [x, y, z] center of the box
'size': [sx, sy, sz] dimensions
'corners': list of 8 lists (each [x,y,z]), representing the 8 vertices
ordered as 4 bottom vertices followed by 4 top vertices.
'rotation': [qx, qy, qz, qw] orientation quaternion
"""
if len(points) == 0:
return None
# 1. Project points to XY plane (2D)
pts_2d = points[:, :2].astype(np.float32)
# 2. Find minimum area bounding box in 2D
rect = cv2.minAreaRect(pts_2d)
(cx, cy), (w, h), angle_deg = rect
# 3. Get Z-bounds from 3D points
min_z = float(np.min(points[:, 2]))
max_z = float(np.max(points[:, 2]))
cz = (min_z + max_z) / 2.0
sz = max_z - min_z
# 4. Get the 4 corners of the 2D bounding box
corners_2d = cv2.boxPoints(rect)
# 5. Build 8 corners in 3D: 4 bottom (min_z) and 4 top (max_z)
corners_3d = []
for pt in corners_2d:
corners_3d.append([float(pt[0]), float(pt[1]), min_z])
for pt in corners_2d:
corners_3d.append([float(pt[0]), float(pt[1]), max_z])
# 6. Compute 3D quaternion for yaw rotation
angle_rad = np.radians(angle_deg)
yaw = angle_rad
qx = 0.0
qy = 0.0
qz = float(np.sin(yaw / 2.0))
qw = float(np.cos(yaw / 2.0))
return {
'center': [float(cx), float(cy), float(cz)],
'size': [float(w), float(h), float(sz)],
'corners': corners_3d,
'rotation': [qx, qy, qz, qw]
}
@staticmethod
def transform_points_camera_to_map(points_cam, odom_pose):
"""Transforms points from camera optical frame to map frame via odometry."""
@@ -0,0 +1,619 @@
#!/usr/bin/env python3
import rclpy
from rclpy.node import Node
from rclpy.callback_groups import ReentrantCallbackGroup
from rclpy.executors import MultiThreadedExecutor
import message_filters
from sensor_msgs.msg import Image, CameraInfo, PointCloud2, PointField
from nav_msgs.msg import Odometry
from std_msgs.msg import Header, String
from geometry_msgs.msg import Point32, Point
from scene_graph_interfaces.msg import ObjectList, Object3DBoundingBox, Object3DBoundingBoxList
from cv_bridge import CvBridge
import numpy as np
import sensor_msgs_py.point_cloud2 as pc2
import cv2
import time
import threading
from tf2_ros import Buffer, TransformListener
from visualization_msgs.msg import Marker, MarkerArray
from rclpy.parameter import Parameter
from .sam_wrapper import SamWrapper
from .geometry_utils import GeometryUtils
class ObjectLocalizationNode(Node):
def __init__(self):
super().__init__(
'object_localization_node',
parameter_overrides=[Parameter('use_sim_time', value=True)]
)
# --- 1. CONFIGURATION ---
model_name = 'FastSAM-s.pt'
self.depth_scale = 0.001
self.declare_parameter('max_object_distance', 5.0)
max_dist = self.get_parameter('max_object_distance').get_parameter_value().double_value
self.get_logger().info(f"Max object distance filter set to: {max_dist} m")
# --- 2. INITIALIZE MODULES ---
self.bridge = CvBridge()
self.get_logger().info(f"Initializing FastSAM Wrapper with {model_name}...")
self.sam = SamWrapper(model_name=model_name)
# --- 3. STATE ---
self.intrinsics = None
self.tf_buffer = Buffer(node=self)
self.tf_listener = TransformListener(self.tf_buffer, self, spin_thread=True)
# Custom buffer state for synchronizing messages
self.lock = threading.Lock()
self.rgb_buffer = {} # timestamp (float) -> msg
self.depth_buffer = {} # timestamp (float) -> msg
self.yolo_buffer = {} # timestamp (float) -> msg
self.is_processing = False
# --- 4. SUBSCRIBERS ---
self.callback_group = ReentrantCallbackGroup()
# A. Camera Intrinsics
self.get_intrinsics = self.create_subscription(
CameraInfo, '/camera/depth/camera_info', self.get_intrinsics_callback, 10,
callback_group=self.callback_group)
# B. Base Synchronized Inputs
self.sub_rgb = self.create_subscription(
Image, '/scene_graph/sync/color/image_raw', self.rgb_callback, 100,
callback_group=self.callback_group)
self.sub_depth = self.create_subscription(
Image, '/scene_graph/sync/depth/image_raw', self.depth_callback, 100,
callback_group=self.callback_group)
# C. Object Detection Inputs
self.sub_yolo = self.create_subscription(
ObjectList, '/scene_graph/yolo', self.yolo_callback, 100,
callback_group=self.callback_group)
# --- 6. PUBLISHERS ---
self.pub_bbox_yolo = self.create_publisher(Object3DBoundingBoxList, '/bounding_boxes_3d/yolo', 10)
self.pub_cloud_yolo = self.create_publisher(PointCloud2, '/object_clouds/yolo', 10)
self.pub_markers_yolo = self.create_publisher(MarkerArray, '/scene_graph/viz/current_bounding_boxes_3d', 10)
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...")
def get_intrinsics_callback(self, msg):
if self.intrinsics is None:
self.intrinsics = {
'fx': msg.k[0], 'fy': msg.k[4],
'cx': msg.k[2], 'cy': msg.k[5]
}
self.get_logger().info(f"Intrinsics captured: {self.intrinsics}")
def stamp_to_sec(self, stamp):
return float(stamp.sec) + float(stamp.nanosec) * 1e-9
def rgb_callback(self, msg):
t = self.stamp_to_sec(msg.header.stamp)
with self.lock:
self.rgb_buffer[t] = msg
if len(self.rgb_buffer) > 50:
oldest = min(self.rgb_buffer.keys())
self.rgb_buffer.pop(oldest)
self.try_process()
def depth_callback(self, msg):
t = self.stamp_to_sec(msg.header.stamp)
with self.lock:
self.depth_buffer[t] = msg
if len(self.depth_buffer) > 50:
oldest = min(self.depth_buffer.keys())
self.depth_buffer.pop(oldest)
self.try_process()
def yolo_callback(self, msg):
t = self.stamp_to_sec(msg.header.stamp)
with self.lock:
self.yolo_buffer[t] = msg
if len(self.yolo_buffer) > 50:
oldest = min(self.yolo_buffer.keys())
self.yolo_buffer.pop(oldest)
self.try_process()
def _find_matching_triplet(self, max_dt=0.05):
for t_yolo in list(self.yolo_buffer.keys()):
if not self.rgb_buffer or not self.depth_buffer:
continue
# Find closest RGB
best_rgb_dt = float('inf')
best_t_rgb = None
for t_rgb in self.rgb_buffer.keys():
dt = abs(t_yolo - t_rgb)
if dt < best_rgb_dt:
best_rgb_dt = dt
best_t_rgb = t_rgb
# Find closest Depth
best_depth_dt = float('inf')
best_t_depth = None
for t_depth in self.depth_buffer.keys():
dt = abs(t_yolo - t_depth)
if dt < best_depth_dt:
best_depth_dt = dt
best_t_depth = t_depth
if best_t_rgb is not None and best_t_depth is not None:
if best_rgb_dt <= max_dt and best_depth_dt <= max_dt:
return best_t_rgb, best_t_depth, t_yolo
return None
def try_process(self):
with self.lock:
if self.is_processing:
return
match = self._find_matching_triplet(max_dt=0.05)
if match is None:
return
t_rgb, t_depth, t_yolo = match
rgb_msg = self.rgb_buffer.pop(t_rgb)
depth_msg = self.depth_buffer.pop(t_depth)
yolo_msg = self.yolo_buffer.pop(t_yolo)
self.is_processing = True
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,
pipeline_start_wall=pipeline_start_wall)
finally:
with self.lock:
self.is_processing = False
# Check recursively for more matches
self.try_process()
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, 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
if not objects:
return
try:
t0 = time.perf_counter()
# --- STEP 0: LOOKUP TF TRANSFORM ---
try:
# Try exact timestamp lookup. Increase timeout to 1.5s for robustness under heavy load / sim time.
transform = self.tf_buffer.lookup_transform(
'map',
depth_msg.header.frame_id,
depth_msg.header.stamp,
rclpy.duration.Duration(seconds=1.5)
)
except Exception as e:
# Fallback: get the latest available transform in case of clock mismatch/delay
try:
transform = self.tf_buffer.lookup_transform(
'map',
depth_msg.header.frame_id,
rclpy.time.Time()
)
# Compute time difference between the requested stamp and the fallback stamp
requested_time = depth_msg.header.stamp.sec + depth_msg.header.stamp.nanosec * 1e-9
fallback_time = transform.header.stamp.sec + transform.header.stamp.nanosec * 1e-9
time_diff = abs(requested_time - fallback_time)
# If the time difference is significant (e.g. > 0.15s), using this fallback transform
# will cause severe misalignment when the robot is moving/turning.
# We should log a warning and skip the frame to prevent map corruption.
if time_diff > 0.40:
self.get_logger().warn(
f"[{source_name}] Exact TF lookup failed (Error: {e}). Fallback transform time difference is too large "
f"({time_diff:.3f} s > 0.15 s). Skipping frame to prevent inaccurate bounding boxes.",
throttle_duration_sec=2.0
)
return
else:
self.get_logger().info(
f"[{source_name}] Exact TF lookup failed (Error: {e}). Using fallback transform (diff: {time_diff:.3f} s).",
throttle_duration_sec=2.0
)
except Exception as fallback_err:
self.get_logger().warn(
f"[{source_name}] TF lookup from 'map' to '{depth_msg.header.frame_id}' failed: "
f"Exact: {e} | Fallback: {fallback_err}",
throttle_duration_sec=2.0
)
return
trans = transform.transform.translation
rot = transform.transform.rotation
translation = np.array([trans.x, trans.y, trans.z])
rotation = np.array([rot.x, rot.y, rot.z, rot.w])
# --- STEP 1: PREPARE DATA ---
cv_bgr = self.bridge.imgmsg_to_cv2(rgb_msg, desired_encoding='bgr8')
cv_rgb = cv2.cvtColor(cv_bgr, cv2.COLOR_BGR2RGB)
cv_depth = self.bridge.imgmsg_to_cv2(depth_msg, desired_encoding='passthrough')
# --- PREPARE DEBUG VISUALIZATIONS ---
segmented_bgr = cv_bgr.copy()
colors = [
(0, 0, 255), # Red
(0, 255, 0), # Green
(255, 0, 0), # Blue
(0, 255, 255), # Yellow
(255, 0, 255), # Magenta
(255, 255, 0), # Cyan
(0, 165, 255), # Orange
(128, 0, 128), # Purple
(0, 128, 128), # Teal
(128, 128, 0) # Olive
]
# --- STEP 2: PREPARE BBOXES FOR FASTSAM ---
bboxes = []
valid_obj_indices = []
for i, obj in enumerate(objects):
if len(obj.bounding_box) >= 2:
x1 = obj.bounding_box[0].x
y1 = obj.bounding_box[0].y
x2 = obj.bounding_box[1].x
y2 = obj.bounding_box[1].y
bboxes.append([x1, y1, x2, y2])
valid_obj_indices.append(i)
if not bboxes:
return
# --- STEP 3: RUN FASTSAM PREDICTION ---
t_inf_start = time.perf_counter()
masks = self.sam.predict(cv_rgb, bboxes)
t_inf_end = time.perf_counter()
# --- STEP 4: GEOMETRY PROCESSING ---
bbox_list_msg = target_list_class()
bbox_list_msg.header = rgb_msg.header
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()
all_cloud_points = []
for i, bbox in enumerate(bboxes):
original_obj = objects[valid_obj_indices[i]]
# Refine mask: intersect it with the YOLO bounding box to prevent leakage
refined_mask = None
if i < len(masks) and masks[i] is not None:
h, w = masks[i].shape
x1, y1, x2, y2 = bbox
ix1 = max(0, int(round(x1)))
iy1 = max(0, int(round(y1)))
ix2 = min(w, int(round(x2)))
iy2 = min(h, int(round(y2)))
bbox_mask = np.zeros_like(masks[i], dtype=bool)
bbox_mask[iy1:iy2, ix1:ix2] = True
refined_mask = masks[i] & bbox_mask
# Debug annotation: draw mask, box, and class label
color = colors[i % len(colors)]
bx1, by1, bx2, by2 = int(bbox[0]), int(bbox[1]), int(bbox[2]), int(bbox[3])
# Overlay mask on segmented_bgr if available
if refined_mask is not None:
mask_overlay = np.zeros_like(segmented_bgr)
mask_overlay[refined_mask] = color
segmented_bgr = cv2.addWeighted(segmented_bgr, 1.0, mask_overlay, 0.4, 0)
cv2.rectangle(segmented_bgr, (bx1, by1), (bx2, by2), color, 2)
class_name_str = original_obj.class_name.data
cv2.putText(segmented_bgr, class_name_str, (bx1, max(by1 - 10, 15)),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
# Try to use FastSAM mask if available
points_cam = None
used_mask = False
if refined_mask is not None:
# A1. Project Mask to 3D
points_cam = GeometryUtils.project_mask_to_3d(
cv_depth, refined_mask, self.intrinsics, self.depth_scale)
if points_cam is not None and len(points_cam) >= 10:
used_mask = True
# Fallback to direct 2D bounding box cropping if mask projection is empty/fails
if not used_mask:
# A2. Project BBox to 3D
points_cam = GeometryUtils.project_bbox_to_3d(
cv_depth, bbox, self.intrinsics, self.depth_scale, shrink_ratio=0.15)
points_clean = GeometryUtils.clean_outliers(points_cam, std_ratio=1.5)
if len(points_clean) < 10:
continue
# --- FILTER BY DISTANCE ---
# Compute centroid of points in camera frame to check physical distance from sensor
centroid_cam = np.mean(points_clean, axis=0)
distance = float(np.linalg.norm(centroid_cam))
max_dist = self.get_parameter('max_object_distance').get_parameter_value().double_value
if distance > max_dist:
self.get_logger().info(
f"[{source_name}] Skipping '{class_name_str}' (distance {distance:.2f} m > max {max_dist:.2f} m)",
throttle_duration_sec=2.0
)
continue
# B. Transform to Map Frame
points_map = GeometryUtils.transform_points(
points_clean, translation, rotation)
# C. Compute 3D OBB
bbox_data = GeometryUtils.compute_3d_obb(points_map)
if bbox_data is None:
continue
# D. Pack Bounding Box
bbox_msg = target_item_class()
bbox_msg.name = original_obj.class_name
# Handle 'graspable' field
if isinstance(bbox_msg, Object3DBoundingBox):
bbox_msg.graspable = original_obj.graspable
# Set bounding box coordinates (8 corners of OBB)
bbox_msg.bounding_box = [
Point32(x=float(pt[0]), y=float(pt[1]), z=float(pt[2]))
for pt in bbox_data['corners']
]
# Generate PointCloud2 for this object
pc_msg = PointCloud2()
pc_msg.header.stamp = rgb_msg.header.stamp
pc_msg.header.frame_id = "map"
if len(points_map) > 0:
pc_msg = pc2.create_cloud_xyz32(pc_msg.header, points_map.astype(np.float32))
if hasattr(bbox_msg, 'point_cloud'):
bbox_msg.point_cloud = pc_msg
bbox_list_msg.bbox.append(bbox_msg)
# ----------- LOGGER -----------
class_name = original_obj.class_name.data
pts_arr = np.array(bbox_data['corners'])
min_pt = np.min(pts_arr, axis=0)
max_pt = np.max(pts_arr, axis=0)
min_s = f"({min_pt[0]:.2f}, {min_pt[1]:.2f}, {min_pt[2]:.2f})"
max_s = f"({max_pt[0]:.2f}, {max_pt[1]:.2f}, {max_pt[2]:.2f})"
grasp_info = f" | Grasp: {bbox_msg.graspable}" if hasattr(bbox_msg, 'graspable') else ""
# Log whether it used mask or bbox fallback
source_method = "Mask" if used_mask else "BBox-Fallback"
self.get_logger().info( f"[{source_name}] ID: {i} | Class: '{class_name}'{grasp_info} | Method: {source_method} | Min: {min_s} | Max: {max_s}" )
# ------------------------------
# E. Cloud Accumulation
class_id = float(i)
class_col = np.full((points_map.shape[0], 1), class_id)
points_with_id = np.hstack((points_map, class_col))
all_cloud_points.append(points_with_id)
# F. Visualization Markers
center_x, center_y, center_z = bbox_data['center']
size_x, size_y, size_z = bbox_data['size']
qx, qy, qz, qw = bbox_data['rotation']
# Cube Marker
marker_cube = Marker()
marker_cube.header.frame_id = "map"
marker_cube.header.stamp = rgb_msg.header.stamp
marker_cube.ns = "yolo_3d_cubes"
marker_cube.id = i
marker_cube.type = Marker.CUBE
marker_cube.action = Marker.ADD
marker_cube.lifetime = rclpy.duration.Duration(seconds=1.0).to_msg()
marker_cube.pose.position.x = float(center_x)
marker_cube.pose.position.y = float(center_y)
marker_cube.pose.position.z = float(center_z)
marker_cube.pose.orientation.x = float(qx)
marker_cube.pose.orientation.y = float(qy)
marker_cube.pose.orientation.z = float(qz)
marker_cube.pose.orientation.w = float(qw)
marker_cube.scale.x = float(size_x)
marker_cube.scale.y = float(size_y)
marker_cube.scale.z = float(size_z)
marker_cube.color.r = 0.0
marker_cube.color.g = 1.0
marker_cube.color.b = 0.0
marker_cube.color.a = 0.4
marker_array_msg.markers.append(marker_cube)
# Text Marker
marker_text = Marker()
marker_text.header.frame_id = "map"
marker_text.header.stamp = rgb_msg.header.stamp
marker_text.ns = "yolo_3d_labels"
marker_text.id = i
marker_text.type = Marker.TEXT_VIEW_FACING
marker_text.action = Marker.ADD
marker_text.lifetime = rclpy.duration.Duration(seconds=1.0).to_msg()
marker_text.pose.position.x = float(center_x)
marker_text.pose.position.y = float(center_y)
marker_text.pose.position.z = float(max_pt[2] + 0.15)
marker_text.pose.orientation.x = 0.0
marker_text.pose.orientation.y = 0.0
marker_text.pose.orientation.z = 0.0
marker_text.pose.orientation.w = 1.0
marker_text.scale.z = 0.2
marker_text.color.r = 1.0
marker_text.color.g = 1.0
marker_text.color.b = 0.0
marker_text.color.a = 1.0
marker_text.text = class_name
marker_array_msg.markers.append(marker_text)
# Point Cloud Marker
if len(points_map) > 0:
marker_pc = Marker()
marker_pc.header.frame_id = "map"
marker_pc.header.stamp = rgb_msg.header.stamp
marker_pc.ns = "yolo_3d_pointclouds"
marker_pc.id = i
marker_pc.type = Marker.POINTS
marker_pc.action = Marker.ADD
marker_pc.lifetime = rclpy.duration.Duration(seconds=1.0).to_msg()
# Cyan color
marker_pc.color.r = 0.0
marker_pc.color.g = 1.0
marker_pc.color.b = 1.0
marker_pc.color.a = 0.8
marker_pc.scale.x = 0.02
marker_pc.scale.y = 0.02
marker_pc.points = [Point(x=float(pt[0]), y=float(pt[1]), z=float(pt[2])) for pt in points_map]
pc_marker_array_msg.markers.append(marker_pc)
# --- STEP 5: PUBLISH ---
pub_bbox.publish(bbox_list_msg)
pub_markers.publish(marker_array_msg)
pub_pc_markers.publish(pc_marker_array_msg)
# Publish Debug Images
try:
# Color the depth image for debugging
depth_copy = np.copy(cv_depth)
if depth_copy.dtype == np.uint16:
depth_float = depth_copy.astype(np.float32) * self.depth_scale
else:
depth_float = depth_copy.astype(np.float32)
# Clean NaNs and Infs
depth_float[~np.isfinite(depth_float)] = 0.0
# Normalize to 0-255 using actual range
max_val = np.max(depth_float)
if max_val > 0.01:
valid_depths = depth_float[depth_float > 0.01]
if len(valid_depths) > 0:
p99 = np.percentile(valid_depths, 99)
max_dist = float(max(p99, 1.0))
else:
max_dist = 5.0
depth_clipped = np.clip(depth_float, 0.0, max_dist)
depth_norm = (depth_clipped / max_dist * 255.0).astype(np.uint8)
else:
depth_norm = np.zeros_like(depth_float, dtype=np.uint8)
# Apply jet colormap (invert to make close red and far blue)
depth_colored = cv2.applyColorMap(255 - depth_norm, cv2.COLORMAP_JET)
# Make background black for zero/invalid depth values
invalid_mask = (depth_float <= 0.01)
depth_colored[invalid_mask] = (0, 0, 0)
# Convert to message and publish
depth_colored_msg = self.bridge.cv2_to_imgmsg(depth_colored, encoding='bgr8')
depth_colored_msg.header = depth_msg.header
self.pub_debug_depth_colored.publish(depth_colored_msg)
# Convert segmented BGR to message and publish
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}")
# Publish Point Cloud
if all_cloud_points:
final_cloud = np.vstack(all_cloud_points).astype(np.float32)
header = Header()
header.stamp = rgb_msg.header.stamp
header.frame_id = "map"
pc_msg = pc2.create_cloud(header, [
PointField(name='x', offset=0, datatype=PointField.FLOAT32, count=1),
PointField(name='y', offset=4, datatype=PointField.FLOAT32, count=1),
PointField(name='z', offset=8, datatype=PointField.FLOAT32, count=1),
PointField(name='intensity', offset=12, datatype=PointField.FLOAT32, count=1),
], final_cloud)
pub_cloud.publish(pc_msg)
t_end = time.perf_counter()
total_duration_ms = (t_end - t0) * 1000
inference_duration_ms = (t_inf_end - t_inf_start) * 1000
geometry_duration_ms = total_duration_ms - inference_duration_ms
self.get_logger().info(
f"[{source_name}] FastSAM Latency: {inference_duration_ms:.2f} ms | "
f"Geometry/Total: {geometry_duration_ms:.2f}/{total_duration_ms:.2f} ms"
)
except Exception as e:
self.get_logger().error(f"[{source_name}] Pipeline Error: {e}")
import traceback
traceback.print_exc()
def main(args=None):
rclpy.init(args=args)
node = ObjectLocalizationNode()
executor = MultiThreadedExecutor()
executor.add_node(node)
try:
executor.spin()
except KeyboardInterrupt:
pass
finally:
node.destroy_node()
if rclpy.ok():
rclpy.shutdown()
if __name__ == '__main__':
main()
@@ -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
@@ -17,9 +17,14 @@
# TRANSIENT_LOCAL QoS policy to ensure late-joining nodes receive all static TF data.
# ==============================================================================
import os
import rclpy
import tf2_ros
from rclpy.node import Node
from rclpy.qos import QoSProfile, DurabilityPolicy
from rclpy.clock import JumpThreshold
from rclpy.duration import Duration
from rclpy.parameter import Parameter
# Import ROS2 standard messages for geometry, visualization, and transforms
from geometry_msgs.msg import PoseWithCovarianceStamped
@@ -34,7 +39,11 @@ class OdomVisualizationNode(Node):
"""
def __init__(self):
# Initialize the parent Node class with the node name 'odom_vizualization_node'
super().__init__('odom_vizualization_node')
# and override use_sim_time default to True for bag file playbacks
super().__init__(
'odom_vizualization_node',
parameter_overrides=[Parameter('use_sim_time', value=True)]
)
# ----------------------------------------------------------------------
# State Storage & Initialization
@@ -50,20 +59,30 @@ class OdomVisualizationNode(Node):
# This list is updated whenever RTAB-Map publishes an optimized map graph.
self.trajectory_points = []
# Initialize TF Buffer and Listener for high-frequency pose lookup
self.tf_buffer = tf2_ros.Buffer()
self.tf_listener = tf2_ros.TransformListener(self.tf_buffer, self)
# Clear the TF buffer when time jumps (e.g. rosbag loops or simulation resets)
try:
threshold = JumpThreshold(
min_forward=Duration(seconds=1),
min_backward=Duration(seconds=-1),
on_clock_change=True
)
self.jump_handle = self.get_clock().create_jump_callback(
threshold,
post_callback=self.time_jump_callback
)
except Exception as e:
self.get_logger().warn(f'Failed to register time jump callback: {e}')
# Create a timer to lookup the robot pose at 20 Hz (0.05 seconds) and publish markers
self.viz_timer = self.create_timer(0.05, self.viz_timer_callback)
# ----------------------------------------------------------------------
# ROS2 Subscribers (Subscriptions)
# ----------------------------------------------------------------------
# Subscribe to RTAB-Map's localization pose.
# Topic: '/rtabmap/localizationPose' (geometry_msgs/PoseWithCovarianceStamped)
# Purpose: Retrieves the real-time estimated position and orientation of the robot
# with respect to the map frame, updated by the SLAM/localization node.
self.pose_sub = self.create_subscription(
PoseWithCovarianceStamped,
'/rtabmap/localizationPose',
self.pose_callback,
10
)
# Subscribe to RTAB-Map's status info.
# Topic: '/rtabmap/info' (rtabmap_msgs/Info)
@@ -134,36 +153,7 @@ class OdomVisualizationNode(Node):
# Log node initialization status
self.get_logger().info('Odom/SLAM Pose, Loop Closure, and TF Static Filter Node initialized')
def pose_callback(self, msg):
"""
Callback triggered when a new localization pose is received.
Stores the incoming pose, logs the coordinates, and creates visualization
markers (an arrow for heading and a sphere for position) to render in RViz.
Args:
msg (geometry_msgs.msg.PoseWithCovarianceStamped): The estimated pose of the robot.
"""
# Update the latest pose storage
self.latest_pose = msg
# Extract position fields for easy logging and inspection
pos = msg.pose.pose.position
self.get_logger().info(f"[ROBOT POSE] x: {pos.x:.3f}, y: {pos.y:.3f}, z: {pos.z:.3f}")
# Instantiate a MarkerArray to hold both visual components (Arrow and Sphere)
marker_array = MarkerArray()
# 1. Generate an arrow marker representing the robot's orientation and position
arrow_marker = self.create_pose_arrow(msg)
marker_array.markers.append(arrow_marker)
# 2. Generate a sphere marker to mark the central position coordinate clearly
position_marker = self.create_position_sphere(msg)
marker_array.markers.append(position_marker)
# Publish the MarkerArray to RViz
self.pose_marker_pub.publish(marker_array)
# pose_callback removed in favor of viz_timer_callback for high frequency visualization
def info_callback(self, msg):
"""
@@ -247,7 +237,11 @@ class OdomVisualizationNode(Node):
msg (tf2_msgs.msg.TFMessage): List of static coordinate frame transforms.
"""
updated = False
current_time = self.get_clock().now().to_msg()
for transform in msg.transforms:
# Override timestamp to current time to prevent TF_OLD_DATA warnings
transform.header.stamp = current_time
exists = False
# Look for an existing cached transform matching the parent and child frame IDs
for cached in self.cached_static_transforms:
@@ -256,7 +250,7 @@ class OdomVisualizationNode(Node):
exists = True
# Update transform values (translation, rotation, and timestamp) in case of changes
cached.transform = transform.transform
cached.header.stamp = transform.header.stamp
cached.header.stamp = current_time
break
# If this is a new static transform, add it to our cache
@@ -272,94 +266,77 @@ class OdomVisualizationNode(Node):
out_msg.transforms = self.cached_static_transforms
self.tf_static_pub.publish(out_msg)
def create_pose_arrow(self, pose_msg):
def time_jump_callback(self, jump_info):
"""
Callback triggered when a clock time jump is detected (e.g., when a rosbag loops or simulation resets).
Clears the TF buffer and republishes the cached static transforms with updated timestamps.
"""
self.get_logger().info("Time jump detected! Clearing TF buffer and republishing static transforms.")
self.tf_buffer.clear()
if self.cached_static_transforms:
current_time = self.get_clock().now().to_msg()
for transform in self.cached_static_transforms:
transform.header.stamp = current_time
out_msg = TFMessage()
out_msg.transforms = self.cached_static_transforms
self.tf_static_pub.publish(out_msg)
def create_pose_arrow(self, header, translation, rotation):
"""
Constructs a red 3D Arrow Marker representing the robot's current position and orientation.
Args:
pose_msg (geometry_msgs.msg.PoseWithCovarianceStamped): Pose data source.
Returns:
visualization_msgs.msg.Marker: Fully populated arrow marker ready for publishing.
"""
marker = Marker()
# Copy the header (timestamp) from the pose message, but force the frame_id to "map"
marker.header = pose_msg.header
marker.header = header
marker.header.frame_id = "map"
# Namespace and ID: uniquely identifies this marker within RViz to allow updates/overwrites
marker.ns = "robot_pose"
marker.id = 0
# Marker shape type: ARROW
marker.type = Marker.ARROW
# Action: ADD (creates or updates the marker)
marker.action = Marker.ADD
# Assign the complete pose (position coordinates and orientation quaternion)
marker.pose = pose_msg.pose.pose
marker.pose.position.x = translation.x
marker.pose.position.y = translation.y
marker.pose.position.z = translation.z
marker.pose.orientation = rotation
# Set physical dimensions of the arrow (in meters)
marker.scale.x = 0.5 # Shaft/total length
marker.scale.y = 0.05 # Shaft width
marker.scale.z = 0.05 # Shaft height
# Set color to solid bright red (RGBA: 1.0, 0.0, 0.0, 1.0)
marker.color.r = 1.0
marker.color.g = 0.0
marker.color.b = 0.0
marker.color.a = 1.0 # Fully opaque
marker.color.a = 1.0
# Lifetime: Setting to 0 indicates the marker should persist indefinitely until replaced or deleted
marker.lifetime = rclpy.duration.Duration(seconds=0).to_msg()
return marker
def create_position_sphere(self, pose_msg):
def create_position_sphere(self, header, translation):
"""
Constructs a semi-transparent green Sphere Marker representing the robot's current position.
Args:
pose_msg (geometry_msgs.msg.PoseWithCovarianceStamped): Pose data source.
Returns:
visualization_msgs.msg.Marker: Fully populated sphere marker ready for publishing.
"""
marker = Marker()
# Setup header details with frame fixed to "map"
marker.header = pose_msg.header
marker.header = header
marker.header.frame_id = "map"
# Separate namespace and unique ID to ensure it doesn't conflict with the arrow marker
marker.ns = "robot_position"
marker.id = 1
# Marker shape type: SPHERE
marker.type = Marker.SPHERE
marker.action = Marker.ADD
# Copy the position coordinates. Orientation quaternion is set to identity (w=1.0)
# since rotation does not affect the visual presentation of a sphere.
marker.pose.position = pose_msg.pose.pose.position
marker.pose.position.x = translation.x
marker.pose.position.y = translation.y
marker.pose.position.z = translation.z
marker.pose.orientation.w = 1.0
# Set diameter of the sphere to 0.2 meters in all axes
marker.scale.x = 0.2
marker.scale.y = 0.2
marker.scale.z = 0.2
# Set color to semi-transparent green (RGBA: 0.0, 1.0, 0.0, 0.8)
marker.color.r = 0.0
marker.color.g = 1.0
marker.color.b = 0.0
marker.color.a = 0.8 # Slightly transparent to make the arrow inside visible
marker.color.a = 0.8
# Indefinite persistence
marker.lifetime = rclpy.duration.Duration(seconds=0).to_msg()
return marker
def create_trajectory(self, frame_id):
@@ -404,6 +381,134 @@ class OdomVisualizationNode(Node):
return marker
def create_robot_mesh(self, header, translation, rotation):
"""
Constructs a MESH_RESOURCE Marker representing the Husarion Panther chassis.
"""
marker = Marker()
marker.header = header
marker.header.frame_id = "map"
marker.ns = "robot_mesh"
marker.id = 3
marker.type = Marker.MESH_RESOURCE
marker.action = Marker.ADD
q = rotation
p = translation
h = 0.1825 # wheel radius / base height offset
dx = 2.0 * h * (q.x * q.z + q.y * q.w)
dy = 2.0 * h * (q.y * q.z - q.x * q.w)
dz = h * (q.w * q.w - q.x * q.x - q.y * q.y + q.z * q.z)
marker.pose.position.x = p.x + dx
marker.pose.position.y = p.y + dy
marker.pose.position.z = p.z + dz
marker.pose.orientation = q
marker.scale.x = 1.0
marker.scale.y = 1.0
marker.scale.z = 1.0
marker.mesh_resource = "package://scene_graph_generation_pipeline/meshes/panther/base.dae"
marker.mesh_use_embedded_materials = True
marker.color.r = 1.0
marker.color.g = 1.0
marker.color.b = 1.0
marker.color.a = 1.0
marker.lifetime = rclpy.duration.Duration(seconds=0).to_msg()
return marker
def create_wheel_marker(self, header, translation, rotation, prefix, offset_x, offset_y, wheel_type="WH01"):
"""
Constructs a MESH_RESOURCE Marker representing a single wheel.
"""
marker = Marker()
marker.header = header
marker.header.frame_id = "map"
marker.ns = f"robot_wheel_{prefix}"
marker.id = 4 + ("fl", "fr", "rl", "rr").index(prefix)
marker.type = Marker.MESH_RESOURCE
marker.action = Marker.ADD
q = rotation
p = translation
vx = offset_x
vy = offset_y
vz = 0.1825
tx = 2.0 * (q.y * vz - q.z * vy)
ty = 2.0 * (q.z * vx - q.x * vz)
tz = 2.0 * (q.x * vy - q.y * vx)
dx = vx + q.w * tx + (q.y * tz - q.z * ty)
dy = vy + q.w * ty + (q.z * tx - q.x * tz)
dz = vz + q.w * tz + (q.x * ty - q.y * tx)
marker.pose.position.x = p.x + dx
marker.pose.position.y = p.y + dy
marker.pose.position.z = p.z + dz
marker.pose.orientation = q
marker.scale.x = 1.0
marker.scale.y = 1.0
marker.scale.z = 1.0
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
marker.color.g = 0.8
marker.color.b = 0.8
marker.color.a = 1.0
marker.lifetime = rclpy.duration.Duration(seconds=0).to_msg()
return marker
def viz_timer_callback(self):
"""
Timer callback to lookup the latest robot pose from the TF tree and publish all markers at high frequency.
"""
try:
trans = self.tf_buffer.lookup_transform(
'map',
'base_footprint',
rclpy.time.Time()
)
# Setup headers (override stamp to match TF timestamp and set frame to map)
header = trans.header
header.frame_id = "map"
translation = trans.transform.translation
rotation = trans.transform.rotation
marker_array = MarkerArray()
# # 1. Pose Arrow
# arrow_marker = self.create_pose_arrow(header, translation, rotation)
# marker_array.markers.append(arrow_marker)
# # 2. Position Sphere
# position_marker = self.create_position_sphere(header, translation)
# marker_array.markers.append(position_marker)
# 3. Robot chassis mesh
robot_mesh_marker = self.create_robot_mesh(header, translation, rotation)
marker_array.markers.append(robot_mesh_marker)
# 4. Wheel markers
for prefix, ox, oy in [("fl", 0.22, 0.3485), ("fr", 0.22, -0.3485), ("rl", -0.22, 0.3485), ("rr", -0.22, -0.3485)]:
wheel_marker = self.create_wheel_marker(header, translation, rotation, prefix, ox, oy)
marker_array.markers.append(wheel_marker)
self.pose_marker_pub.publish(marker_array)
except (tf2_ros.LookupException, tf2_ros.ConnectivityException, tf2_ros.ExtrapolationException):
pass
def main(args=None):
"""
Main entry point for execution. Initialises ROS2 communication context,
@@ -425,8 +530,9 @@ def main(args=None):
finally:
# Clean up node resources explicitly
node.destroy_node()
# Shutdown ROS2 context
rclpy.shutdown()
# Shutdown ROS2 context safely
if rclpy.ok():
rclpy.shutdown()
if __name__ == '__main__':
main()
@@ -0,0 +1 @@
# Initialize room_classification package
@@ -0,0 +1,151 @@
def get_filtered_mpcat40_list():
data = """
mpcat40index mpcat40 hex wnsynsetkey nyu40 skip labels
0 void #ffffff void remove,void
1 wall #aec7e8 wall.n.01,baseboard.n.01,paneling.n.01 wall wallpaper
2 floor #708090 floor.n.01,rug.n.01,mat.n.01,bath_mat.n.01,landing.n.01 floor,floor mat
3 chair #98df8a chair.n.01,beanbag.n.01 chair
4 door #c5b0d5 door.n.01,doorframe.n.01,doorway.n.01,doorknob.n.01,archway.n.01 door garage door
5 table #ff7f0e table.n.02,dressing.n.04 table,desk counter.n.01
6 picture #d62728 picture.n.01,photograph.n.01,picture_frame.n.01 picture
7 cabinet #1f77b4 cabinet.n.01,cupboard.n.01 cabinet
8 cushion #bcbd22 cushion.n.03 pillow couch cushion
9 window #ff9896 window.n.01,windowsill.n.01,window_frame.n.01,windowpane.n.02,window_screen.n.01 window
10 sofa #2ca02c sofa.n.01 sofa
11 bed #e377c2 bed.n.01,bedpost.n.01,bedstead.n.01,headboard.n.01,footboard.n.01,bedspread.n.01,mattress.n.01,sheet.n.03 bed
12 curtain #de9ed6 curtain.n.01 curtain,shower curtain curtain rod,shower curtain rod,shower rod
13 chest_of_drawers #9467bd chest_of_drawers.n.01,drawer.n.01 dresser,night stand
14 plant #8ca252 plant.n.02
15 sink #843c39 sink.n.01 sink
16 stairs #9edae5 step.n.04,stairway.n.01,stairwell.n.01
17 ceiling #9c9ede ceiling.n.01,roof.n.01 ceiling
18 toilet #e7969c toilet.n.01,bidet.n.01 toilet
19 stool #637939 stool.n.01
20 towel #8c564b towel.n.01 towel
21 mirror #dbdb8d mirror.n.01 mirror
22 tv_monitor #d6616b display.n.06 television
23 shower #cedb9c shower.n.01,showerhead.n.01
24 column #e7ba52 column.n.07,post.n.04
25 bathtub #393b79 bathtub.n.01 bathtub
26 counter #a55194 countertop.n.01,counter.n.01,kitchen_island.n.01 counter
27 fireplace #ad494a fireplace.n.01,mantel.n.01
28 lighting #b5cf6b lamp.n.02,lampshade.n.01,light.n.02,chandelier.n.01,spotlight.n.02 lamp
29 beam #5254a3 beam.n.02
30 railing #bd9e39 railing.n.01,bannister.n.02
31 shelving #c49c94 bookshelf.n.01,shelf.n.01,rack.n.05 shelves
32 blinds #f7b6d2 window_blind.n.01 blinds
33 gym_equipment #6b6ecf sports_equipment.n.01,treadmill.n.01,exercise_bike.n.01
34 seating #ffbb78 bench.n.01,seat.n.03
35 board_panel #c7c7c7 panel.n.01 whiteboard board
36 furniture #8c6d31 furniture.n.01 otherfurniture
37 appliances #e7cb94 home_appliance.n.01,stove.n.02,dryer.n.01 refridgerator washing machine and dryer
38 clothes #ce6dbd clothing.n.01 clothes
39 objects #17becf physical_object.n.01,material.n.01 books,paper,box,bag,otherprop structure.n.01,way.n.06,vent.n.01,unknown.n.01,pool.n.01
40 misc #7f7f7f person,otherstructure unknown.n.01
41 unlabeled #000000 unknown.n.01 unknown
"""
lines = data.strip().split('\n')
return [line.split('\t')[1] for line in lines[1:]]
room_classes = [
['a', 'bathroom'], # (should have a toilet and a sink)
['b', 'bedroom'],
['c', 'closet'],
['d', 'dining room'], # (includes “breakfast rooms” other rooms people mainly eat in)
['e', 'entryway/foyer/lobby'], # (should be the front door, not any door)
['f', 'familyroom'], # (should be a room that a family hangs out in, not any area with couches)
['g', 'garage'],
['h', 'hallway'],
['i', 'library'], # (should be room like a library at a university, not an individual study)
['j', 'laundryroom/mudroom'], # (place where people do laundry, etc.)
['k', 'kitchen'],
['l', 'living room'], # (should be the main “showcase” living room in a house, not any area with couches)
['m', 'meetingroom/conferenceroom'],
['n', 'lounge'], # (any area where people relax in comfy chairs/couches that is not the family room or living room
['o', 'office'], # (usually for an individual, or a small set of people)
['p', 'porch/terrace/deck/driveway'], # (must be outdoors on ground level)
['r', 'rec/game'], # (should have recreational objects, like pool table, etc.)
['s', 'stairs'],
['t', 'toilet'], # (should be a small room with ONLY a toilet)
['u', 'utilityroom/toolroom'],
['v', 'tv'], # (must have theater-style seating)
['w', 'workout/gym/exercise'],
['x', 'outdoor areas'], # containing grass, plants, bushes, trees, etc.
['y', 'balcony'], # (must be outside and must not be on ground floor)
['z', 'other room'], # (it is clearly a room, but the function is not clear)
['B', 'bar'],
['C', 'classroom'],
['D', 'dining booth'],
['S', 'spa/sauna'],
['Z', 'junk'], # (reflections of mirrors, random points floating in space, etc.)
['-', 'no label']
]
room_label_blacklist = ['utilityroom/toolroom', 'tv', 'toilet', 'stairs', 'spa/sauna', 'rec/game', 'outdoor areas', 'other room', 'library', 'junk', 'bar', 'garage', 'classroom',
'entryway/foyer/lobby', 'familyroom', 'balcony', 'laundryroom/mudroom', 'meetingroom/conferenceroom', 'workout/gym/exercise', 'dining booth', 'porch/terrace/deck/driveway', 'lounge']
object_label_blacklist = ['void', 'wall', 'floor', 'objects', 'misc', 'unlabeled']
room_label_blacklist_ = [
'closet',
'dining room', # (includes “breakfast rooms” other rooms people mainly eat in)
'entryway/foyer/lobby', # (should be the front door, not any door)
'familyroom', # (should be a room that a family hangs out in, not any area with couches)
'garage',
'library', # (should be room like a library at a university, not an individual study)
'laundryroom/mudroom', # (place where people do laundry, etc.)
'kitchen',
'living room', # (should be the main “showcase” living room in a house, not any area with couches)
'meetingroom/conferenceroom',
'lounge', # (any area where people relax in comfy chairs/couches that is not the family room or living room
'office', # (usually for an individual, or a small set of people)
'porch/terrace/deck/driveway', # (must be outdoors on ground level)
'rec/game', # (should have recreational objects, like pool table, etc.)
'stairs',
'toilet', # (should be a small room with ONLY a toilet)
'utilityroom/toolroom',
'tv', # (must have theater-style seating)
'workout/gym/exercise',
'outdoor areas', # containing grass, plants, bushes, trees, etc.
'balcony', # (must be outside and must not be on ground floor)
'other room', # (it is clearly a room, but the function is not clear)
'bar',
'classroom',
'dining booth',
'spa/sauna',
'junk', # (reflections of mirrors, random points floating in space, etc.)
'no label'
]
mpcat40_mapping = [
['tv', 'tv_monitor'],
['potted plant', 'plant'],
['couch', 'sofa'],
['bottle'],
['mouse'],
['laptop'],
['cup'],
['book'],
['remote'],
['handbag', 'clothes'],
['dining table', 'table'],
['keyboard'],
['scissors'],
['refrigerator', 'appliances']
]
def object_is_in_mpcat40(detected_object):
for i in mpcat40_mapping:
if detected_object == i[0]:
if len(i) > 1:
detected_object = i[1]
mpcat40_list = get_filtered_mpcat40_list()
for i in range(len(mpcat40_list)):
if mpcat40_list[i] == detected_object:
return i
return -1
@@ -0,0 +1,209 @@
#!/usr/bin/env python3
import rclpy
from rclpy.node import Node
from std_msgs.msg import String, Int32
from scene_graph_interfaces.msg import ClassifiedRoom, RoomWithObjects
import time
import numpy as np
import pickle
import os
from ament_index_python.packages import get_package_share_directory
# Relative import within the package
from . import classification_utils
class RoomClassificationNode(Node):
def __init__(self) -> None:
super().__init__('room_classification_node')
# Subscribe to room_with_objects topic
self.room_with_objects_sub = self.create_subscription(
RoomWithObjects,
'/scene/graph/room_with_objects',
self.room_with_objects_callback,
10
)
# Publisher for classified rooms
self.classified_room_pub = self.create_publisher(
ClassifiedRoom,
'/scene_graph/classified_room',
10
)
self.configured = False
# Load the classifier model
try:
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')
except Exception:
model_path = os.path.join(os.path.dirname(__file__), 'rf_classifier.pkl')
self.get_logger().info(f"Loading classifier model from: {model_path}")
with open(model_path, 'rb') as f:
self.rf_classifier = pickle.load(f)
self.get_logger().info('Model loaded successfully')
self.configured = True
self.mpcat40_mapping = {
"person": "misc",
"bicycle": "gym_equipment",
"car": "misc",
"motorcycle": "gym_equipment",
"airplane": "misc",
"bus": "misc",
"train": "misc",
"truck": "misc",
"boat": "misc",
"traffic light": "lighting",
"fire hydrant": "misc",
"stop sign": "misc",
"parking meter": "misc",
"bench": "seating",
"bird": "misc",
"cat": "misc",
"dog": "misc",
"horse": "misc",
"sheep": "misc",
"cow": "misc",
"elephant": "misc",
"bear": "misc",
"zebra": "misc",
"giraffe": "misc",
"backpack": "clothes",
"umbrella": "clothes",
"handbag": "clothes",
"tie": "clothes",
"suitcase": "misc",
"frisbee": "gym_equipment",
"skis": "gym_equipment",
"snowboard": "gym_equipment",
"sports ball": "gym_equipment",
"kite": "gym_equipment",
"baseball bat": "gym_equipment",
"baseball glove": "gym_equipment",
"skateboard": "gym_equipment",
"surfboard": "gym_equipment",
"tennis racket": "gym_equipment",
"bottle": "misc",
"wine glass": "misc",
"cup": "misc",
"fork": "misc",
"knife": "misc",
"spoon": "misc",
"bowl": "misc",
"banana": "misc",
"apple": "misc",
"sandwich": "misc",
"orange": "misc",
"broccoli": "misc",
"carrot": "misc",
"hot dog": "misc",
"pizza": "misc",
"donut": "misc",
"cake": "misc",
"chair": "chair",
"couch": "sofa",
"potted plant": "plant",
"bed": "bed",
"dining table": "table",
"toilet": "toilet",
"tv": "tv_monitor",
"laptop": "misc",
"mouse": "misc",
"remote": "misc",
"keyboard": "misc",
"cell phone": "misc",
"microwave": "appliances",
"oven": "appliances",
"toaster": "appliances",
"sink": "sink",
"refrigerator": "appliances",
"book": "objects",
"clock": "misc",
"vase": "misc",
"scissors": "misc",
"teddy bear": "misc",
"hair drier": "misc",
"toothbrush": "misc"
}
def room_with_objects_callback(self, msg: RoomWithObjects):
if not self.configured:
return
start_time = time.time()
detected_objects = []
for o in msg.objects:
detected_objects.append(o.data)
self.get_logger().info(f'Detected objects in room {msg.id.data}: {detected_objects}')
if len(detected_objects) == 0:
return
classified_room_name = self.classify_room(detected_objects)
if classified_room_name is None:
return
self.get_logger().info(f'[TIMING]: classification took {time.time() - start_time:.4f}s')
classified_room_msg = ClassifiedRoom()
classified_room_msg.header.stamp = self.get_clock().now().to_msg()
classified_room_msg.id = msg.id
classified_room_msg.label = String(data=classified_room_name)
self.classified_room_pub.publish(classified_room_msg)
def classify_room(self, detected_objects):
# create normalized vector
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]
i = classification_utils.object_is_in_mpcat40(do)
if i > -1:
input_vector[i] += 1
score = sum(input_vector)
if score == 0:
return None
for i in range(len(input_vector)):
input_vector[i] /= score
input_vector = [input_vector]
input_vector = np.array(input_vector)
predicted_label = self.rf_classifier.predict(input_vector)
predicted_room_name = classification_utils.room_classes[predicted_label[0]][1]
self.get_logger().info(f'Predicted label index: {predicted_label[0]} -> {predicted_room_name}')
return predicted_room_name
def main(args=None):
rclpy.init(args=args)
node = RoomClassificationNode()
try:
rclpy.spin(node)
except KeyboardInterrupt:
pass
finally:
node.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
@@ -0,0 +1 @@
# room_segmentation package init
@@ -0,0 +1,340 @@
#!/usr/bin/env python3
import math
import time
import numpy as np
import cv2
import rclpy
from rclpy.node import Node
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.
"""
def __init__(self) -> None:
super().__init__(
'room_segmentation_node',
parameter_overrides=[Parameter('use_sim_time', value=True)]
)
# Declare and read parameters
self.declare_parameter('map_topic', '/rtabmap/map')
self.declare_parameter('rooms_topic', '/scene_graph/rooms')
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.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(
OccupancyGrid,
self.map_topic,
self.map_callback,
10
)
# Publisher for rooms
self.rooms_pub = self.create_publisher(
RoomPolygonList,
self.rooms_topic,
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:
current_time = time.time()
if current_time - self.last_process_time < self.process_min_interval:
return
self.last_process_time = current_time
# Validate occupancy grid data
if not msg.data or len(msg.data) == 0:
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} "
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)
free_cleaned = cv2.morphologyEx(free_cleaned, cv2.MORPH_OPEN, kernel)
# Compute L2 Distance Transform
dist_transform = cv2.distanceTransform(free_cleaned, cv2.DIST_L2, 5)
dist_max = dist_transform.max()
if dist_max <= 0:
self.get_logger().warn("No free space found in the map.")
return
# Adaptive thresholding for seeds representing room centers
min_room_radius_px = self.min_room_radius / resolution
thresh_val = min(min_room_radius_px, 0.4 * dist_max)
thresh_val = max(thresh_val, 1.0)
ret, sure_fg = cv2.threshold(dist_transform, thresh_val, 255, 0)
sure_fg = sure_fg.astype(np.uint8)
# Find connected components (seeds)
num_labels, markers = cv2.connectedComponents(sure_fg)
# Set up markers for Watershed:
# Background is labeled 1, sure foreground is 2, 3... and unknown space is 0
unknown = cv2.subtract(free_cleaned, sure_fg)
markers = markers + 1
markers[unknown == 255] = 0
# Run watershed on inverted distance transform
dist_norm = cv2.normalize(dist_transform, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8)
input_img = cv2.cvtColor(255 - dist_norm, cv2.COLOR_GRAY2BGR)
markers = cv2.watershed(input_img, markers)
# Parse map origin position and quaternion
origin_x = msg.info.origin.position.x
origin_y = msg.info.origin.position.y
qx = msg.info.origin.orientation.x
qy = msg.info.origin.orientation.y
qz = msg.info.origin.orientation.z
qw = msg.info.origin.orientation.w
# Convert quaternion to yaw angle
siny_cosp = 2 * (qw * qz + qx * qy)
cosy_cosp = 1 - 2 * (qy * qy + qz * qz)
yaw = math.atan2(siny_cosp, cosy_cosp)
cos_yaw = math.cos(yaw)
sin_yaw = math.sin(yaw)
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
# Extract contour boundaries for each room segment
for i in range(2, num_labels + 1):
room_mask = (markers == i).astype(np.uint8) * 255
contours, _ = cv2.findContours(room_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
area = cv2.contourArea(contour)
if area < min_room_area_px:
continue
# Simplify polygon contours
approx = cv2.approxPolyDP(contour, epsilon, True)
if len(approx) < 3:
continue
room_poly = RoomPolygon()
for pt in approx:
col, row = pt[0]
# Convert pixel coordinates to map origin coordinates
col_meters = col * resolution
row_meters = row * resolution
# Apply 2D yaw rotation and translation
x_world = col_meters * cos_yaw - row_meters * sin_yaw + origin_x
y_world = col_meters * sin_yaw + row_meters * cos_yaw + origin_y
point_msg = Point()
point_msg.x = float(x_world)
point_msg.y = float(y_world)
point_msg.z = 0.0
room_poly.points.append(point_msg)
rooms_list_msg.rooms.append(room_poly)
self.rooms_pub.publish(rooms_list_msg)
# 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)
node = RoomSegmentationNode()
try:
rclpy.spin(node)
except KeyboardInterrupt:
pass
finally:
node.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
@@ -1,91 +0,0 @@
"""
A vocabulary dictionary for indoor robotics object detection that are passed to the YOLO-World model.
For each label we define a boolean that indicates whether the object is typically graspable by a robot.
Structure: Each entry is (label_name, is_graspable)
- label_name (str): Object class name for YOLO detection
- is_graspable (bool): Whether a robot arm can pick/grasp this object
"""
# Vocabulary with graspability affordances
# Format: (label_name: str, is_graspable: bool)
VOCABULARY_DATA = [
("door", False),
("chair", False),
("couch", False),
("cabinet", False),
("shelf", False),
("cupboard", False),
("dresser", False),
("wardrobe", False),
("closet", False),
("drawer", False),
("freezer", False),
("oven", False),
("microwave", False),
("stove", False),
("television", False),
("monitor", False),
("computer", False),
("laptop", False),
("keyboard", True),
("mouse", True),
("lamp", False),
("light", False),
("fan", False),
("radiator", False),
("washing machine", False),
("dryer", False),
("dishwasher", False),
("trash can", True),
("carpet", False),
("curtain", False),
("book", True),
("vase", True),
("plant", True),
("painting", False),
("clock", True),
("dish", True),
("cup", True),
("bottle", True),
("box", True),
("bag", True),
("shoe", True),
("backpack", True),
]
def get_vocabulary_list():
"""
Returns the list of vocabulary labels (class names) for YOLO-World.
Returns:
list: List of string labels in order
"""
return [label for label, _ in VOCABULARY_DATA]
def get_vocabulary_dict():
"""
Returns a dictionary mapping label names to graspability affordances.
Returns:
dict: {label_name: is_graspable, ...}
"""
return {label: is_graspable for label, is_graspable in VOCABULARY_DATA}
def get_vocabulary_with_affordances():
"""
Returns the complete vocabulary data with graspability affordances.
Returns:
list: List of tuples (label_name, is_graspable)
"""
return VOCABULARY_DATA
# For backward compatibility
def get_vocabulary():
"""Alias for get_vocabulary_list() for backward compatibility."""
return get_vocabulary_list()
@@ -1,381 +0,0 @@
#!/usr/bin/env python3
import rclpy
from rclpy.node import Node
import message_filters
from sensor_msgs.msg import Image, CameraInfo, PointCloud2, PointField
from nav_msgs.msg import Odometry
from std_msgs.msg import Header, String
from geometry_msgs.msg import Point32, Point
from scene_graph_interfaces.msg import ObjectList, Object3DBoundingBox, Object3DBoundingBoxList
from cv_bridge import CvBridge
import numpy as np
import sensor_msgs_py.point_cloud2 as pc2
import cv2
import time
from tf2_ros import Buffer, TransformListener
from visualization_msgs.msg import Marker, MarkerArray
from .sam_wrapper import SamWrapper
from .geometry_utils import GeometryUtils
class ObjectLocalizationNode(Node):
def __init__(self):
super().__init__('object_localization_node')
# --- 1. CONFIGURATION ---
model_name = 'FastSAM-s.pt'
self.depth_scale = 0.001
# --- 2. INITIALIZE MODULES ---
self.bridge = CvBridge()
self.get_logger().info(f"Initializing FastSAM Wrapper with {model_name}...")
self.sam = SamWrapper(model_name=model_name)
# --- 3. STATE ---
self.intrinsics = None
self.tf_buffer = Buffer()
self.tf_listener = TransformListener(self.tf_buffer, self)
# --- 4. SUBSCRIBERS ---
# A. Camera Intrinsics
self.get_intrinsics = self.create_subscription(
CameraInfo, '/camera/depth/camera_info', self.get_intrinsics_callback, 10)
# B. Base Synchronized Inputs
self.sub_rgb = message_filters.Subscriber(self, Image, '/scene_graph/sync/color/image_raw')
self.sub_depth = message_filters.Subscriber(self, Image, '/scene_graph/sync/depth/image_raw')
# C. Object Detection Inputs
self.sub_yolo = message_filters.Subscriber(self, ObjectList, '/scene_graph/yolo')
# --- 5. SYNCHRONIZERS ---
# Chain 1: RGB + Depth + YOLO
self.ts_yolo = message_filters.ApproximateTimeSynchronizer(
[self.sub_rgb, self.sub_depth, self.sub_yolo],
queue_size=10, slop=0.1)
self.ts_yolo.registerCallback(self.yolo_callback)
# --- 6. PUBLISHERS ---
self.pub_bbox_yolo = self.create_publisher(Object3DBoundingBoxList, '/bounding_boxes_3d/yolo', 10)
self.pub_cloud_yolo = self.create_publisher(PointCloud2, '/object_clouds/yolo', 10)
self.pub_markers_yolo = self.create_publisher(MarkerArray, '/scene_graph/viz/current_bounding_boxes_3d', 10)
self.pub_pc_markers_yolo = self.create_publisher(MarkerArray, '/bounding_boxes_3d/point_cloud_markers', 10)
self.get_logger().info("Object Localization Node Initialized. Waiting for data...")
def get_intrinsics_callback(self, msg):
if self.intrinsics is None:
self.intrinsics = {
'fx': msg.k[0], 'fy': msg.k[4],
'cx': msg.k[2], 'cy': msg.k[5]
}
self.get_logger().info(f"Intrinsics captured: {self.intrinsics}")
def yolo_callback(self, rgb_msg, depth_msg, yolo_objs_msg):
objects = yolo_objs_msg.objects
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)
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):
if self.intrinsics is None:
self.get_logger().warn(f"[{source_name}] Waiting for Camera Info...", throttle_duration_sec=2.0)
return
if not objects:
return
try:
t0 = time.perf_counter()
# --- STEP 0: LOOKUP TF TRANSFORM ---
try:
# Try exact timestamp lookup
transform = self.tf_buffer.lookup_transform(
'map',
depth_msg.header.frame_id,
depth_msg.header.stamp,
rclpy.duration.Duration(seconds=0.1)
)
except Exception as e:
# Fallback: get the latest available transform in case of clock mismatch
try:
transform = self.tf_buffer.lookup_transform(
'map',
depth_msg.header.frame_id,
rclpy.time.Time()
)
except Exception as fallback_err:
self.get_logger().warn(
f"[{source_name}] TF lookup from 'map' to '{depth_msg.header.frame_id}' failed: "
f"Exact: {e} | Fallback: {fallback_err}",
throttle_duration_sec=2.0
)
return
trans = transform.transform.translation
rot = transform.transform.rotation
translation = np.array([trans.x, trans.y, trans.z])
rotation = np.array([rot.x, rot.y, rot.z, rot.w])
# --- STEP 1: PREPARE DATA ---
cv_bgr = self.bridge.imgmsg_to_cv2(rgb_msg, desired_encoding='bgr8')
cv_rgb = cv2.cvtColor(cv_bgr, cv2.COLOR_BGR2RGB)
cv_depth = self.bridge.imgmsg_to_cv2(depth_msg, desired_encoding='passthrough')
# --- STEP 2: PREPARE BBOXES FOR FASTSAM ---
bboxes = []
valid_obj_indices = []
for i, obj in enumerate(objects):
if len(obj.bounding_box) >= 2:
x1 = obj.bounding_box[0].x
y1 = obj.bounding_box[0].y
x2 = obj.bounding_box[1].x
y2 = obj.bounding_box[1].y
bboxes.append([x1, y1, x2, y2])
valid_obj_indices.append(i)
if not bboxes:
return
# --- STEP 3: RUN FASTSAM PREDICTION ---
t_inf_start = time.perf_counter()
masks = self.sam.predict(cv_rgb, bboxes)
t_inf_end = time.perf_counter()
# --- STEP 4: GEOMETRY PROCESSING ---
bbox_list_msg = target_list_class()
bbox_list_msg.header = rgb_msg.header
bbox_list_msg.header.frame_id = "map"
marker_array_msg = MarkerArray()
pc_marker_array_msg = MarkerArray()
all_cloud_points = []
for i, bbox in enumerate(bboxes):
original_obj = objects[valid_obj_indices[i]]
# Try to use FastSAM mask if available
points_cam = None
if i < len(masks) and masks[i] is not None:
# A1. Project Mask to 3D
points_cam = GeometryUtils.project_mask_to_3d(
cv_depth, masks[i], self.intrinsics, self.depth_scale)
# Fallback to direct 2D bounding box cropping if mask projection is empty/fails
if points_cam is None or len(points_cam) < 10:
# A2. Project BBox to 3D
points_cam = GeometryUtils.project_bbox_to_3d(
cv_depth, bbox, self.intrinsics, self.depth_scale, shrink_ratio=0.15)
points_clean = GeometryUtils.clean_outliers(points_cam, std_ratio=1.5)
if len(points_clean) < 10:
continue
# B. Transform to Map Frame
points_map = GeometryUtils.transform_points(
points_clean, translation, rotation)
# C. Compute 3D BBox
bbox_data = GeometryUtils.compute_3d_bbox(points_map)
if bbox_data is None:
continue
# D. Pack Bounding Box
bbox_msg = target_item_class()
bbox_msg.name = original_obj.class_name
# Handle 'graspable' field
if isinstance(bbox_msg, Object3DBoundingBox):
bbox_msg.graspable = original_obj.graspable
# Set bounding box coordinates
p_min = Point32()
p_min.x, p_min.y, p_min.z = [float(x) for x in bbox_data['min']]
p_max = Point32()
p_max.x, p_max.y, p_max.z = [float(x) for x in bbox_data['max']]
bbox_msg.bounding_box = [p_min, p_max]
# Generate PointCloud2 for this object
pc_msg = PointCloud2()
pc_msg.header.stamp = rgb_msg.header.stamp
pc_msg.header.frame_id = "map"
if len(points_map) > 0:
pc_msg = pc2.create_cloud_xyz32(pc_msg.header, points_map.astype(np.float32))
if hasattr(bbox_msg, 'point_cloud'):
bbox_msg.point_cloud = pc_msg
bbox_list_msg.bbox.append(bbox_msg)
# ----------- LOGGER -----------
class_name = original_obj.class_name.data
min_s = f"({bbox_data['min'][0]:.2f}, {bbox_data['min'][1]:.2f}, {bbox_data['min'][2]:.2f})"
max_s = f"({bbox_data['max'][0]:.2f}, {bbox_data['max'][1]:.2f}, {bbox_data['max'][2]:.2f})"
grasp_info = f" | Grasp: {bbox_msg.graspable}" if hasattr(bbox_msg, 'graspable') else ""
# Log whether it used mask or bbox fallback
source_method = "Mask" if (i < len(masks) and masks[i] is not None and len(points_cam) >= 10) else "BBox-Fallback"
self.get_logger().info( f"[{source_name}] ID: {i} | Class: '{class_name}'{grasp_info} | Method: {source_method} | Min: {min_s} | Max: {max_s}" )
# ------------------------------
# E. Cloud Accumulation
class_id = float(i)
class_col = np.full((points_map.shape[0], 1), class_id)
points_with_id = np.hstack((points_map, class_col))
all_cloud_points.append(points_with_id)
# F. Visualization Markers
min_pt = bbox_data['min']
max_pt = bbox_data['max']
center_x = (min_pt[0] + max_pt[0]) / 2.0
center_y = (min_pt[1] + max_pt[1]) / 2.0
center_z = (min_pt[2] + max_pt[2]) / 2.0
size_x = abs(max_pt[0] - min_pt[0])
size_y = abs(max_pt[1] - min_pt[1])
size_z = abs(max_pt[2] - min_pt[2])
# Cube Marker
marker_cube = Marker()
marker_cube.header.frame_id = "map"
marker_cube.header.stamp = rgb_msg.header.stamp
marker_cube.ns = "yolo_3d_cubes"
marker_cube.id = i
marker_cube.type = Marker.CUBE
marker_cube.action = Marker.ADD
marker_cube.lifetime = rclpy.duration.Duration(seconds=1.0).to_msg()
marker_cube.pose.position.x = float(center_x)
marker_cube.pose.position.y = float(center_y)
marker_cube.pose.position.z = float(center_z)
marker_cube.pose.orientation.x = 0.0
marker_cube.pose.orientation.y = 0.0
marker_cube.pose.orientation.z = 0.0
marker_cube.pose.orientation.w = 1.0
marker_cube.scale.x = float(size_x)
marker_cube.scale.y = float(size_y)
marker_cube.scale.z = float(size_z)
marker_cube.color.r = 0.0
marker_cube.color.g = 1.0
marker_cube.color.b = 0.0
marker_cube.color.a = 0.4
marker_array_msg.markers.append(marker_cube)
# Text Marker
marker_text = Marker()
marker_text.header.frame_id = "map"
marker_text.header.stamp = rgb_msg.header.stamp
marker_text.ns = "yolo_3d_labels"
marker_text.id = i
marker_text.type = Marker.TEXT_VIEW_FACING
marker_text.action = Marker.ADD
marker_text.lifetime = rclpy.duration.Duration(seconds=1.0).to_msg()
marker_text.pose.position.x = float(center_x)
marker_text.pose.position.y = float(center_y)
marker_text.pose.position.z = float(max_pt[2] + 0.15)
marker_text.pose.orientation.x = 0.0
marker_text.pose.orientation.y = 0.0
marker_text.pose.orientation.z = 0.0
marker_text.pose.orientation.w = 1.0
marker_text.scale.z = 0.2
marker_text.color.r = 1.0
marker_text.color.g = 1.0
marker_text.color.b = 0.0
marker_text.color.a = 1.0
marker_text.text = class_name
marker_array_msg.markers.append(marker_text)
# Point Cloud Marker
if len(points_map) > 0:
marker_pc = Marker()
marker_pc.header.frame_id = "map"
marker_pc.header.stamp = rgb_msg.header.stamp
marker_pc.ns = "yolo_3d_pointclouds"
marker_pc.id = i
marker_pc.type = Marker.POINTS
marker_pc.action = Marker.ADD
marker_pc.lifetime = rclpy.duration.Duration(seconds=1.0).to_msg()
# Cyan color
marker_pc.color.r = 0.0
marker_pc.color.g = 1.0
marker_pc.color.b = 1.0
marker_pc.color.a = 0.8
marker_pc.scale.x = 0.02
marker_pc.scale.y = 0.02
marker_pc.points = [Point(x=float(pt[0]), y=float(pt[1]), z=float(pt[2])) for pt in points_map]
pc_marker_array_msg.markers.append(marker_pc)
# --- STEP 5: PUBLISH ---
pub_bbox.publish(bbox_list_msg)
pub_markers.publish(marker_array_msg)
pub_pc_markers.publish(pc_marker_array_msg)
# Publish Point Cloud
if all_cloud_points:
final_cloud = np.vstack(all_cloud_points).astype(np.float32)
header = Header()
header.stamp = rgb_msg.header.stamp
header.frame_id = "map"
pc_msg = pc2.create_cloud(header, [
PointField(name='x', offset=0, datatype=PointField.FLOAT32, count=1),
PointField(name='y', offset=4, datatype=PointField.FLOAT32, count=1),
PointField(name='z', offset=8, datatype=PointField.FLOAT32, count=1),
PointField(name='intensity', offset=12, datatype=PointField.FLOAT32, count=1),
], final_cloud)
pub_cloud.publish(pc_msg)
t_end = time.perf_counter()
total_duration_ms = (t_end - t0) * 1000
inference_duration_ms = (t_inf_end - t_inf_start) * 1000
geometry_duration_ms = total_duration_ms - inference_duration_ms
self.get_logger().info(
f"[{source_name}] FastSAM Latency: {inference_duration_ms:.2f} ms | "
f"Geometry/Total: {geometry_duration_ms:.2f}/{total_duration_ms:.2f} ms"
)
except Exception as e:
self.get_logger().error(f"[{source_name}] Pipeline Error: {e}")
import traceback
traceback.print_exc()
def main(args=None):
rclpy.init(args=args)
node = ObjectLocalizationNode()
try:
rclpy.spin(node)
except KeyboardInterrupt:
pass
finally:
node.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
@@ -1,50 +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 []
if not results or results[0].masks is None:
return []
# Extract masks, move to CPU, and convert to numpy
masks_tensor = results[0].masks.data
masks_np = masks_tensor.cpu().numpy()
# Convert to boolean masks
masks_bool = masks_np.astype(bool)
return [mask for mask in masks_bool]
+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
+13 -5
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,
@@ -14,6 +14,12 @@ setup(
('share/' + package_name, ['package.xml']),
(os.path.join('share', package_name, 'launch'),
glob('launch/*.py')),
(os.path.join('share', package_name, 'meshes', 'panther'),
glob('meshes/panther/*')),
(os.path.join('share', package_name, 'meshes', 'WH01'),
glob('meshes/WH01/*')),
(os.path.join('share', package_name, 'model'),
['scene_graph_generation_pipeline/room_classification/rf_classifier.pkl']),
],
install_requires=['setuptools', 'open3d', 'shapely', "huggingface_hub"],
zip_safe=True,
@@ -28,10 +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'
'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'
],
},
)
+43 -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
@@ -135,6 +135,48 @@ def test_compute_3d_bbox():
assert GeometryUtils.compute_3d_bbox(np.empty((0, 3))) is None
def test_compute_3d_obb():
# Let's generate a rectangular box of points that is rotated by 30 degrees around Z axis.
theta = np.radians(30.0)
c, s = np.cos(theta), np.sin(theta)
R = np.array([
[c, -s, 0.0],
[s, c, 0.0],
[0.0, 0.0, 1.0]
])
# Base box of size (2, 4, 1) centered at (5, 6, 2)
# local coordinates of 8 corners:
local_corners = np.array([
[-1.0, -2.0, -0.5],
[1.0, -2.0, -0.5],
[1.0, 2.0, -0.5],
[-1.0, 2.0, -0.5],
[-1.0, -2.0, 0.5],
[1.0, -2.0, 0.5],
[1.0, 2.0, 0.5],
[-1.0, 2.0, 0.5]
])
global_corners = (R @ local_corners.T).T + np.array([5.0, 6.0, 2.0])
obb = GeometryUtils.compute_3d_obb(global_corners)
assert obb is not None
# The center should be close to [5, 6, 2]
np.testing.assert_allclose(obb['center'], [5.0, 6.0, 2.0], atol=1e-2)
# The size should be close to 2 and 4 (order can depend on cv2 minAreaRect orientation)
sorted_obb_size = sorted(obb['size'][:2])
sorted_expected_size = sorted([2.0, 4.0])
np.testing.assert_allclose(sorted_obb_size, sorted_expected_size, atol=1e-2)
np.testing.assert_allclose(obb['size'][2], 1.0, atol=1e-2)
# 8 corners check
assert len(obb['corners']) == 8
# Empty points check
assert GeometryUtils.compute_3d_obb(np.empty((0, 3))) is None
def test_transform_points_camera_to_map():
# Setup camera point along Z-axis (optical axis)
points_cam = np.array([
+33
View File
@@ -0,0 +1,33 @@
import rclpy
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_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_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()
# Check default parameter is 5.0
max_dist = node.get_parameter('max_object_distance').get_parameter_value().double_value
assert max_dist == 5.0
# Set parameter to a new value
node.set_parameters([Parameter('max_object_distance', Parameter.Type.DOUBLE, 3.5)])
max_dist = node.get_parameter('max_object_distance').get_parameter_value().double_value
assert max_dist == 3.5
node.destroy_node()
# Shutdown rclpy to release any node resources/executors
rclpy.shutdown()
+59
View File
@@ -0,0 +1,59 @@
# Copyright 2026 Developer
# Licensed under the Apache License, Version 2.0
"""Test suite for the room classification node."""
from unittest.mock import MagicMock, patch
import pytest
import rclpy
from scene_graph_generation_pipeline.room_classification.room_classification_node import ( # noqa: E501
RoomClassificationNode
)
@pytest.fixture(scope="function")
def ros_init():
"""Initialize and shutdown the ROS2 context for testing."""
if not rclpy.ok():
rclpy.init()
yield
if rclpy.ok():
rclpy.shutdown()
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=mock_classifier):
node = RoomClassificationNode()
# Test case 1: room containing a refrigerator returns "kitchen"
room_label_kitchen = node.classify_room(
['chair', 'table', 'refrigerator', 'sink']
)
assert room_label_kitchen == 'kitchen'
# Test case 2: room containing a refrigerator (different casing)
room_label_kitchen_caps = node.classify_room(
['REFRIGERATOR', 'cup']
)
assert room_label_kitchen_caps == 'kitchen'
# Test case 3: room without a refrigerator returns "office"
room_label_office = node.classify_room(['chair', 'table', 'laptop'])
assert room_label_office == 'office'
# Test case 4: room with unknown objects returns None
room_label_unknown = node.classify_room(['random_unknown_object'])
assert room_label_unknown is None
node.destroy_node()
+213
View File
@@ -0,0 +1,213 @@
# Copyright 2026 Developer
# Licensed under the Apache License, Version 2.0
"""Test suite for the scene graph fusion logic."""
import rclpy
import numpy as np
import pytest
from geometry_msgs.msg import Point
from scene_graph_interfaces.msg import RoomPolygonList, RoomPolygon
from scene_graph_generation_pipeline.scene_graph_fusion.scene_graph_fusion_node import ( # noqa: E501
GraphManagementNode, ObjectNode, RoomNode, FunctionalElementNode
)
@pytest.fixture(scope="module")
def ros_init():
"""Initialize and shutdown the ROS2 context for testing."""
if not rclpy.ok():
rclpy.init()
yield
if rclpy.ok():
rclpy.shutdown()
def test_room_containment_and_edge_preservation(ros_init):
"""Test room containment match and preservation of functional edges."""
node = GraphManagementNode()
# Verify default room exists
assert node.rooms_segmented is False
assert 1 in node.scene_graph
# Create an object and a functional element child
obj = ObjectNode(id=10, class_id="chair")
# Manually populate point cloud so it has a centroid
pts_obj = np.array([[2.0, 2.0, 0.0]])
obj.point_cloud.points = node.merge_point_clouds(None, pts_obj).points
fn = FunctionalElementNode(id=20, class_id="handle")
pts_fn = np.array([[2.1, 2.0, 0.0]])
fn.point_cloud.points = node.merge_point_clouds(None, pts_fn).points
# Add nodes to graph
node.scene_graph.add_node(10, data=obj)
node.scene_graph.add_node(20, data=fn)
# Add default room edge and parent-child edge
node.scene_graph.add_edge(1, 10)
node.scene_graph.add_edge(10, 20)
fn.parent_object_id = 10
# Add an orphan functional element
orphan_fn = FunctionalElementNode(id=30, class_id="drawer")
pts_orphan = np.array([[5.0, 5.0, 0.0]])
orphan_fn.point_cloud.points = node.merge_point_clouds(None, pts_orphan).points # noqa: E501
node.scene_graph.add_node(30, data=orphan_fn)
node.scene_graph.add_edge(1, 30)
orphan_fn.room_id = 1
# Verify edges exist
assert node.scene_graph.has_edge(10, 20)
assert node.scene_graph.has_edge(1, 10)
assert node.scene_graph.has_edge(1, 30)
# Now simulate room segmentation message
msg = RoomPolygonList()
r1 = RoomPolygon()
r1.points = [
Point(x=0.0, y=0.0),
Point(x=4.0, y=0.0),
Point(x=4.0, y=4.0),
Point(x=0.0, y=4.0)
]
r2 = RoomPolygon()
r2.points = [
Point(x=10.0, y=10.0),
Point(x=12.0, y=10.0),
Point(x=12.0, y=12.0),
Point(x=10.0, y=12.0)
]
r3 = RoomPolygon()
r3.points = [
Point(x=4.5, y=4.5),
Point(x=6.0, y=4.5),
Point(x=6.0, y=6.0),
Point(x=4.5, y=6.0)
]
msg.rooms = [r1, r2, r3]
# Trigger rooms_callback
node.rooms_callback(msg)
# Segmented should now be True
assert node.rooms_segmented is True
# Check that new room nodes are added.
room_ids = []
for n in node.scene_graph.nodes:
if isinstance(node.scene_graph.nodes[n].get("data"), RoomNode):
room_ids.append(n)
assert 1 not in room_ids
assert len(room_ids) == 3
# Let's find which room is which by containment
room_100_id = None
room_300_id = None
for r_id in room_ids:
r_node = node.scene_graph.nodes[r_id]["data"]
# Check center to identify room
if abs(r_node.center_point[0] - 2.0) < 0.1: # (0+4)/2 = 2.0
room_100_id = r_id
elif abs(r_node.center_point[0] - 5.25) < 0.1: # (4.5+6)/2 = 5.25
room_300_id = r_id
assert room_100_id is not None
assert room_300_id is not None
# Object 10 should be assigned to room_100_id (contains (2.0, 2.0))
assert node.scene_graph.has_edge(room_100_id, 10)
# Parent-child edge between Object 10 and FunctionalElement 20 preserved
assert node.scene_graph.has_edge(10, 20)
assert fn.parent_object_id == 10
# Orphan FunctionalElement 30 should be assigned to room_300_id
assert node.scene_graph.has_edge(room_300_id, 30)
assert orphan_fn.room_id == room_300_id
# Clean up node
node.destroy_node()
def test_room_adjacency_edges(ros_init):
"""Test room-to-room adjacency edge calculations based on spatial proximity."""
node = GraphManagementNode()
# Create room segmentation message with adjacent and non-adjacent rooms
msg = RoomPolygonList()
# Room 1: centered around (1.0, 1.0)
r1 = RoomPolygon()
r1.points = [
Point(x=0.0, y=0.0),
Point(x=2.0, y=0.0),
Point(x=2.0, y=2.0),
Point(x=0.0, y=2.0)
]
# Room 2: adjacent to Room 1 (gap of 0.1m, threshold is 0.5m)
r2 = RoomPolygon()
r2.points = [
Point(x=2.1, y=0.0),
Point(x=4.1, y=0.0),
Point(x=4.1, y=2.0),
Point(x=2.1, y=2.0)
]
# Room 3: non-adjacent to Room 1 & 2 (far away)
r3 = RoomPolygon()
r3.points = [
Point(x=10.0, y=10.0),
Point(x=12.0, y=10.0),
Point(x=12.0, y=12.0),
Point(x=10.0, y=12.0)
]
msg.rooms = [r1, r2, r3]
# Trigger rooms_callback
node.rooms_callback(msg)
# Find the room node IDs
room_nodes = []
for n in node.scene_graph.nodes:
if isinstance(node.scene_graph.nodes[n].get("data"), RoomNode):
room_nodes.append(n)
assert len(room_nodes) == 3
# Resolve room IDs by centers to map back to r1, r2, r3
r1_id, r2_id, r3_id = None, None, None
for r_id in room_nodes:
r_node = node.scene_graph.nodes[r_id]["data"]
# r1 center x is 1.0
if abs(r_node.center_point[0] - 1.0) < 0.1:
r1_id = r_id
# r2 center x is 3.1
elif abs(r_node.center_point[0] - 3.1) < 0.1:
r2_id = r_id
# r3 center x is 11.0
elif abs(r_node.center_point[0] - 11.0) < 0.1:
r3_id = r_id
assert r1_id is not None
assert r2_id is not None
assert r3_id is not None
# Assert that Room 1 and Room 2 are adjacent
assert node.scene_graph.has_edge(r1_id, r2_id)
# Assert that Room 3 is not adjacent to Room 1 or Room 2
assert not node.scene_graph.has_edge(r1_id, r3_id)
assert not node.scene_graph.has_edge(r2_id, r3_id)
# Clean up node
node.destroy_node()