Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eeff4f404a |
@@ -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>
|
||||
|
||||

|
||||
---
|
||||
|
||||
### 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/
|
||||
```
|
||||
@@ -37,16 +37,6 @@ def generate_launch_description():
|
||||
remappings=[]
|
||||
)
|
||||
|
||||
# CLIP Feature Extractor Node
|
||||
clip_extractor_node = Node(
|
||||
package='scene_graph_generation_pipeline',
|
||||
executable='clip_extractor_node',
|
||||
name='clip_extractor_node',
|
||||
output='screen',
|
||||
parameters=common_params,
|
||||
remappings=[]
|
||||
)
|
||||
|
||||
# Scene Graph Fusion Node
|
||||
scene_graph_fusion_node = Node(
|
||||
package='scene_graph_generation_pipeline',
|
||||
@@ -89,8 +79,8 @@ def generate_launch_description():
|
||||
|
||||
return LaunchDescription([
|
||||
use_sim_time_arg,
|
||||
object_detection_node,
|
||||
object_localization_node,
|
||||
clip_extractor_node,
|
||||
scene_graph_fusion_node,
|
||||
odom_vizualization_node,
|
||||
room_classification_node,
|
||||
|
||||
@@ -57,16 +57,6 @@ def generate_launch_description():
|
||||
remappings=[]
|
||||
)
|
||||
|
||||
# CLIP Feature Extractor Node
|
||||
clip_extractor_node = Node(
|
||||
package='scene_graph_generation_pipeline',
|
||||
executable='clip_extractor_node',
|
||||
name='clip_extractor_node',
|
||||
output='screen',
|
||||
parameters=common_params,
|
||||
remappings=[]
|
||||
)
|
||||
|
||||
# Scene Graph Fusion Node
|
||||
scene_graph_fusion_node = Node(
|
||||
package='scene_graph_generation_pipeline',
|
||||
@@ -119,8 +109,8 @@ def generate_launch_description():
|
||||
|
||||
return LaunchDescription([
|
||||
rtabmap_slam,
|
||||
object_detection_node,
|
||||
object_localization_node,
|
||||
clip_extractor_node,
|
||||
scene_graph_fusion_node,
|
||||
odom_vizualization_node,
|
||||
room_classification_node,
|
||||
|
||||
@@ -1,153 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import rclpy
|
||||
from rclpy.node import Node
|
||||
import torch
|
||||
import open_clip
|
||||
import numpy as np
|
||||
from PIL import Image as PILImage
|
||||
from cv_bridge import CvBridge, CvBridgeError
|
||||
from scene_graph_interfaces.srv import ExtractClipFeatures
|
||||
from rclpy.parameter import Parameter
|
||||
|
||||
# Standard indoor categories vocabulary for zero-shot classification
|
||||
DEFAULT_VOCABULARY = [
|
||||
"chair", "table", "desk", "sofa", "armchair", "bookshelf", "cabinet", "drawer", "wardrobe",
|
||||
"bed", "cushion", "pillow", "blanket", "carpet", "rug",
|
||||
"lamp", "light", "clock", "mirror", "trash bin", "bin",
|
||||
"cup", "glass", "mug", "bottle", "plate", "bowl", "fork", "knife", "spoon",
|
||||
"laptop", "computer", "keyboard", "mouse", "monitor", "screen", "printer", "telephone",
|
||||
"door", "window", "wall", "floor", "ceiling", "stairs", "railing",
|
||||
"plant", "flowerpot", "vase", "painting", "poster", "sculpture",
|
||||
"refrigerator", "fridge", "microwave", "oven", "stove", "sink", "dishwasher",
|
||||
"washing machine", "dryer", "bathtub", "shower", "toilet"
|
||||
]
|
||||
|
||||
class ClipExtractorNode(Node):
|
||||
def __init__(self):
|
||||
super().__init__(
|
||||
'clip_extractor_node',
|
||||
parameter_overrides=[Parameter('use_sim_time', value=True)]
|
||||
)
|
||||
|
||||
self.bridge = CvBridge()
|
||||
|
||||
# Declare parameters for model config
|
||||
self.declare_parameter('model_name', 'ViT-H-14')
|
||||
self.declare_parameter('pretrained', 'laion2b_s32b_b79k')
|
||||
|
||||
model_name = self.get_parameter('model_name').get_parameter_value().string_value
|
||||
pretrained = self.get_parameter('pretrained').get_parameter_value().string_value
|
||||
|
||||
self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||
self.get_logger().info(f"Loading CLIP model {model_name} (pretrained={pretrained}) on {self.device}...")
|
||||
|
||||
try:
|
||||
self.model, _, self.preprocess = open_clip.create_model_and_transforms(
|
||||
model_name,
|
||||
pretrained=pretrained
|
||||
)
|
||||
self.model.to(self.device)
|
||||
self.model.eval()
|
||||
self.get_logger().info("CLIP model loaded successfully.")
|
||||
except Exception as e:
|
||||
self.get_logger().error(f"Failed to load CLIP model: {e}")
|
||||
raise e
|
||||
|
||||
# Initialize indoor vocabulary and pre-compute text embeddings
|
||||
self.vocabulary = DEFAULT_VOCABULARY
|
||||
self.get_logger().info(f"Pre-computing text features for {len(self.vocabulary)} categories...")
|
||||
try:
|
||||
# Format classes as prompts e.g. "a photo of a chair"
|
||||
prompts = [f"a photo of a {c}" for c in self.vocabulary]
|
||||
self.text_tokens = open_clip.tokenize(prompts).to(self.device)
|
||||
with torch.no_grad():
|
||||
self.text_features = self.model.encode_text(self.text_tokens)
|
||||
self.text_features /= self.text_features.norm(dim=-1, keepdim=True)
|
||||
self.get_logger().info("Text features pre-computed successfully.")
|
||||
except Exception as e:
|
||||
self.get_logger().error(f"Failed to pre-compute text features: {e}")
|
||||
raise e
|
||||
|
||||
# Expose service
|
||||
self.srv = self.create_service(
|
||||
ExtractClipFeatures,
|
||||
'/extract_clip_features',
|
||||
self.extract_features_callback
|
||||
)
|
||||
self.get_logger().info("Service '/extract_clip_features' is ready.")
|
||||
|
||||
def extract_features_callback(self, request, response):
|
||||
"""
|
||||
Callback for ExtractClipFeatures service.
|
||||
Processes a list of image crops and returns flat embeddings + zero-shot class predictions.
|
||||
"""
|
||||
self.get_logger().info(f"Received request to extract CLIP features for {len(request.crops)} crops.")
|
||||
|
||||
if not request.crops:
|
||||
response.embeddings = []
|
||||
response.classes = []
|
||||
response.success = True
|
||||
return response
|
||||
|
||||
try:
|
||||
pil_images = []
|
||||
for idx, img_msg in enumerate(request.crops):
|
||||
try:
|
||||
# Convert ROS Image to OpenCV BGR, then to RGB
|
||||
cv_img = self.bridge.imgmsg_to_cv2(img_msg, desired_encoding='bgr8')
|
||||
# Convert to PIL Image
|
||||
pil_img = PILImage.fromarray(cv_img[:, :, ::-1]) # BGR to RGB
|
||||
pil_images.append(pil_img)
|
||||
except CvBridgeError as e:
|
||||
self.get_logger().error(f"CvBridge error converting crop {idx}: {e}")
|
||||
response.success = False
|
||||
response.embeddings = []
|
||||
response.classes = []
|
||||
return response
|
||||
|
||||
# Preprocess all images and batch them
|
||||
preprocessed_tensors = [self.preprocess(img) for img in pil_images]
|
||||
batch_tensor = torch.stack(preprocessed_tensors).to(self.device)
|
||||
|
||||
# Run inference
|
||||
with torch.no_grad(), torch.amp.autocast(device_type=('cuda' if 'cuda' in self.device else 'cpu')):
|
||||
image_features = self.model.encode_image(batch_tensor)
|
||||
# Normalize features to unit length for cosine similarity
|
||||
image_features /= image_features.norm(dim=-1, keepdim=True)
|
||||
|
||||
# Compute zero-shot classification similarities
|
||||
similarities = image_features @ self.text_features.T
|
||||
best_indices = similarities.argmax(dim=-1).cpu().numpy().tolist()
|
||||
predicted_classes = [self.vocabulary[idx] for idx in best_indices]
|
||||
|
||||
# Flatten the batch of embeddings to a list of floats
|
||||
flat_features = image_features.cpu().numpy().flatten().tolist()
|
||||
|
||||
response.embeddings = flat_features
|
||||
response.classes = predicted_classes
|
||||
response.success = True
|
||||
self.get_logger().info(f"Features extracted and classified successfully. Predictions: {predicted_classes}")
|
||||
|
||||
except Exception as e:
|
||||
self.get_logger().error(f"Error during feature extraction/classification: {e}")
|
||||
response.success = False
|
||||
response.embeddings = []
|
||||
response.classes = []
|
||||
|
||||
return response
|
||||
|
||||
def main(args=None):
|
||||
rclpy.init(args=args)
|
||||
node = ClipExtractorNode()
|
||||
try:
|
||||
rclpy.spin(node)
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
finally:
|
||||
node.destroy_node()
|
||||
if rclpy.ok():
|
||||
rclpy.shutdown()
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -10,11 +10,8 @@ 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 scene_graph_interfaces.srv import ExtractClipFeatures
|
||||
from cv_bridge import CvBridge
|
||||
|
||||
import numpy as np
|
||||
import open3d as o3d
|
||||
import sensor_msgs_py.point_cloud2 as pc2
|
||||
import cv2
|
||||
import time
|
||||
@@ -56,6 +53,7 @@ class ObjectLocalizationNode(Node):
|
||||
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 ---
|
||||
@@ -74,6 +72,10 @@ class ObjectLocalizationNode(Node):
|
||||
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)
|
||||
@@ -83,18 +85,9 @@ class ObjectLocalizationNode(Node):
|
||||
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.pub_debug_detected_objects = self.create_publisher(Image, '/scene_graph/debug/detected_objects_overlay', 10)
|
||||
|
||||
# C. CLIP Feature Extractor Service Client
|
||||
self.clip_client = self.create_client(
|
||||
ExtractClipFeatures,
|
||||
'/extract_clip_features',
|
||||
callback_group=self.callback_group
|
||||
)
|
||||
|
||||
self.get_logger().info("Object Localization Node Initialized. Waiting for data...")
|
||||
|
||||
|
||||
def get_intrinsics_callback(self, msg):
|
||||
if self.intrinsics is None:
|
||||
self.intrinsics = {
|
||||
@@ -124,46 +117,66 @@ class ObjectLocalizationNode(Node):
|
||||
self.depth_buffer.pop(oldest)
|
||||
self.try_process()
|
||||
|
||||
def _find_matching_pair(self, max_dt=0.05):
|
||||
for t_rgb in list(self.rgb_buffer.keys()):
|
||||
if not self.depth_buffer:
|
||||
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_rgb - t_depth)
|
||||
dt = abs(t_yolo - t_depth)
|
||||
if dt < best_depth_dt:
|
||||
best_depth_dt = dt
|
||||
best_t_depth = t_depth
|
||||
|
||||
if best_t_depth is not None and best_depth_dt <= max_dt:
|
||||
return t_rgb, best_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_pair(max_dt=0.05)
|
||||
match = self._find_matching_triplet(max_dt=0.05)
|
||||
if match is None:
|
||||
return
|
||||
t_rgb, t_depth = match
|
||||
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:
|
||||
# Extract pipeline start wall time from rgb_msg frame_id if formatted as frame_id|timestamp
|
||||
objects = yolo_msg.objects
|
||||
pipeline_start_wall = ""
|
||||
frame_parts = rgb_msg.header.frame_id.split('|')
|
||||
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,
|
||||
self.pub_bbox_yolo, self.pub_cloud_yolo, self.pub_markers_yolo, self.pub_pc_markers_yolo, source_name="Geometry",
|
||||
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:
|
||||
@@ -172,13 +185,15 @@ class ObjectLocalizationNode(Node):
|
||||
# Check recursively for more matches
|
||||
self.try_process()
|
||||
|
||||
def process_segmentation_pipeline(self, rgb_msg, depth_msg,
|
||||
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()
|
||||
@@ -254,323 +269,252 @@ class ObjectLocalizationNode(Node):
|
||||
(128, 128, 0) # Olive
|
||||
]
|
||||
|
||||
# --- STEP 2: GEOMETRY PROPOSAL GENERATION ---
|
||||
fx, fy = self.intrinsics['fx'], self.intrinsics['fy']
|
||||
cx, cy = self.intrinsics['cx'], self.intrinsics['cy']
|
||||
|
||||
# Stride sample to downsample for real-time performance
|
||||
stride = 4
|
||||
h, w = cv_depth.shape[:2]
|
||||
|
||||
us, vs = np.meshgrid(np.arange(0, w, stride), np.arange(0, h, stride))
|
||||
us = us.flatten()
|
||||
vs = vs.flatten()
|
||||
|
||||
zs = cv_depth[vs, us].astype(np.float32) * self.depth_scale
|
||||
|
||||
# Filter points within valid depth range (0.1m up to parameter max_object_distance)
|
||||
max_dist = self.get_parameter('max_object_distance').get_parameter_value().double_value
|
||||
valid = (zs > 0.1) & (zs < max_dist)
|
||||
if np.sum(valid) < 100:
|
||||
self.get_logger().warn(f"[{source_name}] Not enough valid depth points for geometry proposals.")
|
||||
return
|
||||
|
||||
us = us[valid]
|
||||
vs = vs[valid]
|
||||
zs = zs[valid]
|
||||
|
||||
xs = (us - cx) * zs / fx
|
||||
ys = (vs - cy) * zs / fy
|
||||
points_cam = np.vstack((xs, ys, zs)).T
|
||||
|
||||
# Segment planes and cluster using Open3D
|
||||
pcd = o3d.geometry.PointCloud()
|
||||
pcd.points = o3d.utility.Vector3dVector(points_cam)
|
||||
|
||||
remaining_pcd = pcd
|
||||
for _ in range(3):
|
||||
if len(remaining_pcd.points) < 200:
|
||||
break
|
||||
plane_model, inliers = remaining_pcd.segment_plane(
|
||||
distance_threshold=0.04,
|
||||
ransac_n=3,
|
||||
num_iterations=100
|
||||
)
|
||||
if len(inliers) > len(remaining_pcd.points) * 0.08:
|
||||
remaining_pcd = remaining_pcd.select_by_index(inliers, invert=True)
|
||||
else:
|
||||
break
|
||||
|
||||
# --- STEP 2: PREPARE BBOXES FOR FASTSAM ---
|
||||
bboxes = []
|
||||
cluster_points_list = []
|
||||
valid_obj_indices = []
|
||||
|
||||
if len(remaining_pcd.points) >= 50:
|
||||
labels = np.array(remaining_pcd.cluster_dbscan(eps=0.18, min_points=15, print_progress=False))
|
||||
unique_labels = set(labels)
|
||||
if -1 in unique_labels:
|
||||
unique_labels.remove(-1)
|
||||
|
||||
for label in unique_labels:
|
||||
cluster_indices = np.where(labels == label)[0]
|
||||
cluster_pcd = remaining_pcd.select_by_index(cluster_indices)
|
||||
cluster_pts = np.asarray(cluster_pcd.points)
|
||||
|
||||
if len(cluster_pts) < 15:
|
||||
continue
|
||||
|
||||
xs_c = cluster_pts[:, 0]
|
||||
ys_c = cluster_pts[:, 1]
|
||||
zs_c = cluster_pts[:, 2]
|
||||
|
||||
us_proj = (xs_c * fx / zs_c) + cx
|
||||
vs_proj = (ys_c * fy / zs_c) + cy
|
||||
|
||||
u1 = int(np.floor(np.min(us_proj)))
|
||||
v1 = int(np.floor(np.min(vs_proj)))
|
||||
u2 = int(np.ceil(np.max(us_proj)))
|
||||
v2 = int(np.ceil(np.max(vs_proj)))
|
||||
|
||||
padding = 10
|
||||
u1 = max(0, u1 - padding)
|
||||
v1 = max(0, v1 - padding)
|
||||
u2 = min(w - 1, u2 + padding)
|
||||
v2 = min(h - 1, v2 + padding)
|
||||
|
||||
if u2 > u1 and v2 > v1:
|
||||
bboxes.append([u1, v1, u2, v2])
|
||||
cluster_points_list.append(cluster_pts)
|
||||
|
||||
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:
|
||||
self.get_logger().info(f"[{source_name}] No geometry proposals found in frame.")
|
||||
return
|
||||
|
||||
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: CROP & MASK FOR CLIP ---
|
||||
valid_crops = []
|
||||
valid_proposal_indices = []
|
||||
refined_masks = [None] * len(bboxes)
|
||||
|
||||
for idx, bbox in enumerate(bboxes):
|
||||
refined_mask = None
|
||||
if idx < len(masks) and masks[idx] is not None:
|
||||
mh, mw = masks[idx].shape
|
||||
x1, y1, x2, y2 = bbox
|
||||
ix1 = max(0, int(round(x1)))
|
||||
iy1 = max(0, int(round(y1)))
|
||||
ix2 = min(mw, int(round(x2)))
|
||||
iy2 = min(mh, int(round(y2)))
|
||||
|
||||
bbox_mask = np.zeros_like(masks[idx], dtype=bool)
|
||||
bbox_mask[iy1:iy2, ix1:ix2] = True
|
||||
refined_mask = masks[idx] & bbox_mask
|
||||
refined_masks[idx] = refined_mask
|
||||
|
||||
cx1 = max(0, int(round(bbox[0])))
|
||||
cy1 = max(0, int(round(bbox[1])))
|
||||
cx2 = min(cv_bgr.shape[1], int(round(bbox[2])))
|
||||
cy2 = min(cv_bgr.shape[0], int(round(bbox[3])))
|
||||
|
||||
if cx2 > cx1 and cy2 > cy1:
|
||||
crop_img = cv_bgr[cy1:cy2, cx1:cx2].copy()
|
||||
if refined_mask is not None:
|
||||
crop_mask = refined_mask[cy1:cy2, cx1:cx2]
|
||||
masked_crop = np.zeros_like(crop_img)
|
||||
masked_crop[crop_mask] = crop_img[crop_mask]
|
||||
else:
|
||||
masked_crop = crop_img
|
||||
|
||||
try:
|
||||
crop_msg = self.bridge.cv2_to_imgmsg(masked_crop, encoding='bgr8')
|
||||
valid_crops.append(crop_msg)
|
||||
valid_proposal_indices.append(idx)
|
||||
except Exception as e:
|
||||
self.get_logger().error(f"Error converting crop to message: {e}")
|
||||
|
||||
# Call CLIP service for visual embeddings and zero-shot labels
|
||||
predicted_classes = ["object"] * len(bboxes)
|
||||
embeddings_list = [[]] * len(bboxes)
|
||||
|
||||
if valid_crops:
|
||||
if self.clip_client.service_is_ready():
|
||||
self.get_logger().info(f"Extracting CLIP features & zero-shot labels for {len(valid_crops)} geometry proposals...")
|
||||
req = ExtractClipFeatures.Request()
|
||||
req.crops = valid_crops
|
||||
res = self.clip_client.call(req)
|
||||
if res.success:
|
||||
emb_dim = 1024
|
||||
if len(res.embeddings) == len(valid_crops) * emb_dim:
|
||||
for crop_idx, prop_idx in enumerate(valid_proposal_indices):
|
||||
start_idx = crop_idx * emb_dim
|
||||
end_idx = start_idx + emb_dim
|
||||
embeddings_list[prop_idx] = res.embeddings[start_idx:end_idx]
|
||||
predicted_classes[prop_idx] = res.classes[crop_idx]
|
||||
self.get_logger().info(f"CLIP zero-shot predictions: {res.classes}")
|
||||
else:
|
||||
self.get_logger().error(f"CLIP embeddings size mismatch: expected {len(valid_crops) * emb_dim}, got {len(res.embeddings)}")
|
||||
else:
|
||||
self.get_logger().error("CLIP feature extraction service call failed.")
|
||||
else:
|
||||
self.get_logger().warn("CLIP feature extraction service not ready. Skipping embeddings.")
|
||||
|
||||
# --- STEP 4.5: GEOMETRY PROCESSING & PACKING ---
|
||||
|
||||
# --- 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 idx, bbox in enumerate(bboxes):
|
||||
class_name_str = predicted_classes[idx]
|
||||
embedding = embeddings_list[idx]
|
||||
refined_mask = refined_masks[idx]
|
||||
all_cloud_points = []
|
||||
|
||||
for i, bbox in enumerate(bboxes):
|
||||
original_obj = objects[valid_obj_indices[i]]
|
||||
|
||||
# Check point counts
|
||||
points_clean = GeometryUtils.clean_outliers(cluster_points_list[idx], std_ratio=1.5)
|
||||
if len(points_clean) < 10:
|
||||
continue
|
||||
# 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)))
|
||||
|
||||
# Filter by distance
|
||||
centroid_cam = np.mean(points_clean, axis=0)
|
||||
distance = float(np.linalg.norm(centroid_cam))
|
||||
if distance > max_dist:
|
||||
continue
|
||||
|
||||
# Transform to Map Frame
|
||||
points_map = GeometryUtils.transform_points(points_clean, translation, rotation)
|
||||
bbox_data = GeometryUtils.compute_3d_obb(points_map)
|
||||
if bbox_data is None:
|
||||
continue
|
||||
|
||||
# Pack bounding box message
|
||||
bbox_msg = target_item_class()
|
||||
bbox_msg.name = String(data=class_name_str)
|
||||
if isinstance(bbox_msg, Object3DBoundingBox):
|
||||
bbox_msg.graspable = False
|
||||
bbox_msg.clip_embedding = embedding
|
||||
|
||||
bbox_msg.bounding_box = [
|
||||
Point32(x=float(pt[0]), y=float(pt[1]), z=float(pt[2]))
|
||||
for pt in bbox_data['corners']
|
||||
]
|
||||
bbox_mask = np.zeros_like(masks[i], dtype=bool)
|
||||
bbox_mask[iy1:iy2, ix1:ix2] = True
|
||||
refined_mask = masks[i] & bbox_mask
|
||||
|
||||
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)
|
||||
|
||||
# Debug overlay annotations
|
||||
color = colors[idx % len(colors)]
|
||||
# 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)
|
||||
|
||||
# Log information
|
||||
|
||||
# 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})"
|
||||
self.get_logger().info(f"[{source_name}] ID: {idx} | Class: '{class_name_str}' | Min: {min_s} | Max: {max_s}")
|
||||
|
||||
# Cloud accumulation
|
||||
class_id = float(idx)
|
||||
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)
|
||||
|
||||
# Visualization Markers
|
||||
|
||||
# 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 = "geometry_3d_cubes"
|
||||
marker_cube.id = idx
|
||||
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 = float(color[2] / 255.0)
|
||||
marker_cube.color.g = float(color[1] / 255.0)
|
||||
marker_cube.color.b = float(color[0] / 255.0)
|
||||
|
||||
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 = "geometry_3d_labels"
|
||||
marker_text.id = idx
|
||||
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_str
|
||||
|
||||
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 = "geometry_3d_pointclouds"
|
||||
marker_pc.id = idx
|
||||
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()
|
||||
marker_pc.color.r = float(color[2] / 255.0)
|
||||
marker_pc.color.g = float(color[1] / 255.0)
|
||||
marker_pc.color.b = float(color[0] / 255.0)
|
||||
|
||||
# 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)
|
||||
@@ -618,7 +562,6 @@ class ObjectLocalizationNode(Node):
|
||||
segmented_msg = self.bridge.cv2_to_imgmsg(segmented_bgr, encoding='bgr8')
|
||||
segmented_msg.header = rgb_msg.header
|
||||
self.pub_debug_segmented_rgb.publish(segmented_msg)
|
||||
self.pub_debug_detected_objects.publish(segmented_msg)
|
||||
|
||||
# Publish segments overlay debug image
|
||||
overlay_msg = self.bridge.cv2_to_imgmsg(segmented_bgr, encoding='bgr8')
|
||||
|
||||
@@ -36,9 +36,7 @@ setup(
|
||||
'console_scripts': [
|
||||
'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',
|
||||
'clip_extractor_node = scene_graph_generation_pipeline.object_localization.clip_extractor_node:main',
|
||||
'scene_graph_fusion_node = scene_graph_generation_pipeline.scene_graph_fusion.scene_graph_fusion_node:main',
|
||||
|
||||
'odom_vizualization_node = scene_graph_generation_pipeline.odom_vizualization.odom_vizualization_node:main',
|
||||
'room_classification_node = scene_graph_generation_pipeline.room_classification.room_classification_node:main',
|
||||
'room_segmentation_node = scene_graph_generation_pipeline.room_segmentation.room_segmentation_node:main'
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
import rclpy
|
||||
from unittest.mock import MagicMock, patch
|
||||
import numpy as np
|
||||
import torch
|
||||
from rclpy.parameter import Parameter
|
||||
from scene_graph_interfaces.srv import ExtractClipFeatures
|
||||
from sensor_msgs.msg import Image
|
||||
|
||||
# Mock open_clip before importing to avoid loading weights on test runs
|
||||
with patch('open_clip.create_model_and_transforms'):
|
||||
from scene_graph_generation_pipeline.object_localization.clip_extractor_node import ClipExtractorNode, DEFAULT_VOCABULARY
|
||||
|
||||
def test_clip_node_initialization():
|
||||
if not rclpy.ok():
|
||||
rclpy.init()
|
||||
|
||||
mock_model = MagicMock()
|
||||
# Mock text encoding output
|
||||
mock_model.encode_text.return_value = torch.randn(len(DEFAULT_VOCABULARY), 1024)
|
||||
mock_preprocess = MagicMock()
|
||||
|
||||
# Mock create_model_and_transforms
|
||||
with patch('open_clip.create_model_and_transforms', return_value=(mock_model, None, mock_preprocess)) as mock_create:
|
||||
node = ClipExtractorNode()
|
||||
|
||||
# Verify open_clip was called with the default parameters
|
||||
mock_create.assert_called_once_with('ViT-H-14', pretrained='laion2b_s32b_b79k')
|
||||
|
||||
# Check node state
|
||||
assert node.model == mock_model
|
||||
assert node.preprocess == mock_preprocess
|
||||
|
||||
node.destroy_node()
|
||||
rclpy.shutdown()
|
||||
|
||||
def test_clip_node_service_callback():
|
||||
if not rclpy.ok():
|
||||
rclpy.init()
|
||||
|
||||
mock_model = MagicMock()
|
||||
mock_model.encode_text.return_value = torch.randn(len(DEFAULT_VOCABULARY), 1024)
|
||||
mock_preprocess = MagicMock()
|
||||
mock_preprocess.return_value = torch.randn(3, 224, 224)
|
||||
|
||||
# Configure mock model encoding to return a mock tensor
|
||||
# Since embedding size is 1024-d, return a tensor of shape (2, 1024) for 2 crops
|
||||
dummy_features = torch.randn(2, 1024)
|
||||
mock_model.encode_image.return_value = dummy_features
|
||||
|
||||
with patch('open_clip.create_model_and_transforms', return_value=(mock_model, None, mock_preprocess)):
|
||||
node = ClipExtractorNode()
|
||||
|
||||
# Create a mock service request
|
||||
request = ExtractClipFeatures.Request()
|
||||
|
||||
# Create dummy crops (blank 32x32 images)
|
||||
dummy_cv_image = np.zeros((32, 32, 3), dtype=np.uint8)
|
||||
img_msg1 = node.bridge.cv2_to_imgmsg(dummy_cv_image, encoding='bgr8')
|
||||
img_msg2 = node.bridge.cv2_to_imgmsg(dummy_cv_image, encoding='bgr8')
|
||||
request.crops = [img_msg1, img_msg2]
|
||||
|
||||
response = ExtractClipFeatures.Response()
|
||||
|
||||
# Execute the callback
|
||||
response = node.extract_features_callback(request, response)
|
||||
|
||||
assert response.success is True
|
||||
# Total flat embedding length should be 2 * 1024 = 2048
|
||||
assert len(response.embeddings) == 2048
|
||||
# Should have 2 predicted class labels
|
||||
assert len(response.classes) == 2
|
||||
assert all(cls in DEFAULT_VOCABULARY for cls in response.classes)
|
||||
|
||||
node.destroy_node()
|
||||
rclpy.shutdown()
|
||||
Reference in New Issue
Block a user