78 Commits
Author SHA1 Message Date
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
Ben Ronde 91a842b284 update comments 2026-02-04 15:39:15 +01:00
Adrian_Manteca f3efaecfb2 Comment translation 2026-02-03 17:24:16 +01:00
Ben Ronde 5b5ee6d535 remove redundant functionalelement attribute 2026-02-01 16:25:19 +01:00
Adrian_Manteca 3ca202a9da smal Speicher-Stop fix 2026-01-28 17:42:48 +01:00
Adrian_Manteca 055546c29b Fixed Speicher-Stop and object deletion 2026-01-28 17:37:40 +01:00
Adrian_Manteca 24347959ea Merge remote changes 2026-01-28 15:35:26 +01:00
Adrian_Manteca c649a9001d Fix Task Processing 2026-01-28 15:32:11 +01:00
Ben Ronde 0e6f92a9ab fix publishers not working correctly 2026-01-27 16:29:08 +01:00
Ben Ronde 7c31dc9d7e adjust for new publishers 2026-01-27 16:00:57 +01:00
Adrian_Manteca 388489f510 Task processing 2026-01-27 12:06:15 +01:00
Ben Ronde c443c935af add publishers 2026-01-27 11:31:46 +01:00
Adrian_Manteca e75d97210e Update Delete 2026-01-27 11:20:27 +01:00
Ben Ronde 94d3778855 add new publishers 2026-01-27 10:25:22 +01:00
Adrian_Manteca 9ba7b4f4b4 Subscriber Update 2026-01-27 10:19:39 +01:00
Ben Ronde 4df1429a2e latency logs 2026-01-24 12:53:44 +01:00
Ben Ronde 02977b67a2 change logs to show latency 2026-01-22 12:40:47 +01:00
Ben Ronde cc3885b83c change order of functions 2026-01-19 22:46:13 +01:00
Adrian_Manteca f0452af063 Merge remote changes 2026-01-19 22:01:54 +01:00
Adrian_Manteca a30b372540 Löschen und Speicher-Pausen Funktionalität 2026-01-19 21:56:35 +01:00
Ben Ronde 325d214ee7 add target logic and allow update-boolean 2026-01-16 15:44:39 +01:00
Ben Ronde aca0791ec2 add console log to scene_graph_fusion_node 2026-01-12 15:38:13 +01:00
Ben Ronde fa1bcb5fa9 update comments 2025-12-18 16:21:28 +01:00
Ben Ronde cc5bac24e7 adjust merging 2025-12-15 14:54:13 +01:00
Adrian_Manteca 0ff81b2daa Verbesserung Merging 2025-12-14 10:35:47 +01:00
Ben Ronde dcd2719c10 edit todos 2025-12-13 13:46:05 +01:00
Ben Ronde fff6f2c247 add pointcloud publishers 2025-12-13 12:31:44 +01:00
Ben Ronde 3a62c456e5 adjustments for new subscribers 2025-12-12 17:52:47 +01:00
Ben Ronde dde7c419fa Merge remote-tracking branch 'origin/localization_with_sam' into graph 2025-12-12 12:27:18 +01:00
Ben Ronde 7dba151fa9 merge detection 2025-12-12 12:24:59 +01:00
Yehia_Elhaw e83be6eb7b integrate with FunObject3DBoundingBox 2025-12-12 00:48:51 +01:00
Ben Ronde bdda7eb66b add new subs 2025-12-11 13:04:16 +01:00
Yehia_Elhaw 75ec715102 simplified sam_wrapper.py 2025-12-08 20:55:46 +01:00
Ben Ronde a4b5064475 update fusion node 2025-12-08 17:59:05 +01:00
Yehia_Elhaw c1637b77e5 update Launch file 2025-12-08 15:46:45 +01:00
Adrian_Manteca 7112d1411e changes 2025-12-07 11:36:29 +01:00
Yehia_Elhaw 848261285b made a node for odom viz 2025-12-06 17:27:33 +01:00
Yehia_Elhaw 99045752c8 Renamed SamNode into ObjectLocalizationNode 2025-12-06 16:55:45 +01:00
Yehia_Elhaw 69be071cfa integrated localization with object_detection_node 2025-12-06 16:33:51 +01:00
Yehia_Elhaw 450fc1b12e Merge branch 'detection' into localization_with_sam 2025-12-06 15:30:54 +01:00
Yehia_Elhaw 40b966df44 revert zoe and rely on sensor data 2025-12-05 17:33:04 +01:00
Yehia_Elhaw 107e0f6ed2 factored geometery in sam_node into geo_utils 2025-12-02 01:38:40 +01:00
Yehia_Elhaw 163f70b51c update .gitignore 2025-12-01 16:16:25 +01:00
Yehia_Elhaw db71d617a2 added timm dependency 2025-12-01 14:47:29 +01:00
Ben Ronde a0728c8da4 adjust subscribers 2025-11-30 18:16:36 +01:00
Yehia_Elhaw 0bad0a2a5d use odometry for transforms 2025-11-30 01:47:27 +01:00
Yehia_Elhaw acc19d7c47 removed unnecessary tf2_ros 2025-11-30 01:25:14 +01:00
Yehia_Elhaw a0caa80bc4 added zoe_wrapper (pip install timm==0.6.7)
added zoe_wrapper (pip install timm==0.6.7)
2025-11-29 19:12:10 +01:00
Ben Ronde 1518561294 Merge remote-tracking branch 'origin/localization_with_sam' into graph 2025-11-29 13:18:11 +01:00
Ben Ronde 5c256595fd adjust bbox logic 2025-11-28 17:25:42 +01:00
Ben Ronde 5241a1c9c7 test 2025-11-27 23:40:22 +01:00
Ben Ronde 09b9cba022 Revert "modify bbox callback"
This reverts commit 9b85b537b4.
2025-11-27 23:36:52 +01:00
Ben Ronde 0cc316cc38 Revert "Von AABB zu OBB"
This reverts commit a013ed3110.
2025-11-27 23:29:56 +01:00
Adrian_Manteca a013ed3110 Von AABB zu OBB 2025-11-27 20:59:36 +01:00
Ben Ronde 9b85b537b4 modify bbox callback 2025-11-27 19:08:09 +01:00
Ben Ronde ab478f4b3a add FunctionalElementNode 2025-11-25 20:07:13 +01:00
Yehia_Elhaw 9a7c86474c added sync_callback 2025-11-24 23:23:24 +01:00
Yehia_Elhaw 43130a4a46 sam_node.py init 2025-11-24 23:22:03 +01:00
Yehia_Elhaw b79e4ccfbd Polished comments 2025-11-24 22:46:31 +01:00
Yehia_Elhaw 5a33efad68 Added sam_wrapper.py 2025-11-24 22:46:03 +01:00
Yehia_Elhaw 5e24272ca2 Polished comments 2025-11-24 22:42:40 +01:00
Yehia_Elhaw 849c5f2e72 Included clean_outliers for noise reduction and compute_3d_bbox for spatial analysis 2025-11-24 22:36:33 +01:00
Yehia_Elhaw 16e17cdd22 Added transform_points to handle frame conversions 2025-11-24 22:35:09 +01:00
Yehia_Elhaw aee122bf55 Added project_mask_to_3d using vectorized pinhole camera mathematics 2025-11-24 22:32:31 +01:00
Yehia_Elhaw d478b80fc5 geometry_utils.py init 2025-11-24 22:24:29 +01:00
32 changed files with 6638 additions and 1418 deletions
+2 -1
View File
@@ -5,4 +5,5 @@ pipeline.png
/build/
/install/
/log/
~/.cache
~/.cache
.vscode/
+56 -8
View File
@@ -1,16 +1,29 @@
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."""
# Image Segmentation Node
image_segmentation_node = Node(
# 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',
executable='image_segmentation_node',
name='image_segmentation_node',
executable='object_detection_node',
name='object_detection_node',
output='screen',
parameters=[],
parameters=common_params,
remappings=[]
)
@@ -20,7 +33,7 @@ def generate_launch_description():
executable='object_localization_node',
name='object_localization_node',
output='screen',
parameters=[],
parameters=common_params,
remappings=[]
)
@@ -30,12 +43,47 @@ def generate_launch_description():
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',
executable='odom_vizualization_node',
name='odom_vizualization_node',
output='screen',
parameters=common_params,
remappings=[]
)
# Room Classification Node
room_classification_node = Node(
package='scene_graph_room_classification',
executable='room_classification_node',
name='room_classification_node',
output='screen',
parameters=common_params,
remappings=[]
)
# Room Segmentation Node
room_segmentation_node = Node(
package='scene_graph_room_classification',
executable='room_segmentation_node',
name='room_segmentation_node',
output='screen',
parameters=common_params,
remappings=[]
)
return LaunchDescription([
image_segmentation_node,
use_sim_time_arg,
object_detection_node,
object_localization_node,
scene_graph_fusion_node,
odom_vizualization_node,
room_classification_node,
room_segmentation_node
])
+119
View File
@@ -0,0 +1,119 @@
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_room_classification',
executable='object_detection_node',
name='object_detection_node',
output='screen',
parameters=common_params,
remappings=[]
)
# Object Localization Node
object_localization_node = Node(
package='scene_graph_room_classification',
executable='object_localization_node',
name='object_localization_node',
output='screen',
parameters=common_params,
remappings=[]
)
# Scene Graph Fusion Node
scene_graph_fusion_node = Node(
package='scene_graph_room_classification',
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_room_classification',
executable='odom_vizualization_node',
name='odom_vizualization_node',
output='screen',
parameters=common_params,
remappings=[]
)
# Room Classification Node
room_classification_node = Node(
package='scene_graph_room_classification',
executable='room_classification_node',
name='room_classification_node',
output='screen',
parameters=common_params,
remappings=[]
)
# Room Segmentation Node
room_segmentation_node = Node(
package='scene_graph_room_classification',
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_room_classification/rviz/graph_video.rviz'],
parameters=[{'use_sim_time': True}],
additional_env={'DISPLAY': ':1'}
)
return LaunchDescription([
rtabmap_slam,
object_detection_node,
object_localization_node,
scene_graph_fusion_node,
odom_vizualization_node,
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.
+16 -1
View File
@@ -12,9 +12,24 @@
<test_depend>ament_pep257</test_depend>
<test_depend>python3-pytest</test_depend>
<!-- 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 -->
<exec_depend>scene_graph_interfaces</exec_depend>
<export>
<build_type>ament_python</build_type>
</export>
</package>
</package>
+3 -1
View File
@@ -4,7 +4,9 @@ numpy>=1.17.3,<1.25.0
networkx
scipy
shapely
open3d
pillow>=9.5.0
pyyaml
requests
huggingface-hub
huggingface-hub
git+https://github.com/openai/CLIP.git
+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,8 +107,8 @@ 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
@@ -170,15 +129,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
@@ -194,13 +148,6 @@ class ObjectDetectionNode(Node):
yolo_objects_msg.objects = yolo_detected_objects
yolo_objects_msg.header.stamp = current_time
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 +206,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 +216,6 @@ class ObjectDetectionNode(Node):
object_details.append({
'class': class_name,
'confidence': confidence,
'graspable': is_graspable,
'bbox': (x1, y1, x2, y2)
})
@@ -282,7 +225,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 +240,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 +258,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 +298,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
@@ -10,7 +10,32 @@ Structure: Each entry is (label_name, is_graspable)
# 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),
@@ -20,38 +45,138 @@ VOCABULARY_DATA = [
("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),
("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),
#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),
("box", True),
("bag", 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),
("backpack", True),
#new
("notebook", False), # False / True?
("binder", False),
("folder", False), # False / True?
("briefcase", False),
("suitcase", False),
("clipboard", False),
("wallet", False), # False / True?
]
@@ -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
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,80 @@
import torch
from ultralytics import SAM, FastSAM
class SamWrapper:
"""Wrapper for Ultralytics SAM/SAM2/FastSAM to handle prompted segmentation via bounding boxes."""
def __init__(self, model_name):
"""
Initializes segmenter model.
Args:
model_name (str): Model name / path (e.g. 'FastSAM-s.pt', 'sam2_b.pt', etc.)
"""
self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
print(f"[SamWrapper] Loading {model_name} on {self.device}...")
try:
if "FastSAM" in model_name:
self.model = FastSAM(model_name)
else:
self.model = SAM(model_name)
self.model.to(self.device)
print("[SamWrapper] Model loaded successfully.")
except Exception as e:
print(f"[SamWrapper] Error loading model: {e}")
raise e
def predict(self, image, bboxes):
"""Generates segmentation masks based on bounding box prompts."""
if not bboxes or len(bboxes) == 0:
return []
try:
# Run inference with bbox prompts
results = self.model(image, bboxes=bboxes, verbose=False)
except Exception as e:
print(f"[SamWrapper] Inference failed: {e}")
return [None] * len(bboxes)
if not results or results[0].masks is None:
return [None] * len(bboxes)
# Extract masks, move to CPU, and convert to numpy
masks_tensor = results[0].masks.data
masks_np = masks_tensor.cpu().numpy().astype(bool)
# Get bounding boxes corresponding to the detected masks
detected_boxes = results[0].boxes.xyxy.cpu().numpy()
def bbox_iou(box1, box2):
x1 = max(box1[0], box2[0])
y1 = max(box1[1], box2[1])
x2 = min(box1[2], box2[2])
y2 = min(box1[3], box2[3])
intersection = max(0.0, x2 - x1) * max(0.0, y2 - y1)
area1 = (box1[2] - box1[0]) * (box1[3] - box1[1])
area2 = (box2[2] - box2[0]) * (box2[3] - box2[1])
union = area1 + area2 - intersection
if union == 0:
return 0.0
return intersection / union
# Match each input bbox to a returned mask using IoU
matched_masks = [None] * len(bboxes)
for i, input_bbox in enumerate(bboxes):
best_iou = 0.0
best_idx = -1
for j, det_box in enumerate(detected_boxes):
iou = bbox_iou(input_bbox, det_box)
if iou > best_iou:
best_iou = iou
best_idx = j
if best_idx != -1 and best_iou > 0.3:
matched_masks[i] = masks_np[best_idx]
return matched_masks
@@ -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_room_classification/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_room_classification/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,208 @@
#!/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_room_classification')
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:
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,193 @@
#!/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
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('min_room_area', 2.0) # Minimum room area in square meters
self.declare_parameter('min_room_radius', 0.8) # Expected room radius in meters
self.declare_parameter('simplification_tolerance', 0.1) # Polygon simplification tolerance in meters
self.declare_parameter('process_min_interval', 2.0) # Rate limit in seconds
self.map_topic = self.get_parameter('map_topic').get_parameter_value().string_value
self.rooms_topic = self.get_parameter('rooms_topic').get_parameter_value().string_value
self.min_room_area = self.get_parameter('min_room_area').get_parameter_value().double_value
self.min_room_radius = self.get_parameter('min_room_radius').get_parameter_value().double_value
self.simplification_tolerance = self.get_parameter('simplification_tolerance').get_parameter_value().double_value
self.process_min_interval = self.get_parameter('process_min_interval').get_parameter_value().double_value
self.get_logger().info(f"Subscribing to map topic: {self.map_topic}")
self.get_logger().info(f"Publishing rooms to: {self.rooms_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
)
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} (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
# 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)
self.get_logger().info(f"Successfully segmented and published {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()
File diff suppressed because it is too large Load Diff
+10 -1
View File
@@ -14,8 +14,14 @@ 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_room_classification/room_classification/rf_classifier.pkl']),
],
install_requires=['setuptools'],
install_requires=['setuptools', 'open3d', 'shapely', "huggingface_hub"],
zip_safe=True,
maintainer='root',
maintainer_email='root@todo.todo',
@@ -31,6 +37,9 @@ setup(
'object_detection_node = scene_graph_room_classification.object_detection.object_detection_node:main',
'object_localization_node = scene_graph_room_classification.object_localization.object_localization_node:main',
'scene_graph_fusion_node = scene_graph_room_classification.scene_graph_fusion.scene_graph_fusion_node:main',
'odom_vizualization_node = scene_graph_room_classification.odom_vizualization.odom_vizualization_node:main',
'room_classification_node = scene_graph_room_classification.room_classification.room_classification_node:main',
'room_segmentation_node = scene_graph_room_classification.room_segmentation.room_segmentation_node:main'
],
},
)
+224
View File
@@ -0,0 +1,224 @@
import numpy as np
import pytest
from geometry_msgs.msg import Pose, Point, Quaternion
from scene_graph_room_classification.object_localization.geometry_utils import GeometryUtils
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_room_classification.object_localization.sam_wrapper.SamWrapper'), \
patch('scene_graph_room_classification.object_localization.object_localization_node.Buffer'), \
patch('scene_graph_room_classification.object_localization.object_localization_node.TransformListener'):
from scene_graph_room_classification.object_localization.object_localization_node import ObjectLocalizationNode
def test_node_parameter():
if not rclpy.ok():
rclpy.init()
with patch('scene_graph_room_classification.object_localization.sam_wrapper.SamWrapper'), \
patch('scene_graph_room_classification.object_localization.object_localization_node.Buffer'), \
patch('scene_graph_room_classification.object_localization.object_localization_node.TransformListener'):
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()
+51
View File
@@ -0,0 +1,51 @@
# 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_room_classification.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."""
with patch('builtins.open', MagicMock()), \
patch('pickle.load', return_value=MagicMock()):
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 "office"
room_label_unknown = node.classify_room(['random_unknown_object'])
assert room_label_unknown == 'office'
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_room_classification.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()