26 Commits
Author SHA1 Message Date
janzon 7a3d18bf80 refactor: replace yolo-based object detection with open3d geometry-based clustering for proposal generation 2026-07-30 11:04:21 +00:00
janzon e00f87707c feat: implement ClipExtractorNode to provide CLIP image feature extraction via service and integrate into existing launch files. 2026-07-10 13:35:21 +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
janzon 37631e0c98 feat: implement robust three-stage point cloud outlier removal pipeline and depth-based median filtering 2026-06-19 13:47:23 +00:00
janzon 019d17923e feat: add point cloud processing and publishing to object localization node 2026-06-19 13:31:04 +00:00
janzon 4a6058d490 refactor: replace odometry-based localization with tf2 transformation and add visualization markers for 3D bounding boxes 2026-06-19 12:44:42 +00:00
janzon 229d26a0eb feat: integrate FastSAM support, implement 3D bounding box projection utilities, and add comprehensive unit tests. 2026-06-19 10:09:24 +00:00
janzon 6d03da054a refactor: remove RT-DETR model support and simplify YOLO-World object detection pipeline. 2026-06-18 13:46:19 +00:00
janzon ed44e3471a refactor: overhaul odom_vizualization_node for multi-topic visualization and add TF filtering capabilities, integrate with new scene_graph_rtabmap_launch, and update package dependencies. 2026-06-18 08:47:05 +00:00
46 changed files with 6058 additions and 1326 deletions
+2 -1
View File
@@ -5,4 +5,5 @@ pipeline.png
/build/
/install/
/log/
~/.cache
~/.cache
.vscode/
+57 -10
View File
@@ -1,52 +1,99 @@
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=[]
)
# 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_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([
object_detection_node,
use_sim_time_arg,
object_localization_node,
clip_extractor_node,
scene_graph_fusion_node,
odom_vizualization_node
odom_vizualization_node,
room_classification_node,
room_segmentation_node
])
+129
View File
@@ -0,0 +1,129 @@
import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import IncludeLaunchDescription
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch_ros.actions import Node
def generate_launch_description():
"""Launch file to start RTAB-Map SLAM alongside the complete Scene Graph pipeline."""
# -------------------------------------------------------------------------
# 1. RTAB-Map SLAM Launch Configuration
# -------------------------------------------------------------------------
rtabmap_launch_dir = os.path.join(get_package_share_directory('rtabmap_launch'), 'launch')
rtabmap_slam = IncludeLaunchDescription(
PythonLaunchDescriptionSource(os.path.join(rtabmap_launch_dir, 'rtabmap.launch.py')),
launch_arguments={
'use_sim_time': 'true',
'subscribe_scan': 'true',
'scan_topic': '/scan',
'odom_topic': '/odom',
'rgb_topic': '/camera/color/image_raw',
'depth_topic': '/camera/depth/image_raw',
'camera_info_topic': '/camera/color/camera_info',
'approx_sync': 'true',
'frame_id': 'base_footprint',
'visual_odometry': 'false',
'wait_for_transform': '1.0',
'rtabmap_viz': 'false',
'rviz': 'false',
'args': '-d --Grid/3D false --Grid/FromDepth false'
}.items()
)
# -------------------------------------------------------------------------
# 2. Scene Graph Pipeline Nodes (with use_sim_time enabled)
# -------------------------------------------------------------------------
common_params = [{'use_sim_time': True}]
# Object Detection Node
object_detection_node = Node(
package='scene_graph_generation_pipeline',
executable='object_detection_node',
name='object_detection_node',
output='screen',
parameters=common_params,
remappings=[]
)
# Object Localization Node
object_localization_node = Node(
package='scene_graph_generation_pipeline',
executable='object_localization_node',
name='object_localization_node',
output='screen',
parameters=common_params,
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',
executable='scene_graph_fusion_node',
name='scene_graph_fusion_node',
output='screen',
parameters=common_params,
remappings=[]
)
# Odom Visualization Node
odom_vizualization_node = Node(
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_localization_node,
clip_extractor_node,
scene_graph_fusion_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.
+6 -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,10 +15,15 @@
<!-- 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>
<exec_depend>python3-pip</exec_depend>
<exec_depend>rtabmap_msgs</exec_depend>
<exec_depend>geometry_msgs</exec_depend>
<exec_depend>tf2_ros</exec_depend>
<exec_depend>visualization_msgs</exec_depend>
<!-- Your custom interface package -->
+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
@@ -1,47 +1,48 @@
#!/usr/bin/env python
from ultralytics import YOLO, RTDETR
from ultralytics import YOLO
import rclpy
from rclpy.node import Node
from sensor_msgs.msg import Image, PointCloud2
from cv_bridge import CvBridge, CvBridgeError
import cv2
import numpy as np
from scene_graph_interfaces.msg import ObjectList, Object, FunObject, FunObjectList
from scene_graph_interfaces.msg import ObjectList, Object
from geometry_msgs.msg import Point32
from std_msgs.msg import String
from nav_msgs.msg import Odometry
import message_filters
from huggingface_hub import snapshot_download
import os
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, get_vocabulary_dict
from .vocabulary_configs import get_vocabulary
class ObjectDetectionNode(Node):
def __init__(self):
"""
Initializes the ImageSegmentationNode.
This constructor sets up the ROS2 node for performing image segmentation using both YOLO-World
and RT-DETR models. It subscribes to camera image, depth, and odometry topics, and publishes
synchronized topics along with detected object information from both models.
This constructor sets up the ROS2 node for performing image segmentation using the YOLO-World
model. It subscribes to camera image, depth, and odometry topics, and publishes
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)
# YOLO-World allows detecting any object by providing text prompts
# Available models: yolov8l-world.pt (large), yolov8m-world.pt (medium), yolov8s-world.pt (small)
self.model_yolo = YOLO('yolov8s-world.pt')
self.model_yolo = YOLO('yolov8l-world.pt')
# Load indoor robotics vocabulary with graspability affordances
# Structure: {label_name: is_graspable, ...}
# Load indoor robotics vocabulary
self.vocabulary_list = get_vocabulary() # List of labels for YOLO
self.vocabulary_dict = get_vocabulary_dict() # Dict with graspability affordances
# Set vocabulary for the YOLO-World model
self.model_yolo.set_classes(self.vocabulary_list)
@@ -49,49 +50,12 @@ class ObjectDetectionNode(Node):
self.get_logger().info(f"Using vocabulary with {len(self.vocabulary_list)} classes:")
self.get_logger().info(f"Classes: {', '.join(self.vocabulary_list)}")
# ==================== RT-DETR Model ====================
# Load the fine-tuned RT-DETR model for functional elements detection
# Model from: https://huggingface.co/DennisRotondi/rtdetr_functional_elements
try:
self.get_logger().info("Downloading RT-DETR functional elements model from Hugging Face...")
# Download the entire repo which contains the model
repo_dir = snapshot_download(
repo_id="DennisRotondi/rtdetr_functional_elements",
cache_dir=os.path.expanduser("~/.cache/huggingface/hub")
)
model_path = os.path.join(repo_dir, "rtdetr_functional_elements.pt")
if not os.path.exists(model_path):
raise FileNotFoundError(f"Model file not found at {model_path}")
self.get_logger().info(f"RT-DETR model found at: {model_path}")
self.model_rtdetr = RTDETR(model_path)
# Extract class names from the model
# RT-DETR model is trained to detect functional elements (actions like push, pull, etc.)
if hasattr(self.model_rtdetr.model, 'names'):
self.rtdetr_class_names = self.model_rtdetr.model.names
else:
# Fallback default names
self.rtdetr_class_names = {i: f"element_{i}" for i in range(10)}
self.get_logger().info(f"RT-DETR class names: {self.rtdetr_class_names}")
self.get_logger().info("RT-DETR model loaded successfully")
self.rtdetr_available = True
except Exception as e:
self.get_logger().warn(f"RT-DETR model not available: {e}. Only YOLO-World will be used.")
self.model_rtdetr = None
self.rtdetr_class_names = {}
self.rtdetr_available = False
# Move the models to GPU for faster inference if CUDA is available
if self._check_cuda_available():
self.model_yolo.to('cuda')
self.model_rtdetr.to('cuda') if self.rtdetr_available else None
# Set confidence threshold - only detections above this value are kept
self.confidence_threshold_yolo = 0.8
self.confidence_threshold_rtdetr = 0.5
# Initialize counter and callback flag (currently unused in the code)
self.n = 0
@@ -135,12 +99,7 @@ class ObjectDetectionNode(Node):
# Create publisher for detected objects from YOLO-World (queue_size=10)
self.yolo_detected_objects_pub = self.create_publisher(ObjectList, '/scene_graph/yolo', 10)
# ==================== RT-DETR Publishers ====================
# Create publisher for debugging - shows the segmented image with bounding boxes from RT-DETR
self.rtdetr_image_pub = self.create_publisher(Image, '/scene_graph/debug/rtdetr', 1)
# Create publisher for detected objects from RT-DETR (queue_size=10)
self.rtdetr_detected_objects_pub = self.create_publisher(FunObjectList, '/scene_graph/rtdetr', 10)
def synchronized_callback(self, ros_image, depth_msg, odom_msg):
@@ -148,14 +107,16 @@ class ObjectDetectionNode(Node):
Callback function for synchronized sensor data.
This function is triggered when synchronized RGB image, depth image, and odometry
messages are available. It performs object detection using both YOLO-World and RT-DETR,
and publishes their results independently.
messages are available. It performs object detection using the YOLO-World model,
and publishes the results.
Args:
ros_image (sensor_msgs/Image): RGB camera image
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')
@@ -170,15 +131,10 @@ class ObjectDetectionNode(Node):
# ==================== YOLO-World Detection ====================
# Run YOLO-World inference on the image
yolo_detected_objects = self._detect_with_yolo(cv_image)
# ==================== RT-DETR Detection ====================
# Run RT-DETR inference if available
rtdetr_detected_objects = []
if self.rtdetr_available:
rtdetr_detected_objects = self._detect_with_rtdetr(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
@@ -193,14 +149,8 @@ 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)
# Publish RT-DETR detections
if rtdetr_detected_objects:
rtdetr_objects_msg = FunObjectList()
rtdetr_objects_msg.fun_objects = rtdetr_detected_objects
rtdetr_objects_msg.header.stamp = current_time
self.rtdetr_detected_objects_pub.publish(rtdetr_objects_msg)
def _detect_with_yolo(self, cv_image):
"""
@@ -259,12 +209,9 @@ class ObjectDetectionNode(Node):
# Extract bounding box coordinates
x1, y1, x2, y2 = box.xyxy[0][0].item(), box.xyxy[0][1].item(), box.xyxy[0][2].item(), box.xyxy[0][3].item()
# Determine graspability from vocabulary dictionary (O(1) lookup)
is_graspable = self.vocabulary_dict.get(class_name, False)
# Create Object message with graspability affordance
# Create Object message
detected_objects.append(Object(
class_name=String(data=str(class_name)), graspable=is_graspable,
class_name=String(data=str(class_name)), graspable=False,
bounding_box=[Point32(x=x1, y=y1, z=0.0), Point32(x=x2, y=y2, z=0.0)]
))
@@ -272,7 +219,6 @@ class ObjectDetectionNode(Node):
object_details.append({
'class': class_name,
'confidence': confidence,
'graspable': is_graspable,
'bbox': (x1, y1, x2, y2)
})
@@ -282,7 +228,7 @@ class ObjectDetectionNode(Node):
self.get_logger().info(f"[YOLO] Detected {len(detected_objects)} object(s):")
for idx, obj in enumerate(object_details, 1):
self.get_logger().info(f" [{idx}] '{obj['class']}' | Confidence: {obj['confidence']:.2%} | "
f"Graspable: {obj['graspable']} | BBox: ({obj['bbox'][0]:.0f}, {obj['bbox'][1]:.0f}) "
f"BBox: ({obj['bbox'][0]:.0f}, {obj['bbox'][1]:.0f}) "
f"to ({obj['bbox'][2]:.0f}, {obj['bbox'][3]:.0f})")
# Draw bounding boxes on the image for visualization
@@ -297,8 +243,7 @@ class ObjectDetectionNode(Node):
# Add class name label
class_name = detected_obj.class_name.data
graspable_text = "graspable: TRUE" if detected_obj.graspable else "graspable: FALSE"
cv2.putText(annotated_image, f"{class_name} {graspable_text}", (x1, y1 - 10),
cv2.putText(annotated_image, f"{class_name}", (x1, y1 - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
# Publish the annotated image
@@ -316,115 +261,7 @@ class ObjectDetectionNode(Node):
self.get_logger().error(f"[YOLO] Total time before error: {total_time:.2f} ms")
return []
def _detect_with_rtdetr(self, cv_image):
"""
Perform object detection using RT-DETR model.
Args:
cv_image: OpenCV image
Returns:
List of Object messages detected by RT-DETR
"""
rtdetr_start_time = time.time()
try:
# Record inference start time
inference_start = time.time()
# Run RT-DETR inference on the image
results = self.model_rtdetr(cv_image, conf=self.confidence_threshold_rtdetr, verbose=False)
inference_time = (time.time() - inference_start) * 1000 # Convert to ms
self.get_logger().info(f"[RT-DETR] Inference time: {inference_time:.2f} ms")
# Initialize lists to store detected objects
detected_objects = []
annotated_image = results[0].orig_img.copy() if len(results) > 0 else cv_image.copy()
# Check if any detections were found
if len(results) == 0 or len(results[0].boxes) == 0:
self.get_logger().info("RT-DETR: No detections found in the image.")
# Still publish the debug image even when no detections are found
self.rtdetr_image_pub.publish(self.bridge.cv2_to_imgmsg(annotated_image, encoding='bgr8'))
total_time = (time.time() - rtdetr_start_time) * 1000
self.get_logger().info(f"[RT-DETR] Total processing time: {total_time:.2f} ms (0 objects detected)")
return []
# Iterate through all detection results
object_details = []
processing_start = time.time()
for result in results:
for i, box in enumerate(result.boxes):
# Extract class ID
class_id = int(box.cls.item())
# Get the actual class name from the model
if class_id in self.rtdetr_class_names:
class_name = self.rtdetr_class_names[class_id]
else:
class_name = f"element_{class_id}"
# Get confidence score for this detection
confidence = box.conf.item()
# Only process detections above the confidence threshold
if confidence > self.confidence_threshold_rtdetr:
# Extract bounding box coordinates
x1, y1, x2, y2 = box.xyxy[0][0].item(), box.xyxy[0][1].item(), box.xyxy[0][2].item(), box.xyxy[0][3].item()
# Create Object message
detected_objects.append(FunObject(
class_name=String(data=str(class_name)),
bounding_box=[Point32(x=x1, y=y1, z=0.0), Point32(x=x2, y=y2, z=0.0)]
))
# Track object details for logging
object_details.append({
'class': class_name,
'confidence': confidence,
'bbox': (x1, y1, x2, y2)
})
processing_time = (time.time() - processing_start) * 1000
# Log detected objects summary
self.get_logger().info(f"[RT-DETR] Detected {len(detected_objects)} object(s):")
for idx, obj in enumerate(object_details, 1):
self.get_logger().info(f" [{idx}] '{obj['class']}' | Confidence: {obj['confidence']:.2%} | "
f"BBox: ({obj['bbox'][0]:.0f}, {obj['bbox'][1]:.0f}) "
f"to ({obj['bbox'][2]:.0f}, {obj['bbox'][3]:.0f})")
# Draw bounding boxes on the image for visualization
for detected_obj in detected_objects:
x1 = int(detected_obj.bounding_box[0].x)
y1 = int(detected_obj.bounding_box[0].y)
x2 = int(detected_obj.bounding_box[1].x)
y2 = int(detected_obj.bounding_box[1].y)
# Draw bounding box rectangle (blue for RT-DETR)
cv2.rectangle(annotated_image, (x1, y1), (x2, y2), (255, 0, 0), 2)
# Add class name label
class_name = detected_obj.class_name.data
cv2.putText(annotated_image, f"{class_name}", (x1, y1 - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
# Publish the annotated image
self.rtdetr_image_pub.publish(self.bridge.cv2_to_imgmsg(annotated_image, encoding='bgr8'))
total_time = (time.time() - rtdetr_start_time) * 1000
self.get_logger().info(f"[RT-DETR] Inference: {inference_time:.2f} ms | Processing: {processing_time:.2f} ms | "
f"Total: {total_time:.2f} ms")
return detected_objects
except Exception as e:
self.get_logger().error(f"Error in RT-DETR detection: {e}")
total_time = (time.time() - rtdetr_start_time) * 1000
self.get_logger().error(f"[RT-DETR] Total time before error: {total_time:.2f} ms")
return []
def _check_cuda_available(self):
@@ -464,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()
@@ -0,0 +1,153 @@
#!/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()
@@ -0,0 +1,342 @@
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
class GeometryUtils:
"""Stateless geometric operations for 3D computer vision tasks."""
@staticmethod
def project_mask_to_3d(depth_img, mask, intrinsics, depth_scale):
"""
Projects 2D mask pixels into 3D camera space.
Returns: (N, 3) point cloud in camera frame.
"""
vs, us = np.where(mask)
if len(vs) == 0:
return np.empty((0, 3))
zs = depth_img[vs, us] * depth_scale
# Filter valid depth range (0.1m to 10.0m)
valid_mask = (zs > 0.1) & (zs < 10.0)
if np.sum(valid_mask) == 0:
return np.empty((0, 3))
# Depth median window filter: keep points within +/- 0.6m of the median depth
median_z = np.median(zs[valid_mask])
valid_mask = valid_mask & (np.abs(zs - median_z) < 0.6)
if np.sum(valid_mask) == 0:
return np.empty((0, 3))
us = us[valid_mask]
vs = vs[valid_mask]
zs = zs[valid_mask]
xs = (us - intrinsics['cx']) * zs / intrinsics['fx']
ys = (vs - intrinsics['cy']) * zs / intrinsics['fy']
return np.vstack((xs, ys, zs)).T
@staticmethod
def project_bbox_to_3d(depth_img, bbox, intrinsics, depth_scale, shrink_ratio=0.15):
"""
Projects a 2D bounding box's depth region into 3D camera space,
applying a shrink ratio to avoid edge background pixels.
"""
x1, y1, x2, y2 = bbox
h, w = depth_img.shape[:2]
# Clamp inputs to image boundaries
x1 = max(0, min(int(x1), w - 1))
x2 = max(0, min(int(x2), w - 1))
y1 = max(0, min(int(y1), h - 1))
y2 = max(0, min(int(y2), h - 1))
box_w = x2 - x1
box_h = y2 - y1
if box_w <= 0 or box_h <= 0:
return np.empty((0, 3))
dx = int(box_w * shrink_ratio)
dy = int(box_h * shrink_ratio)
# Ensure we don't shrink the box to empty
sx1 = x1 + dx
sx2 = x2 - dx
sy1 = y1 + dy
sy2 = y2 - dy
if sx2 <= sx1 or sy2 <= sy1:
sx1, sx2, sy1, sy2 = x1, x2, y1, y2
# Create grid coordinates for the region
us, vs = np.meshgrid(np.arange(sx1, sx2 + 1), np.arange(sy1, sy2 + 1))
us = us.flatten()
vs = vs.flatten()
zs = depth_img[vs, us] * depth_scale
valid_mask = (zs > 0.1) & (zs < 10.0)
if np.sum(valid_mask) == 0:
return np.empty((0, 3))
# Depth median window filter: keep points within +/- 0.6m of the median depth
median_z = np.median(zs[valid_mask])
valid_mask = valid_mask & (np.abs(zs - median_z) < 0.6)
if np.sum(valid_mask) == 0:
return np.empty((0, 3))
us = us[valid_mask]
vs = vs[valid_mask]
zs = zs[valid_mask]
xs = (us - intrinsics['cx']) * zs / intrinsics['fx']
ys = (vs - intrinsics['cy']) * zs / intrinsics['fy']
return np.vstack((xs, ys, zs)).T
@staticmethod
def clean_outliers(points, std_ratio=1.5):
"""
Removes outliers using a three-stage pipeline:
0. Downsample using stride-based sampling if points count > 1000.
1. Statistical Outlier Removal (SOR) via KDTree distance verification.
2. Density Clustering (DBSCAN-like) to keep only the largest connected component.
3. PCA-aligned axis filtering to remove tails along the principal directions.
"""
if len(points) < 5:
return points
# --- STAGE 0: Downsample dense point clouds for real-time performance ---
max_pts = 1000
if len(points) > max_pts:
stride = len(points) // max_pts
points = points[::stride][:max_pts]
# --- STAGE 1: Statistical Outlier Removal (SOR) ---
try:
tree = KDTree(points)
k = min(15, len(points) - 1)
dists, _ = tree.query(points, k=k+1)
mean_dists = np.mean(dists[:, 1:], axis=1)
global_mean = np.mean(mean_dists)
global_std = np.std(mean_dists)
if global_std > 0:
sor_mask = mean_dists < (global_mean + std_ratio * global_std)
points = points[sor_mask]
except Exception:
pass
if len(points) < 5:
return points
# --- STAGE 2: Largest Connected Cluster (DBSCAN-like) ---
try:
tree = KDTree(points)
adj_list = tree.query_pairs(r=0.15)
if len(adj_list) > 0:
rows, cols = zip(*adj_list)
r = np.concatenate([rows, cols])
c = np.concatenate([cols, rows])
data = np.ones_like(r)
n = len(points)
adj_matrix = csr_matrix((data, (r, c)), shape=(n, n))
n_components, labels = connected_components(csgraph=adj_matrix, directed=False, return_labels=True)
unique, counts = np.unique(labels, return_counts=True)
largest_label = unique[np.argmax(counts)]
points = points[labels == largest_label]
except Exception:
pass
if len(points) < 5:
return points
# --- STAGE 3: PCA-aligned Axis standard deviation filtering ---
try:
mean = np.mean(points, axis=0)
centered = points - mean
cov = np.cov(centered, rowvar=False)
eigenvalues, eigenvectors = np.linalg.eigh(cov)
idx = np.argsort(eigenvalues)[::-1]
eigenvectors = eigenvectors[:, idx]
projected = centered @ eigenvectors
# Use a robust multiplier to prevent multivariate over-filtering
pca_multiplier = max(2.2, std_ratio * 1.5)
inlier_mask = np.ones(len(points), dtype=bool)
for dim in range(3):
dim_mean = np.mean(projected[:, dim])
dim_std = np.std(projected[:, dim])
if dim_std > 0:
dim_mask = np.abs(projected[:, dim] - dim_mean) < (pca_multiplier * dim_std)
inlier_mask = inlier_mask & dim_mask
points = points[inlier_mask]
except Exception:
pass
return points
@staticmethod
def compute_3d_bbox(points):
"""Computes the axis-aligned bounding box (AABB)."""
if len(points) == 0:
return None
min_pt = np.min(points, axis=0)
max_pt = np.max(points, axis=0)
return {
'center': (min_pt + max_pt) / 2.0,
'size': max_pt - min_pt,
'min': min_pt,
'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."""
if points_cam.shape[0] == 0:
return points_cam
# 1. Parse Quaternion
q = odom_pose.orientation
qx, qy, qz, qw = q.x, q.y, q.z, q.w
norm = math.sqrt(qx**2 + qy**2 + qz**2 + qw**2)
if norm > 0:
qx, qy, qz, qw = qx/norm, qy/norm, qz/norm, qw/norm
R_odom = np.array([
[1 - 2*(qy**2 + qz**2), 2*(qx*qy - qw*qz), 2*(qx*qz + qw*qy)],
[2*(qx*qy + qw*qz), 1 - 2*(qx**2 + qz**2), 2*(qy*qz - qw*qx)],
[2*(qx*qz - qw*qy), 2*(qy*qz + qw*qx), 1 - 2*(qx**2 + qy**2)]
])
# 2. Camera Correction (-90 Roll, -90 Yaw)
roll, yaw = np.radians(-90.0), np.radians(-90.0)
Rx = np.array([
[1, 0, 0],
[0, np.cos(roll), -np.sin(roll)],
[0, np.sin(roll), np.cos(roll)]
])
Rz = np.array([
[np.cos(yaw), -np.sin(yaw), 0],
[np.sin(yaw), np.cos(yaw), 0],
[0, 0, 1]
])
# 3. Apply Combined Rotation and Translation
R_combined = R_odom @ (Rz @ Rx)
points_rotated = (R_combined @ points_cam.T).T
pos = odom_pose.position
robot_position = np.array([pos.x, pos.y, pos.z])
return points_rotated + robot_position
@staticmethod
def transform_points(points, translation, rotation):
"""
Transforms points using a given translation and rotation.
Args:
points (np.ndarray): (N, 3) array of 3D points.
translation (object/list/tuple): Translation with x, y, z fields or subscriptable.
rotation (object/list/tuple): Quaternion with x, y, z, w fields or subscriptable.
"""
if points.shape[0] == 0:
return points
# Parse translation
if hasattr(translation, 'x'):
tx, ty, tz = translation.x, translation.y, translation.z
else:
tx, ty, tz = translation[0], translation[1], translation[2]
# Parse rotation
if hasattr(rotation, 'x'):
qx, qy, qz, qw = rotation.x, rotation.y, rotation.z, rotation.w
else:
qx, qy, qz, qw = rotation[0], rotation[1], rotation[2], rotation[3]
# Normalize quaternion
norm = math.sqrt(qx**2 + qy**2 + qz**2 + qw**2)
if norm > 0:
qx, qy, qz, qw = qx/norm, qy/norm, qz/norm, qw/norm
R = np.array([
[1 - 2*(qy**2 + qz**2), 2*(qx*qy - qw*qz), 2*(qx*qz + qw*qy)],
[2*(qx*qy + qw*qz), 1 - 2*(qx**2 + qz**2), 2*(qy*qz - qw*qx)],
[2*(qx*qz - qw*qy), 2*(qy*qz + qw*qx), 1 - 2*(qx**2 + qy**2)]
])
points_rotated = (R @ points.T).T
translation_vec = np.array([tx, ty, tz])
return points_rotated + translation_vec
@@ -0,0 +1,676 @@
#!/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 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
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.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)
# --- 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.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 = {
'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 _find_matching_pair(self, max_dt=0.05):
for t_rgb in list(self.rgb_buffer.keys()):
if not self.depth_buffer:
continue
# 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)
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
return None
def try_process(self):
with self.lock:
if self.is_processing:
return
match = self._find_matching_pair(max_dt=0.05)
if match is None:
return
t_rgb, t_depth = match
rgb_msg = self.rgb_buffer.pop(t_rgb)
depth_msg = self.depth_buffer.pop(t_depth)
self.is_processing = True
try:
# Extract pipeline start wall time from rgb_msg frame_id if formatted as frame_id|timestamp
pipeline_start_wall = ""
frame_parts = rgb_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",
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,
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
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: 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
bboxes = []
cluster_points_list = []
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)
if not bboxes:
self.get_logger().info(f"[{source_name}] No geometry proposals found in frame.")
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 ---
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]
# Check point counts
points_clean = GeometryUtils.clean_outliers(cluster_points_list[idx], std_ratio=1.5)
if len(points_clean) < 10:
continue
# 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']
]
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)]
bx1, by1, bx2, by2 = int(bbox[0]), int(bbox[1]), int(bbox[2]), int(bbox[3])
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)
cv2.putText(segmented_bgr, class_name_str, (bx1, max(by1 - 10, 15)),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
# Log information
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)
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
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']
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.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.a = 0.4
marker_array_msg.markers.append(marker_cube)
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.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_array_msg.markers.append(marker_text)
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.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)
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)
self.pub_debug_detected_objects.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
@@ -0,0 +1,538 @@
#!/usr/bin/env python3
# ==============================================================================
# ROS2 Node: Odom Visualization and TF Filtering Node
# ==============================================================================
# This node serves three primary purposes in the scene graph room classification system:
# 1. Visualization: It subscribes to RTAB-Map's localization pose, info, and map graph,
# generating RViz visualization markers (Marker and MarkerArray) for:
# - The robot's current position and orientation (Arrow marker)
# - The robot's current position (Sphere marker)
# - The optimized trajectory history (Line Strip marker)
# 2. TF Filtering: It prevents transform conflicts by subscribing to '/tf_old',
# filtering out any coordinate frame transforms that reference the 'map' frame,
# and republishing the remaining valid transforms to '/tf'.
# 3. TF Static Forwarding: It intercepts static transforms on '/tf_static_old',
# caches unique transforms, and republishes them to '/tf_static' using the
# 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
from rtabmap_msgs.msg import Info, MapGraph
from tf2_msgs.msg import TFMessage
from visualization_msgs.msg import Marker, MarkerArray
class OdomVisualizationNode(Node):
"""
OdomVisualizationNode is a ROS2 node designed to handle coordinate transform (TF)
filtering, static TF latching, and SLAM trajectory/pose visualization for RViz.
"""
def __init__(self):
# Initialize the parent Node class with the node name '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
# ----------------------------------------------------------------------
# Stores the latest PoseWithCovarianceStamped received from the localization system.
self.latest_pose = None
# Caches unique geometry_msgs/TransformStamped objects received from /tf_static_old.
# This allows us to accumulate and re-publish all static transforms to any new subscribers.
self.cached_static_transforms = []
# ----------------------------------------------------------------------
# Stores a list of geometry_msgs/Point objects representing the nodes in the map graph.
# 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 status info.
# Topic: '/rtabmap/info' (rtabmap_msgs/Info)
# Purpose: Monitors SLAM statistics, loop closure detection events, and node indices.
self.info_sub = self.create_subscription(
Info,
'/rtabmap/info',
self.info_callback,
10
)
# Subscribe to RTAB-Map's map graph.
# Topic: '/rtabmap/mapGraph' (rtabmap_msgs/MapGraph)
# Purpose: Obtains the optimized pose graph containing all keyframe positions,
# allowing us to render the corrected robot trajectory path.
self.graph_sub = self.create_subscription(
MapGraph,
'/rtabmap/mapGraph',
self.map_graph_callback,
10
)
# ----------------------------------------------------------------------
# TF Filtering Configuration (Active TF)
# ----------------------------------------------------------------------
# Publisher: Publishes filtered transforms to the active '/tf' topic.
self.tf_pub = self.create_publisher(TFMessage, '/tf', 10)
# Subscriber: Listens to '/tf_old' where raw/unfiltered transforms are routed.
# Purpose: Intercepts raw transforms so we can filter out 'map' frame relationships
# and prevent frame ownership conflicts.
self.tf_sub = self.create_subscription(
TFMessage,
'/tf_old',
self.tf_callback,
10
)
# ----------------------------------------------------------------------
# TF Static Latching Configuration
# ----------------------------------------------------------------------
# In ROS2, static transforms (like sensor offsets) are typically published once.
# To ensure nodes that start up late can still get these transforms, we use
# a QoS Profile with 'TRANSIENT_LOCAL' durability (equivalent to latching in ROS1).
static_qos = QoSProfile(
depth=10,
durability=DurabilityPolicy.TRANSIENT_LOCAL
)
# Publisher: Publishes combined static transforms on '/tf_static' with latching.
self.tf_static_pub = self.create_publisher(TFMessage, '/tf_static', static_qos)
# Subscriber: Listens to raw static transforms on '/tf_static_old'.
self.tf_static_sub = self.create_subscription(
TFMessage,
'/tf_static_old',
self.tf_static_callback,
static_qos
)
# ----------------------------------------------------------------------
# Visualization Publishers
# ----------------------------------------------------------------------
# Publisher: Publishes MarkerArray messages to visualize the robot's pose/trajectory.
# Topic: '/scene_graph/viz/robot_pose' (visualization_msgs/MarkerArray)
self.pose_marker_pub = self.create_publisher(MarkerArray, "/scene_graph/viz/robot_pose", 10)
# Log node initialization status
self.get_logger().info('Odom/SLAM Pose, Loop Closure, and TF Static Filter Node initialized')
# pose_callback removed in favor of viz_timer_callback for high frequency visualization
def info_callback(self, msg):
"""
Callback triggered when new SLAM info/statistics are published by RTAB-Map.
Monitors the statistics to check for loop closure events. When a loop closure is
detected, it logs a formatted message detailing the node IDs involved.
Args:
msg (rtabmap_msgs.msg.Info): RTAB-Map status info containing statistics.
"""
# If loop_closure_id is greater than 0, it means RTAB-Map has successfully
# matched the current frame with a previously visited location (loop closure).
if msg.loop_closure_id > 0:
self.get_logger().info(
f"\n=========================================\n"
f"[LOOP CLOSURE] Detected loop closure!\n"
f"Current Node ID: {msg.ref_id} ===> Historical Node ID: {msg.loop_closure_id}\n"
f"=========================================\n"
)
def map_graph_callback(self, msg):
"""
Callback triggered when the optimized MapGraph is published by RTAB-Map.
Extracts the list of positions from the optimized poses in the graph, updates
the local trajectory points representation, and republishes the path history
as a line strip marker.
Args:
msg (rtabmap_msgs.msg.MapGraph): The map graph message containing poses.
"""
# Extract the position components from all keyframe poses in the graph message.
# This reflects the optimized trajectory updated after loop closures.
self.trajectory_points = [pose.position for pose in msg.poses]
# Create the MarkerArray to visualize the updated path
marker_array = MarkerArray()
# Create a line strip marker connecting all trajectory coordinates
trajectory_marker = self.create_trajectory(msg.header.frame_id)
marker_array.markers.append(trajectory_marker)
# Publish the updated trajectory to RViz
self.pose_marker_pub.publish(marker_array)
def tf_callback(self, msg):
"""
Callback triggered when a transform message is received on '/tf_old'.
Filters out any transforms that have 'map' as the parent (frame_id) or the child
(child_frame_id) frame to avoid conflicting coordinate frame definitions on the
active '/tf' topic. Only forwards non-map transforms.
Args:
msg (tf2_msgs.msg.TFMessage): List of coordinate frame transforms.
"""
filtered_transforms = []
for transform in msg.transforms:
# We filter out 'map' transforms because RTAB-Map or another SLAM system publishes
# the primary map -> odom transform. Subscribing to tf_old and republishing allows
# us to pass through base_link, sensor frames, etc., without messing up the map frame tree.
if transform.header.frame_id != 'map' and transform.child_frame_id != 'map':
filtered_transforms.append(transform)
# If we have any remaining valid transforms, package them and publish to /tf
if filtered_transforms:
out_msg = TFMessage()
out_msg.transforms = filtered_transforms
self.tf_pub.publish(out_msg)
def tf_static_callback(self, msg):
"""
Callback triggered when a static transform message is received on '/tf_static_old'.
Caches new static transforms and updates existing ones if their frame relationships
change. It then republishes the entire accumulated set of static transforms to
'/tf_static' to ensure late-joining nodes have complete access to the coordinate system.
Args:
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:
if (cached.header.frame_id == transform.header.frame_id and
cached.child_frame_id == transform.child_frame_id):
exists = True
# Update transform values (translation, rotation, and timestamp) in case of changes
cached.transform = transform.transform
cached.header.stamp = current_time
break
# If this is a new static transform, add it to our cache
if not exists:
self.cached_static_transforms.append(transform)
updated = True
# Republish the updated cache of static transforms. In ROS2, because the topic uses
# Transient Local durability, publishing the entire list ensures new subscribers receive
# all of them.
if updated or msg.transforms:
out_msg = TFMessage()
out_msg.transforms = self.cached_static_transforms
self.tf_static_pub.publish(out_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.
"""
marker = Marker()
marker.header = header
marker.header.frame_id = "map"
marker.ns = "robot_pose"
marker.id = 0
marker.type = Marker.ARROW
marker.action = Marker.ADD
marker.pose.position.x = translation.x
marker.pose.position.y = translation.y
marker.pose.position.z = translation.z
marker.pose.orientation = rotation
marker.scale.x = 0.5 # Shaft/total length
marker.scale.y = 0.05 # Shaft width
marker.scale.z = 0.05 # Shaft height
marker.color.r = 1.0
marker.color.g = 0.0
marker.color.b = 0.0
marker.color.a = 1.0
marker.lifetime = rclpy.duration.Duration(seconds=0).to_msg()
return marker
def create_position_sphere(self, header, translation):
"""
Constructs a semi-transparent green Sphere Marker representing the robot's current position.
"""
marker = Marker()
marker.header = header
marker.header.frame_id = "map"
marker.ns = "robot_position"
marker.id = 1
marker.type = Marker.SPHERE
marker.action = Marker.ADD
marker.pose.position.x = translation.x
marker.pose.position.y = translation.y
marker.pose.position.z = translation.z
marker.pose.orientation.w = 1.0
marker.scale.x = 0.2
marker.scale.y = 0.2
marker.scale.z = 0.2
marker.color.r = 0.0
marker.color.g = 1.0
marker.color.b = 0.0
marker.color.a = 0.8
marker.lifetime = rclpy.duration.Duration(seconds=0).to_msg()
return marker
def create_trajectory(self, frame_id):
"""
Constructs a Line Strip Marker connecting the historical points of the robot's path.
Args:
frame_id (str): The coordinate frame ID (typically "map") in which points are defined.
Returns:
visualization_msgs.msg.Marker: Fully populated line strip marker.
"""
marker = Marker()
marker.header.frame_id = frame_id
# Use the current node clock timestamp for the marker
marker.header.stamp = self.get_clock().now().to_msg()
# Set namespace and unique ID for the trajectory strip
marker.ns = "trajectory"
marker.id = 2
# Marker shape type: LINE_STRIP (connects a sequence of vertices with straight line segments)
marker.type = Marker.LINE_STRIP
marker.action = Marker.ADD
# Line thickness: scale.x defines the width of the line segment in meters
marker.scale.x = 0.02
# Set color to semi-transparent blue (RGBA: 0.0, 0.0, 1.0, 0.8)
marker.color.r = 0.0
marker.color.g = 0.0
marker.color.b = 1.0
marker.color.a = 0.8 # Semi-transparent
# Populate the vertices list using cached trajectory points
for point in self.trajectory_points:
marker.points.append(point)
# Indefinite persistence
marker.lifetime = rclpy.duration.Duration(seconds=0).to_msg()
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,
creates the OdomVisualizationNode instance, spins to handle callbacks,
and handles graceful shutdown on interruption.
"""
# Initialize the ROS2 client library
rclpy.init(args=args)
# Create the visualization and transform filter node
node = OdomVisualizationNode()
try:
# Spin the node to process subscriptions, service calls, and timers
rclpy.spin(node)
except KeyboardInterrupt:
# Catch interruption signal (e.g. Ctrl+C) to exit spin loop gracefully
pass
finally:
# Clean up node resources explicitly
node.destroy_node()
# 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,103 +0,0 @@
import numpy as np
import math
class GeometryUtils:
"""Stateless geometric operations for 3D computer vision tasks."""
@staticmethod
def project_mask_to_3d(depth_img, mask, intrinsics, depth_scale):
"""
Projects 2D mask pixels into 3D camera space.
Returns: (N, 3) point cloud in camera frame.
"""
vs, us = np.where(mask)
if len(vs) == 0:
return np.empty((0, 3))
zs = depth_img[vs, us] * depth_scale
# Filter valid depth range (0.1m to 10.0m)
valid_mask = (zs > 0.1) & (zs < 10.0)
if np.sum(valid_mask) == 0:
return np.empty((0, 3))
us = us[valid_mask]
vs = vs[valid_mask]
zs = zs[valid_mask]
xs = (us - intrinsics['cx']) * zs / intrinsics['fx']
ys = (vs - intrinsics['cy']) * zs / intrinsics['fy']
return np.vstack((xs, ys, zs)).T
@staticmethod
def clean_outliers(points, std_ratio=2.0):
"""Removes statistical outliers using distance-based thresholding."""
if len(points) < 10:
return points
center = np.mean(points, axis=0)
distances = np.linalg.norm(points - center, axis=1)
threshold = np.mean(distances) + (std_ratio * np.std(distances))
return points[distances < threshold]
@staticmethod
def compute_3d_bbox(points):
"""Computes the axis-aligned bounding box (AABB)."""
if len(points) == 0:
return None
min_pt = np.min(points, axis=0)
max_pt = np.max(points, axis=0)
return {
'center': (min_pt + max_pt) / 2.0,
'size': max_pt - min_pt,
'min': min_pt,
'max': max_pt
}
@staticmethod
def transform_points_camera_to_map(points_cam, odom_pose):
"""Transforms points from camera optical frame to map frame via odometry."""
if points_cam.shape[0] == 0:
return points_cam
# 1. Parse Quaternion
q = odom_pose.orientation
qx, qy, qz, qw = q.x, q.y, q.z, q.w
norm = math.sqrt(qx**2 + qy**2 + qz**2 + qw**2)
if norm > 0:
qx, qy, qz, qw = qx/norm, qy/norm, qz/norm, qw/norm
R_odom = np.array([
[1 - 2*(qy**2 + qz**2), 2*(qx*qy - qw*qz), 2*(qx*qz + qw*qy)],
[2*(qx*qy + qw*qz), 1 - 2*(qx**2 + qz**2), 2*(qy*qz - qw*qx)],
[2*(qx*qz - qw*qy), 2*(qy*qz + qw*qx), 1 - 2*(qx**2 + qy**2)]
])
# 2. Camera Correction (-90 Roll, -90 Yaw)
roll, yaw = np.radians(-90.0), np.radians(-90.0)
Rx = np.array([
[1, 0, 0],
[0, np.cos(roll), -np.sin(roll)],
[0, np.sin(roll), np.cos(roll)]
])
Rz = np.array([
[np.cos(yaw), -np.sin(yaw), 0],
[np.sin(yaw), np.cos(yaw), 0],
[0, 0, 1]
])
# 3. Apply Combined Rotation and Translation
R_combined = R_odom @ (Rz @ Rx)
points_rotated = (R_combined @ points_cam.T).T
pos = odom_pose.position
robot_position = np.array([pos.x, pos.y, pos.z])
return points_rotated + robot_position
@@ -1,226 +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
from scene_graph_interfaces.msg import ObjectList, FunObjectList, Object3DBoundingBox, Object3DBoundingBoxList, FunObject3DBoundingBox, FunObject3DBoundingBoxList
from cv_bridge import CvBridge
import numpy as np
import sensor_msgs_py.point_cloud2 as pc2
import cv2
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 = 'sam2_b.pt'
self.depth_scale = 0.001
# --- 2. INITIALIZE MODULES ---
self.bridge = CvBridge()
self.get_logger().info(f"Initializing SAM Wrapper with {model_name}...")
self.sam = SamWrapper(model_name=model_name)
# --- 3. STATE ---
self.intrinsics = None
# --- 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')
self.sub_odom = message_filters.Subscriber(self, Odometry, '/scene_graph/sync/odom')
# C. Object Detection Inputs
self.sub_yolo = message_filters.Subscriber(self, ObjectList, '/scene_graph/yolo')
self.sub_rtdetr = message_filters.Subscriber(self, FunObjectList, '/scene_graph/rtdetr')
# --- 5. SYNCHRONIZERS ---
# Chain 1: RGB + Depth + Odom + YOLO
self.ts_yolo = message_filters.ApproximateTimeSynchronizer(
[self.sub_rgb, self.sub_depth, self.sub_odom, self.sub_yolo],
queue_size=10, slop=0.1)
self.ts_yolo.registerCallback(self.yolo_callback)
# Chain 2: RGB + Depth + Odom + RT-DETR
self.ts_rtdetr = message_filters.ApproximateTimeSynchronizer(
[self.sub_rgb, self.sub_depth, self.sub_odom, self.sub_rtdetr],
queue_size=10, slop=0.1)
self.ts_rtdetr.registerCallback(self.rtdetr_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_bbox_rtdetr = self.create_publisher(FunObject3DBoundingBoxList, '/bounding_boxes_3d/rtdetr', 10)
self.pub_cloud_rtdetr = self.create_publisher(PointCloud2, '/object_clouds/rtdetr', 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, odom_msg, yolo_objs_msg):
objects = yolo_objs_msg.objects
self.process_segmentation_pipeline(
rgb_msg, depth_msg, odom_msg, objects,
self.pub_bbox_yolo, self.pub_cloud_yolo, source_name="YOLO",
target_list_class=Object3DBoundingBoxList, target_item_class=Object3DBoundingBox)
def rtdetr_callback(self, rgb_msg, depth_msg, odom_msg, rtdetr_objs_msg):
objects = rtdetr_objs_msg.fun_objects
self.process_segmentation_pipeline(
rgb_msg, depth_msg, odom_msg, objects,
self.pub_bbox_rtdetr, self.pub_cloud_rtdetr, source_name="RT-DETR",
target_list_class=FunObject3DBoundingBoxList, target_item_class=FunObject3DBoundingBox)
def process_segmentation_pipeline(self, rgb_msg, depth_msg, odom_msg, objects,
pub_bbox, pub_cloud, 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:
# --- 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 SAM ---
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 SAM PREDICTION ---
masks = self.sam.predict(cv_rgb, bboxes)
# --- STEP 4: GEOMETRY PROCESSING ---
bbox_list_msg = target_list_class()
bbox_list_msg.header = rgb_msg.header
bbox_list_msg.header.frame_id = "map"
all_cloud_points = []
for i, mask in enumerate(masks):
# A. Project & Filter
points_cam = GeometryUtils.project_mask_to_3d(
cv_depth, mask, self.intrinsics, self.depth_scale)
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_camera_to_map(
points_clean, odom_msg.pose.pose)
# C. Compute 3D BBox
bbox_data = GeometryUtils.compute_3d_bbox(points_map)
if bbox_data is None:
continue
# D. Pack Bounding Box
original_obj = objects[valid_obj_indices[i]]
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]
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 ""
self.get_logger().info( f"[{source_name}] ID: {i} | Class: '{class_name}'{grasp_info} | 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)
# --- STEP 5: PUBLISH ---
pub_bbox.publish(bbox_list_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)
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,47 +0,0 @@
import torch
from ultralytics import SAM
class SamWrapper:
"""Wrapper for Ultralytics SAM2 (Segment Anything Model 2) to handle prompted segmentation via bounding boxes."""
def __init__(self, model_name):
"""
Initializes SAM2 model.
Args:
model_name (str): 'sam2_b.pt' (base), 'sam2_t.pt' (tiny), or 'sam2_l.pt' (large).
"""
self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
print(f"[SamWrapper] Loading {model_name} on {self.device}...")
try:
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]
@@ -1,206 +0,0 @@
#!/usr/bin/env python
import rclpy
from rclpy.node import Node
from nav_msgs.msg import Odometry
from visualization_msgs.msg import Marker, MarkerArray
class OdomVisualizationNode(Node):
def __init__(self):
# Initialize the parent Node class
super().__init__('odom_vizualization_node')
# Initialize storage for robot pose
self.latest_odom = None
# Subscribe to robot odometry for pose information
self.odom_sub = self.create_subscription(Odometry, '/scene_graph/sync/odom', self.odom_callback, 10)
# Create publisher for robot pose visualization
self.pose_marker_pub = self.create_publisher(MarkerArray, "/scene_graph/viz/robot_pose", 10)
# Initialize trajectory tracking variables
self.trajectory_points = []
self.max_trajectory_points = 1000 # Limit trajectory history to prevent memory overflow
self.get_logger().info('Odom Visualization Node initialized')
def odom_callback(self, msg):
"""
Callback for robot odometry data.
Stores the latest robot pose and creates visualization markers showing:
1. An arrow indicating position and orientation
2. A sphere at the robot's position
3. A line strip showing the robot's trajectory
Args:
msg (nav_msgs/Odometry): Robot odometry containing pose and velocity
"""
# Store the latest odometry message
self.latest_odom = msg
# Create a marker array to hold multiple visualization markers
marker_array = MarkerArray()
# 1. Create arrow marker for robot pose (shows both position and orientation)
arrow_marker = self.create_pose_arrow(msg)
marker_array.markers.append(arrow_marker)
# 2. Create sphere marker for position only (easier to see than arrow tip)
position_marker = self.create_position_sphere(msg)
marker_array.markers.append(position_marker)
# 3. Create and update trajectory line showing robot's path history
self.trajectory_points.append(msg.pose.pose.position)
# Remove oldest point if trajectory exceeds maximum length
if len(self.trajectory_points) > self.max_trajectory_points:
self.trajectory_points.pop(0)
trajectory_marker = self.create_trajectory(msg.header.frame_id)
marker_array.markers.append(trajectory_marker)
# Publish all visualization markers
self.pose_marker_pub.publish(marker_array)
def create_pose_arrow(self, odom_msg):
"""
Create an ARROW marker showing robot's position and orientation.
The arrow points in the direction the robot is facing, providing
visual feedback on both location and heading.
Args:
odom_msg (nav_msgs/Odometry): Odometry message with pose information
Returns:
visualization_msgs/Marker: Arrow marker for RViz
"""
marker = Marker()
marker.header = odom_msg.header
# FIXME: use position from SLAM instead of raw odometry
marker.header.frame_id = "map"
marker.ns = "robot_pose" # Namespace for grouping markers
marker.id = 0 # Unique ID within namespace
marker.type = Marker.ARROW
marker.action = Marker.ADD
# Set pose from odometry (position and orientation)
marker.pose = odom_msg.pose.pose
# Arrow dimensions (length, width, height)
marker.scale.x = 0.5 # Arrow length (0.5 meters)
marker.scale.y = 0.05 # Arrow shaft width
marker.scale.z = 0.05 # Arrow shaft height
# Color (Red arrow for visibility)
marker.color.r = 1.0
marker.color.g = 0.0
marker.color.b = 0.0
marker.color.a = 1.0 # Fully opaque
# Persistent marker (lifetime=0 means it stays until deleted)
marker.lifetime = rclpy.duration.Duration(seconds=0).to_msg()
return marker
def create_position_sphere(self, odom_msg):
"""
Create a SPHERE marker at the robot's position.
This provides an easy-to-see indicator of the robot's current location,
complementing the arrow marker.
Args:
odom_msg (nav_msgs/Odometry): Odometry message with pose information
Returns:
visualization_msgs/Marker: Sphere marker for RViz
"""
marker = Marker()
marker.header = odom_msg.header
# FIXME: use position from SLAM instead of raw odometry
marker.header.frame_id = "map"
marker.ns = "robot_position"
marker.id = 1 # Different ID from arrow marker
marker.type = Marker.SPHERE
marker.action = Marker.ADD
# Set position only (orientation doesn't matter for a sphere)
marker.pose.position = odom_msg.pose.pose.position
marker.pose.orientation.w = 1.0 # Identity quaternion
# Sphere size (0.2m diameter)
marker.scale.x = 0.2
marker.scale.y = 0.2
marker.scale.z = 0.2
# Color (Green sphere)
marker.color.r = 0.0
marker.color.g = 1.0
marker.color.b = 0.0
marker.color.a = 0.8 # Semi-transparent
marker.lifetime = rclpy.duration.Duration(seconds=0).to_msg()
return marker
def create_trajectory(self, frame_id):
"""
Create a LINE_STRIP marker showing the robot's path history.
This visualizes where the robot has been by connecting all previous
position points with a continuous line.
Args:
frame_id (str): Reference frame for the marker
Returns:
visualization_msgs/Marker: Line strip marker for RViz
"""
marker = Marker()
marker.header.frame_id = frame_id
marker.header.stamp = self.get_clock().now().to_msg()
marker.ns = "trajectory"
marker.id = 2 # Different ID from pose markers
marker.type = Marker.LINE_STRIP
marker.action = Marker.ADD
# Line width
marker.scale.x = 0.02
# Color (Blue trajectory)
marker.color.r = 0.0
marker.color.g = 0.0
marker.color.b = 1.0
marker.color.a = 0.8 # Semi-transparent
# Add all stored trajectory points to the line
for point in self.trajectory_points:
marker.points.append(point)
marker.lifetime = rclpy.duration.Duration(seconds=0).to_msg()
return marker
def main(args=None):
"""
Main entry point for the ROS2 node.
"""
rclpy.init(args=args)
node = OdomVisualizationNode()
try:
rclpy.spin(node)
except KeyboardInterrupt:
pass
finally:
node.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
+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
+15 -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,14 @@ 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',
'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'
],
},
)
+75
View File
@@ -0,0 +1,75 @@
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()
+224
View File
@@ -0,0 +1,224 @@
import numpy as np
import pytest
from geometry_msgs.msg import Pose, Point, Quaternion
from scene_graph_generation_pipeline.object_localization.geometry_utils import GeometryUtils
def test_project_mask_to_3d():
# Setup test inputs
depth_scale = 0.001
intrinsics = {
'fx': 500.0, 'fy': 500.0,
'cx': 320.0, 'cy': 240.0
}
# 640x480 depth image of constant depth 1000 (which corresponds to 1.0 meter)
depth_img = np.full((480, 640), 1000, dtype=np.uint16)
# Simple 2D mask of 2x2 pixels at the center
mask = np.zeros((480, 640), dtype=bool)
mask[240, 320] = True
mask[240, 321] = True
# Project
points_3d = GeometryUtils.project_mask_to_3d(depth_img, mask, intrinsics, depth_scale)
assert points_3d.shape[0] == 2
assert points_3d.shape[1] == 3
# Point 1 check: mask[240, 320]
# u = 320, v = 240.
# z = 1000 * 0.001 = 1.0
# x = (320 - 320) * 1.0 / 500 = 0.0
# y = (240 - 240) * 1.0 / 500 = 0.0
# So point 1 should be approx [0, 0, 1]
np.testing.assert_allclose(points_3d[0], [0.0, 0.0, 1.0], atol=1e-5)
# Point 2 check: mask[240, 321]
# u = 321, v = 240
# z = 1.0
# x = (321 - 320) * 1.0 / 500 = 0.002
np.testing.assert_allclose(points_3d[1], [0.002, 0.0, 1.0], atol=1e-5)
def test_project_mask_to_3d_out_of_range():
# Setup test inputs
depth_scale = 0.001
intrinsics = {
'fx': 500.0, 'fy': 500.0,
'cx': 320.0, 'cy': 240.0
}
# Depth values that are filtered out (e.g. 50 meaning 0.05m (<0.1m) or 15000 meaning 15.0m (>10.0m))
depth_img = np.full((480, 640), 50, dtype=np.uint16)
mask = np.zeros((480, 640), dtype=bool)
mask[240, 320] = True
points_3d = GeometryUtils.project_mask_to_3d(depth_img, mask, intrinsics, depth_scale)
assert points_3d.shape == (0, 3) or len(points_3d) == 0
def test_project_bbox_to_3d():
depth_scale = 0.001
intrinsics = {
'fx': 500.0, 'fy': 500.0,
'cx': 320.0, 'cy': 240.0
}
# 640x480 depth image of constant depth 1000 (1.0 meter)
depth_img = np.full((480, 640), 1000, dtype=np.uint16)
# Bbox centered
bbox = [300, 220, 340, 260] # w=40, h=40
# shrink_ratio=0.15 => dx = 6, dy = 6. Shrunk bbox: [306, 226, 334, 254]
# width = 334 - 306 + 1 = 29
# height = 254 - 226 + 1 = 29
# Total points = 29 * 29 = 841
points_3d = GeometryUtils.project_bbox_to_3d(depth_img, bbox, intrinsics, depth_scale, shrink_ratio=0.15)
assert points_3d.shape[0] == 841
assert points_3d.shape[1] == 3
# Check that points are indeed in the shrunk bounds
# center is u=320, v=240 => x=0, y=0, z=1
# Check min/max values
# sx1=306 => x_min = (306 - 320) * 1.0 / 500 = -0.028
# sx2=334 => x_max = (334 - 320) * 1.0 / 500 = 0.028
# sy1=226 => y_min = (226 - 240) * 1.0 / 500 = -0.028
# sy2=254 => y_max = (254 - 240) * 1.0 / 500 = 0.028
np.testing.assert_allclose(np.min(points_3d, axis=0), [-0.028, -0.028, 1.0], atol=1e-5)
np.testing.assert_allclose(np.max(points_3d, axis=0), [0.028, 0.028, 1.0], atol=1e-5)
def test_clean_outliers():
# 10 points close to origin, 1 point far away
points = np.array([
[0.0, 0.0, 0.0],
[0.1, 0.0, 0.0],
[0.0, 0.1, 0.0],
[0.0, 0.0, 0.1],
[-0.1, 0.0, 0.0],
[0.0, -0.1, 0.0],
[0.0, 0.0, -0.1],
[0.05, 0.05, 0.05],
[-0.05, -0.05, -0.05],
[0.02, -0.02, 0.01],
[10.0, 10.0, 10.0] # Outlier
])
clean = GeometryUtils.clean_outliers(points, std_ratio=1.0)
# The outlier at [10.0, 10.0, 10.0] should be filtered out
assert len(clean) == 10
for pt in clean:
assert np.linalg.norm(pt) < 1.0
def test_compute_3d_bbox():
# Set of 3D points
points = np.array([
[-1.0, -2.0, -3.0],
[1.0, 2.0, 3.0],
[0.0, 0.0, 0.0]
])
bbox = GeometryUtils.compute_3d_bbox(points)
assert bbox is not None
np.testing.assert_allclose(bbox['min'], [-1.0, -2.0, -3.0])
np.testing.assert_allclose(bbox['max'], [1.0, 2.0, 3.0])
np.testing.assert_allclose(bbox['center'], [0.0, 0.0, 0.0])
np.testing.assert_allclose(bbox['size'], [2.0, 4.0, 6.0])
# Empty points check
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([
[0.0, 0.0, 1.0]
])
# Identity pose (zero translation, identity rotation q = [0, 0, 0, 1])
pose = Pose()
pose.position = Point(x=0.0, y=0.0, z=0.0)
pose.orientation = Quaternion(x=0.0, y=0.0, z=0.0, w=1.0)
transformed = GeometryUtils.transform_points_camera_to_map(points_cam, pose)
# Check shape
assert transformed.shape == (1, 3)
assert np.all(np.isfinite(transformed))
def test_transform_points():
# Setup test points
points = np.array([
[1.0, 2.0, 3.0]
])
# Test 1: Identity transformation
translation = [0.0, 0.0, 0.0]
rotation = [0.0, 0.0, 0.0, 1.0] # x,y,z,w
transformed = GeometryUtils.transform_points(points, translation, rotation)
np.testing.assert_allclose(transformed, points, atol=1e-5)
# Test 2: Simple translation only
translation = [10.0, -5.0, 2.5]
transformed = GeometryUtils.transform_points(points, translation, rotation)
np.testing.assert_allclose(transformed, [[11.0, -3.0, 5.5]], atol=1e-5)
# Test 3: Simple 90-degree rotation around Z-axis
# Yaw = 90 deg => q = [0, 0, sin(45), cos(45)] = [0, 0, 0.707107, 0.707107]
# Rotate [1, 2, 3] by 90 deg around Z:
# x' = x*cos(90) - y*sin(90) = 1*0 - 2*1 = -2
# y' = x*sin(90) + y*cos(90) = 1*1 + 2*0 = 1
# z' = z = 3
translation = [0.0, 0.0, 0.0]
rotation = [0.0, 0.0, np.sin(np.pi/4), np.cos(np.pi/4)]
transformed = GeometryUtils.transform_points(points, translation, rotation)
np.testing.assert_allclose(transformed, [[-2.0, 1.0, 3.0]], atol=1e-5)
+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()