Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f93011219e | ||
|
|
74add73a61 | ||
|
|
4ee096d037 | ||
|
|
aef27851d6 | ||
|
|
a9be8192de | ||
|
|
992afe5f4e | ||
|
|
47af27b686 | ||
|
|
7d471405f4 | ||
|
|
37631e0c98 | ||
|
|
019d17923e | ||
|
|
4a6058d490 | ||
|
|
229d26a0eb | ||
|
|
6d03da054a | ||
|
|
ed44e3471a |
+2
-1
@@ -5,4 +5,5 @@ pipeline.png
|
||||
/build/
|
||||
/install/
|
||||
/log/
|
||||
~/.cache
|
||||
~/.cache
|
||||
.vscode/
|
||||
@@ -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."""
|
||||
|
||||
# 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='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,7 +43,7 @@ def generate_launch_description():
|
||||
executable='scene_graph_fusion_node',
|
||||
name='scene_graph_fusion_node',
|
||||
output='screen',
|
||||
parameters=[],
|
||||
parameters=common_params,
|
||||
remappings=[]
|
||||
)
|
||||
|
||||
@@ -40,13 +53,37 @@ def generate_launch_description():
|
||||
executable='odom_vizualization_node',
|
||||
name='odom_vizualization_node',
|
||||
output='screen',
|
||||
parameters=[],
|
||||
parameters=common_params,
|
||||
remappings=[]
|
||||
)
|
||||
|
||||
# Room Classification Node
|
||||
room_classification_node = Node(
|
||||
package='scene_graph_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([
|
||||
use_sim_time_arg,
|
||||
object_detection_node,
|
||||
object_localization_node,
|
||||
scene_graph_fusion_node,
|
||||
odom_vizualization_node
|
||||
odom_vizualization_node,
|
||||
room_classification_node,
|
||||
room_segmentation_node
|
||||
])
|
||||
|
||||
|
||||
@@ -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.
@@ -15,10 +15,15 @@
|
||||
<!-- Execution Dependencies needed for your node -->
|
||||
<exec_depend>rclpy</exec_depend>
|
||||
<exec_depend>sensor_msgs</exec_depend>
|
||||
<exec_depend>nav_msgs</exec_depend>
|
||||
<exec_depend>cv_bridge</exec_depend>
|
||||
<exec_depend>python3-opencv</exec_depend>
|
||||
<exec_depend>std_msgs</exec_depend>
|
||||
<exec_depend>python3-pip</exec_depend>
|
||||
<exec_depend>rtabmap_msgs</exec_depend>
|
||||
<exec_depend>geometry_msgs</exec_depend>
|
||||
<exec_depend>tf2_ros</exec_depend>
|
||||
<exec_depend>visualization_msgs</exec_depend>
|
||||
|
||||
|
||||
<!-- Your custom interface package -->
|
||||
|
||||
@@ -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?
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
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."""
|
||||
@@ -20,6 +24,12 @@ class GeometryUtils:
|
||||
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]
|
||||
@@ -29,18 +39,152 @@ class GeometryUtils:
|
||||
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=2.0):
|
||||
"""Removes statistical outliers using distance-based thresholding."""
|
||||
if len(points) < 10:
|
||||
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
|
||||
|
||||
center = np.mean(points, axis=0)
|
||||
distances = np.linalg.norm(points - center, axis=1)
|
||||
|
||||
threshold = np.mean(distances) + (std_ratio * np.std(distances))
|
||||
return points[distances < threshold]
|
||||
|
||||
# --- 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):
|
||||
@@ -58,6 +202,60 @@ class GeometryUtils:
|
||||
'max': max_pt
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def compute_3d_obb(points):
|
||||
"""
|
||||
Computes the Yaw-aligned Oriented Bounding Box (OBB-Z) of a 3D point cloud.
|
||||
|
||||
Returns:
|
||||
dict containing:
|
||||
'center': [x, y, z] center of the box
|
||||
'size': [sx, sy, sz] dimensions
|
||||
'corners': list of 8 lists (each [x,y,z]), representing the 8 vertices
|
||||
ordered as 4 bottom vertices followed by 4 top vertices.
|
||||
'rotation': [qx, qy, qz, qw] orientation quaternion
|
||||
"""
|
||||
if len(points) == 0:
|
||||
return None
|
||||
|
||||
# 1. Project points to XY plane (2D)
|
||||
pts_2d = points[:, :2].astype(np.float32)
|
||||
|
||||
# 2. Find minimum area bounding box in 2D
|
||||
rect = cv2.minAreaRect(pts_2d)
|
||||
(cx, cy), (w, h), angle_deg = rect
|
||||
|
||||
# 3. Get Z-bounds from 3D points
|
||||
min_z = float(np.min(points[:, 2]))
|
||||
max_z = float(np.max(points[:, 2]))
|
||||
cz = (min_z + max_z) / 2.0
|
||||
sz = max_z - min_z
|
||||
|
||||
# 4. Get the 4 corners of the 2D bounding box
|
||||
corners_2d = cv2.boxPoints(rect)
|
||||
|
||||
# 5. Build 8 corners in 3D: 4 bottom (min_z) and 4 top (max_z)
|
||||
corners_3d = []
|
||||
for pt in corners_2d:
|
||||
corners_3d.append([float(pt[0]), float(pt[1]), min_z])
|
||||
for pt in corners_2d:
|
||||
corners_3d.append([float(pt[0]), float(pt[1]), max_z])
|
||||
|
||||
# 6. Compute 3D quaternion for yaw rotation
|
||||
angle_rad = np.radians(angle_deg)
|
||||
yaw = angle_rad
|
||||
qx = 0.0
|
||||
qy = 0.0
|
||||
qz = float(np.sin(yaw / 2.0))
|
||||
qw = float(np.cos(yaw / 2.0))
|
||||
|
||||
return {
|
||||
'center': [float(cx), float(cy), float(cz)],
|
||||
'size': [float(w), float(h), float(sz)],
|
||||
'corners': corners_3d,
|
||||
'rotation': [qx, qy, qz, qw]
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def transform_points_camera_to_map(points_cam, odom_pose):
|
||||
"""Transforms points from camera optical frame to map frame via odometry."""
|
||||
@@ -100,4 +298,45 @@ class GeometryUtils:
|
||||
pos = odom_pose.position
|
||||
robot_position = np.array([pos.x, pos.y, pos.z])
|
||||
|
||||
return points_rotated + robot_position
|
||||
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
|
||||
@@ -2,70 +2,88 @@
|
||||
|
||||
import rclpy
|
||||
from rclpy.node import Node
|
||||
from rclpy.callback_groups import ReentrantCallbackGroup
|
||||
from rclpy.executors import MultiThreadedExecutor
|
||||
import message_filters
|
||||
from sensor_msgs.msg import Image, CameraInfo, PointCloud2, PointField
|
||||
from nav_msgs.msg import Odometry
|
||||
from std_msgs.msg import Header, String
|
||||
from geometry_msgs.msg import Point32
|
||||
from scene_graph_interfaces.msg import ObjectList, FunObjectList, Object3DBoundingBox, Object3DBoundingBoxList, FunObject3DBoundingBox, FunObject3DBoundingBoxList
|
||||
from geometry_msgs.msg import Point32, Point
|
||||
from scene_graph_interfaces.msg import ObjectList, Object3DBoundingBox, Object3DBoundingBoxList
|
||||
from cv_bridge import CvBridge
|
||||
import numpy as np
|
||||
import sensor_msgs_py.point_cloud2 as pc2
|
||||
import cv2
|
||||
import time
|
||||
import threading
|
||||
from tf2_ros import Buffer, TransformListener
|
||||
from visualization_msgs.msg import Marker, MarkerArray
|
||||
|
||||
from rclpy.parameter import Parameter
|
||||
|
||||
from .sam_wrapper import SamWrapper
|
||||
from .geometry_utils import GeometryUtils
|
||||
|
||||
class ObjectLocalizationNode(Node):
|
||||
def __init__(self):
|
||||
super().__init__('object_localization_node')
|
||||
super().__init__(
|
||||
'object_localization_node',
|
||||
parameter_overrides=[Parameter('use_sim_time', value=True)]
|
||||
)
|
||||
|
||||
# --- 1. CONFIGURATION ---
|
||||
model_name = 'sam2_b.pt'
|
||||
model_name = 'FastSAM-s.pt'
|
||||
self.depth_scale = 0.001
|
||||
self.declare_parameter('max_object_distance', 5.0)
|
||||
max_dist = self.get_parameter('max_object_distance').get_parameter_value().double_value
|
||||
self.get_logger().info(f"Max object distance filter set to: {max_dist} m")
|
||||
|
||||
# --- 2. INITIALIZE MODULES ---
|
||||
self.bridge = CvBridge()
|
||||
|
||||
self.get_logger().info(f"Initializing SAM Wrapper with {model_name}...")
|
||||
self.get_logger().info(f"Initializing FastSAM Wrapper with {model_name}...")
|
||||
self.sam = SamWrapper(model_name=model_name)
|
||||
|
||||
# --- 3. STATE ---
|
||||
self.intrinsics = None
|
||||
self.tf_buffer = Buffer(node=self)
|
||||
self.tf_listener = TransformListener(self.tf_buffer, self, spin_thread=True)
|
||||
|
||||
# Custom buffer state for synchronizing messages
|
||||
self.lock = threading.Lock()
|
||||
self.rgb_buffer = {} # timestamp (float) -> msg
|
||||
self.depth_buffer = {} # timestamp (float) -> msg
|
||||
self.yolo_buffer = {} # timestamp (float) -> msg
|
||||
self.is_processing = False
|
||||
|
||||
# --- 4. SUBSCRIBERS ---
|
||||
self.callback_group = ReentrantCallbackGroup()
|
||||
|
||||
# A. Camera Intrinsics
|
||||
self.get_intrinsics = self.create_subscription(
|
||||
CameraInfo, '/camera/depth/camera_info', self.get_intrinsics_callback, 10)
|
||||
CameraInfo, '/camera/depth/camera_info', self.get_intrinsics_callback, 10,
|
||||
callback_group=self.callback_group)
|
||||
|
||||
# B. Base Synchronized Inputs
|
||||
self.sub_rgb = message_filters.Subscriber(self, Image, '/scene_graph/sync/color/image_raw')
|
||||
self.sub_depth = message_filters.Subscriber(self, Image, '/scene_graph/sync/depth/image_raw')
|
||||
self.sub_odom = message_filters.Subscriber(self, Odometry, '/scene_graph/sync/odom')
|
||||
self.sub_rgb = self.create_subscription(
|
||||
Image, '/scene_graph/sync/color/image_raw', self.rgb_callback, 100,
|
||||
callback_group=self.callback_group)
|
||||
self.sub_depth = self.create_subscription(
|
||||
Image, '/scene_graph/sync/depth/image_raw', self.depth_callback, 100,
|
||||
callback_group=self.callback_group)
|
||||
|
||||
# C. Object Detection Inputs
|
||||
self.sub_yolo = message_filters.Subscriber(self, ObjectList, '/scene_graph/yolo')
|
||||
self.sub_rtdetr = message_filters.Subscriber(self, FunObjectList, '/scene_graph/rtdetr')
|
||||
|
||||
# --- 5. SYNCHRONIZERS ---
|
||||
# Chain 1: RGB + Depth + Odom + YOLO
|
||||
self.ts_yolo = message_filters.ApproximateTimeSynchronizer(
|
||||
[self.sub_rgb, self.sub_depth, self.sub_odom, self.sub_yolo],
|
||||
queue_size=10, slop=0.1)
|
||||
self.ts_yolo.registerCallback(self.yolo_callback)
|
||||
|
||||
# Chain 2: RGB + Depth + Odom + RT-DETR
|
||||
self.ts_rtdetr = message_filters.ApproximateTimeSynchronizer(
|
||||
[self.sub_rgb, self.sub_depth, self.sub_odom, self.sub_rtdetr],
|
||||
queue_size=10, slop=0.1)
|
||||
self.ts_rtdetr.registerCallback(self.rtdetr_callback)
|
||||
self.sub_yolo = self.create_subscription(
|
||||
ObjectList, '/scene_graph/yolo', self.yolo_callback, 100,
|
||||
callback_group=self.callback_group)
|
||||
|
||||
# --- 6. PUBLISHERS ---
|
||||
self.pub_bbox_yolo = self.create_publisher(Object3DBoundingBoxList, '/bounding_boxes_3d/yolo', 10)
|
||||
self.pub_cloud_yolo = self.create_publisher(PointCloud2, '/object_clouds/yolo', 10)
|
||||
|
||||
self.pub_bbox_rtdetr = self.create_publisher(FunObject3DBoundingBoxList, '/bounding_boxes_3d/rtdetr', 10)
|
||||
self.pub_cloud_rtdetr = self.create_publisher(PointCloud2, '/object_clouds/rtdetr', 10)
|
||||
self.pub_markers_yolo = self.create_publisher(MarkerArray, '/scene_graph/viz/current_bounding_boxes_3d', 10)
|
||||
self.pub_pc_markers_yolo = self.create_publisher(MarkerArray, '/bounding_boxes_3d/point_cloud_markers', 10)
|
||||
self.pub_debug_depth_colored = self.create_publisher(Image, '/scene_graph/debug/depth_colored', 10)
|
||||
self.pub_debug_segmented_rgb = self.create_publisher(Image, '/scene_graph/debug/segmented_rgb', 10)
|
||||
|
||||
self.get_logger().info("Object Localization Node Initialized. Waiting for data...")
|
||||
|
||||
@@ -77,22 +95,91 @@ class ObjectLocalizationNode(Node):
|
||||
}
|
||||
self.get_logger().info(f"Intrinsics captured: {self.intrinsics}")
|
||||
|
||||
def yolo_callback(self, rgb_msg, depth_msg, odom_msg, yolo_objs_msg):
|
||||
objects = yolo_objs_msg.objects
|
||||
self.process_segmentation_pipeline(
|
||||
rgb_msg, depth_msg, odom_msg, objects,
|
||||
self.pub_bbox_yolo, self.pub_cloud_yolo, source_name="YOLO",
|
||||
target_list_class=Object3DBoundingBoxList, target_item_class=Object3DBoundingBox)
|
||||
def stamp_to_sec(self, stamp):
|
||||
return float(stamp.sec) + float(stamp.nanosec) * 1e-9
|
||||
|
||||
def rtdetr_callback(self, rgb_msg, depth_msg, odom_msg, rtdetr_objs_msg):
|
||||
objects = rtdetr_objs_msg.fun_objects
|
||||
self.process_segmentation_pipeline(
|
||||
rgb_msg, depth_msg, odom_msg, objects,
|
||||
self.pub_bbox_rtdetr, self.pub_cloud_rtdetr, source_name="RT-DETR",
|
||||
target_list_class=FunObject3DBoundingBoxList, target_item_class=FunObject3DBoundingBox)
|
||||
def rgb_callback(self, msg):
|
||||
t = self.stamp_to_sec(msg.header.stamp)
|
||||
with self.lock:
|
||||
self.rgb_buffer[t] = msg
|
||||
if len(self.rgb_buffer) > 50:
|
||||
oldest = min(self.rgb_buffer.keys())
|
||||
self.rgb_buffer.pop(oldest)
|
||||
self.try_process()
|
||||
|
||||
def process_segmentation_pipeline(self, rgb_msg, depth_msg, odom_msg, objects,
|
||||
pub_bbox, pub_cloud, source_name,
|
||||
def depth_callback(self, msg):
|
||||
t = self.stamp_to_sec(msg.header.stamp)
|
||||
with self.lock:
|
||||
self.depth_buffer[t] = msg
|
||||
if len(self.depth_buffer) > 50:
|
||||
oldest = min(self.depth_buffer.keys())
|
||||
self.depth_buffer.pop(oldest)
|
||||
self.try_process()
|
||||
|
||||
def yolo_callback(self, msg):
|
||||
t = self.stamp_to_sec(msg.header.stamp)
|
||||
with self.lock:
|
||||
self.yolo_buffer[t] = msg
|
||||
if len(self.yolo_buffer) > 50:
|
||||
oldest = min(self.yolo_buffer.keys())
|
||||
self.yolo_buffer.pop(oldest)
|
||||
self.try_process()
|
||||
|
||||
def _find_matching_triplet(self, max_dt=0.05):
|
||||
for t_yolo in list(self.yolo_buffer.keys()):
|
||||
if not self.rgb_buffer or not self.depth_buffer:
|
||||
continue
|
||||
|
||||
# Find closest RGB
|
||||
best_rgb_dt = float('inf')
|
||||
best_t_rgb = None
|
||||
for t_rgb in self.rgb_buffer.keys():
|
||||
dt = abs(t_yolo - t_rgb)
|
||||
if dt < best_rgb_dt:
|
||||
best_rgb_dt = dt
|
||||
best_t_rgb = t_rgb
|
||||
|
||||
# Find closest Depth
|
||||
best_depth_dt = float('inf')
|
||||
best_t_depth = None
|
||||
for t_depth in self.depth_buffer.keys():
|
||||
dt = abs(t_yolo - t_depth)
|
||||
if dt < best_depth_dt:
|
||||
best_depth_dt = dt
|
||||
best_t_depth = t_depth
|
||||
|
||||
if best_t_rgb is not None and best_t_depth is not None:
|
||||
if best_rgb_dt <= max_dt and best_depth_dt <= max_dt:
|
||||
return best_t_rgb, best_t_depth, t_yolo
|
||||
return None
|
||||
|
||||
def try_process(self):
|
||||
with self.lock:
|
||||
if self.is_processing:
|
||||
return
|
||||
match = self._find_matching_triplet(max_dt=0.05)
|
||||
if match is None:
|
||||
return
|
||||
t_rgb, t_depth, t_yolo = match
|
||||
rgb_msg = self.rgb_buffer.pop(t_rgb)
|
||||
depth_msg = self.depth_buffer.pop(t_depth)
|
||||
yolo_msg = self.yolo_buffer.pop(t_yolo)
|
||||
self.is_processing = True
|
||||
|
||||
try:
|
||||
objects = yolo_msg.objects
|
||||
self.process_segmentation_pipeline(
|
||||
rgb_msg, depth_msg, objects,
|
||||
self.pub_bbox_yolo, self.pub_cloud_yolo, self.pub_markers_yolo, self.pub_pc_markers_yolo, source_name="YOLO",
|
||||
target_list_class=Object3DBoundingBoxList, target_item_class=Object3DBoundingBox)
|
||||
finally:
|
||||
with self.lock:
|
||||
self.is_processing = False
|
||||
# Check recursively for more matches
|
||||
self.try_process()
|
||||
|
||||
def process_segmentation_pipeline(self, rgb_msg, depth_msg, objects,
|
||||
pub_bbox, pub_cloud, pub_markers, pub_pc_markers, source_name,
|
||||
target_list_class, target_item_class):
|
||||
if self.intrinsics is None:
|
||||
self.get_logger().warn(f"[{source_name}] Waiting for Camera Info...", throttle_duration_sec=2.0)
|
||||
@@ -102,12 +189,80 @@ class ObjectLocalizationNode(Node):
|
||||
return
|
||||
|
||||
try:
|
||||
t0 = time.perf_counter()
|
||||
|
||||
# --- STEP 0: LOOKUP TF TRANSFORM ---
|
||||
try:
|
||||
# Try exact timestamp lookup. Increase timeout to 1.5s for robustness under heavy load / sim time.
|
||||
transform = self.tf_buffer.lookup_transform(
|
||||
'map',
|
||||
depth_msg.header.frame_id,
|
||||
depth_msg.header.stamp,
|
||||
rclpy.duration.Duration(seconds=1.5)
|
||||
)
|
||||
except Exception as e:
|
||||
# Fallback: get the latest available transform in case of clock mismatch/delay
|
||||
try:
|
||||
transform = self.tf_buffer.lookup_transform(
|
||||
'map',
|
||||
depth_msg.header.frame_id,
|
||||
rclpy.time.Time()
|
||||
)
|
||||
|
||||
# Compute time difference between the requested stamp and the fallback stamp
|
||||
requested_time = depth_msg.header.stamp.sec + depth_msg.header.stamp.nanosec * 1e-9
|
||||
fallback_time = transform.header.stamp.sec + transform.header.stamp.nanosec * 1e-9
|
||||
time_diff = abs(requested_time - fallback_time)
|
||||
|
||||
# If the time difference is significant (e.g. > 0.15s), using this fallback transform
|
||||
# will cause severe misalignment when the robot is moving/turning.
|
||||
# We should log a warning and skip the frame to prevent map corruption.
|
||||
if time_diff > 0.40:
|
||||
self.get_logger().warn(
|
||||
f"[{source_name}] Exact TF lookup failed (Error: {e}). Fallback transform time difference is too large "
|
||||
f"({time_diff:.3f} s > 0.15 s). Skipping frame to prevent inaccurate bounding boxes.",
|
||||
throttle_duration_sec=2.0
|
||||
)
|
||||
return
|
||||
else:
|
||||
self.get_logger().info(
|
||||
f"[{source_name}] Exact TF lookup failed (Error: {e}). Using fallback transform (diff: {time_diff:.3f} s).",
|
||||
throttle_duration_sec=2.0
|
||||
)
|
||||
except Exception as fallback_err:
|
||||
self.get_logger().warn(
|
||||
f"[{source_name}] TF lookup from 'map' to '{depth_msg.header.frame_id}' failed: "
|
||||
f"Exact: {e} | Fallback: {fallback_err}",
|
||||
throttle_duration_sec=2.0
|
||||
)
|
||||
return
|
||||
|
||||
trans = transform.transform.translation
|
||||
rot = transform.transform.rotation
|
||||
translation = np.array([trans.x, trans.y, trans.z])
|
||||
rotation = np.array([rot.x, rot.y, rot.z, rot.w])
|
||||
|
||||
# --- STEP 1: PREPARE DATA ---
|
||||
cv_bgr = self.bridge.imgmsg_to_cv2(rgb_msg, desired_encoding='bgr8')
|
||||
cv_rgb = cv2.cvtColor(cv_bgr, cv2.COLOR_BGR2RGB)
|
||||
cv_depth = self.bridge.imgmsg_to_cv2(depth_msg, desired_encoding='passthrough')
|
||||
|
||||
# --- STEP 2: PREPARE BBOXES FOR SAM ---
|
||||
# --- PREPARE DEBUG VISUALIZATIONS ---
|
||||
segmented_bgr = cv_bgr.copy()
|
||||
colors = [
|
||||
(0, 0, 255), # Red
|
||||
(0, 255, 0), # Green
|
||||
(255, 0, 0), # Blue
|
||||
(0, 255, 255), # Yellow
|
||||
(255, 0, 255), # Magenta
|
||||
(255, 255, 0), # Cyan
|
||||
(0, 165, 255), # Orange
|
||||
(128, 0, 128), # Purple
|
||||
(0, 128, 128), # Teal
|
||||
(128, 128, 0) # Olive
|
||||
]
|
||||
|
||||
# --- STEP 2: PREPARE BBOXES FOR FASTSAM ---
|
||||
bboxes = []
|
||||
valid_obj_indices = []
|
||||
|
||||
@@ -123,62 +278,137 @@ class ObjectLocalizationNode(Node):
|
||||
if not bboxes:
|
||||
return
|
||||
|
||||
# --- STEP 3: RUN SAM PREDICTION ---
|
||||
# --- STEP 3: RUN FASTSAM PREDICTION ---
|
||||
t_inf_start = time.perf_counter()
|
||||
masks = self.sam.predict(cv_rgb, bboxes)
|
||||
t_inf_end = time.perf_counter()
|
||||
|
||||
# --- STEP 4: GEOMETRY PROCESSING ---
|
||||
bbox_list_msg = target_list_class()
|
||||
bbox_list_msg.header = rgb_msg.header
|
||||
bbox_list_msg.header.frame_id = "map"
|
||||
|
||||
marker_array_msg = MarkerArray()
|
||||
pc_marker_array_msg = MarkerArray()
|
||||
all_cloud_points = []
|
||||
|
||||
for i, mask in enumerate(masks):
|
||||
# A. Project & Filter
|
||||
points_cam = GeometryUtils.project_mask_to_3d(
|
||||
cv_depth, mask, self.intrinsics, self.depth_scale)
|
||||
for i, bbox in enumerate(bboxes):
|
||||
original_obj = objects[valid_obj_indices[i]]
|
||||
|
||||
# Refine mask: intersect it with the YOLO bounding box to prevent leakage
|
||||
refined_mask = None
|
||||
if i < len(masks) and masks[i] is not None:
|
||||
h, w = masks[i].shape
|
||||
x1, y1, x2, y2 = bbox
|
||||
ix1 = max(0, int(round(x1)))
|
||||
iy1 = max(0, int(round(y1)))
|
||||
ix2 = min(w, int(round(x2)))
|
||||
iy2 = min(h, int(round(y2)))
|
||||
|
||||
bbox_mask = np.zeros_like(masks[i], dtype=bool)
|
||||
bbox_mask[iy1:iy2, ix1:ix2] = True
|
||||
refined_mask = masks[i] & bbox_mask
|
||||
|
||||
# Debug annotation: draw mask, box, and class label
|
||||
color = colors[i % len(colors)]
|
||||
bx1, by1, bx2, by2 = int(bbox[0]), int(bbox[1]), int(bbox[2]), int(bbox[3])
|
||||
|
||||
# Overlay mask on segmented_bgr if available
|
||||
if refined_mask is not None:
|
||||
mask_overlay = np.zeros_like(segmented_bgr)
|
||||
mask_overlay[refined_mask] = color
|
||||
segmented_bgr = cv2.addWeighted(segmented_bgr, 1.0, mask_overlay, 0.4, 0)
|
||||
|
||||
cv2.rectangle(segmented_bgr, (bx1, by1), (bx2, by2), color, 2)
|
||||
|
||||
class_name_str = original_obj.class_name.data
|
||||
cv2.putText(segmented_bgr, class_name_str, (bx1, max(by1 - 10, 15)),
|
||||
cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
|
||||
|
||||
# Try to use FastSAM mask if available
|
||||
points_cam = None
|
||||
used_mask = False
|
||||
if refined_mask is not None:
|
||||
# A1. Project Mask to 3D
|
||||
points_cam = GeometryUtils.project_mask_to_3d(
|
||||
cv_depth, refined_mask, self.intrinsics, self.depth_scale)
|
||||
if points_cam is not None and len(points_cam) >= 10:
|
||||
used_mask = True
|
||||
|
||||
# Fallback to direct 2D bounding box cropping if mask projection is empty/fails
|
||||
if not used_mask:
|
||||
# A2. Project BBox to 3D
|
||||
points_cam = GeometryUtils.project_bbox_to_3d(
|
||||
cv_depth, bbox, self.intrinsics, self.depth_scale, shrink_ratio=0.15)
|
||||
|
||||
points_clean = GeometryUtils.clean_outliers(points_cam, std_ratio=1.5)
|
||||
|
||||
if len(points_clean) < 10:
|
||||
continue
|
||||
|
||||
# B. Transform to Map Frame
|
||||
points_map = GeometryUtils.transform_points_camera_to_map(
|
||||
points_clean, odom_msg.pose.pose)
|
||||
# --- FILTER BY DISTANCE ---
|
||||
# Compute centroid of points in camera frame to check physical distance from sensor
|
||||
centroid_cam = np.mean(points_clean, axis=0)
|
||||
distance = float(np.linalg.norm(centroid_cam))
|
||||
max_dist = self.get_parameter('max_object_distance').get_parameter_value().double_value
|
||||
if distance > max_dist:
|
||||
self.get_logger().info(
|
||||
f"[{source_name}] Skipping '{class_name_str}' (distance {distance:.2f} m > max {max_dist:.2f} m)",
|
||||
throttle_duration_sec=2.0
|
||||
)
|
||||
continue
|
||||
|
||||
# C. Compute 3D BBox
|
||||
bbox_data = GeometryUtils.compute_3d_bbox(points_map)
|
||||
# B. Transform to Map Frame
|
||||
points_map = GeometryUtils.transform_points(
|
||||
points_clean, translation, rotation)
|
||||
|
||||
# C. Compute 3D OBB
|
||||
bbox_data = GeometryUtils.compute_3d_obb(points_map)
|
||||
|
||||
if bbox_data is None:
|
||||
continue
|
||||
|
||||
# D. Pack Bounding Box
|
||||
original_obj = objects[valid_obj_indices[i]]
|
||||
bbox_msg = target_item_class()
|
||||
|
||||
bbox_msg.name = original_obj.class_name
|
||||
|
||||
# Handle 'graspable' field
|
||||
if isinstance(bbox_msg, Object3DBoundingBox):
|
||||
bbox_msg.graspable = original_obj.graspable
|
||||
|
||||
# Set bounding box coordinates
|
||||
p_min = Point32()
|
||||
p_min.x, p_min.y, p_min.z = [float(x) for x in bbox_data['min']]
|
||||
p_max = Point32()
|
||||
p_max.x, p_max.y, p_max.z = [float(x) for x in bbox_data['max']]
|
||||
# Set bounding box coordinates (8 corners of OBB)
|
||||
bbox_msg.bounding_box = [
|
||||
Point32(x=float(pt[0]), y=float(pt[1]), z=float(pt[2]))
|
||||
for pt in bbox_data['corners']
|
||||
]
|
||||
|
||||
# Generate PointCloud2 for this object
|
||||
pc_msg = PointCloud2()
|
||||
pc_msg.header.stamp = rgb_msg.header.stamp
|
||||
pc_msg.header.frame_id = "map"
|
||||
|
||||
bbox_msg.bounding_box = [p_min, p_max]
|
||||
if len(points_map) > 0:
|
||||
pc_msg = pc2.create_cloud_xyz32(pc_msg.header, points_map.astype(np.float32))
|
||||
|
||||
if hasattr(bbox_msg, 'point_cloud'):
|
||||
bbox_msg.point_cloud = pc_msg
|
||||
|
||||
bbox_list_msg.bbox.append(bbox_msg)
|
||||
|
||||
# ----------- LOGGER -----------
|
||||
class_name = original_obj.class_name.data
|
||||
min_s = f"({bbox_data['min'][0]:.2f}, {bbox_data['min'][1]:.2f}, {bbox_data['min'][2]:.2f})"
|
||||
max_s = f"({bbox_data['max'][0]:.2f}, {bbox_data['max'][1]:.2f}, {bbox_data['max'][2]:.2f})"
|
||||
pts_arr = np.array(bbox_data['corners'])
|
||||
min_pt = np.min(pts_arr, axis=0)
|
||||
max_pt = np.max(pts_arr, axis=0)
|
||||
min_s = f"({min_pt[0]:.2f}, {min_pt[1]:.2f}, {min_pt[2]:.2f})"
|
||||
max_s = f"({max_pt[0]:.2f}, {max_pt[1]:.2f}, {max_pt[2]:.2f})"
|
||||
|
||||
grasp_info = f" | Grasp: {bbox_msg.graspable}" if hasattr(bbox_msg, 'graspable') else ""
|
||||
|
||||
self.get_logger().info( f"[{source_name}] ID: {i} | Class: '{class_name}'{grasp_info} | Min: {min_s} | Max: {max_s}" )
|
||||
# Log whether it used mask or bbox fallback
|
||||
source_method = "Mask" if used_mask else "BBox-Fallback"
|
||||
|
||||
self.get_logger().info( f"[{source_name}] ID: {i} | Class: '{class_name}'{grasp_info} | Method: {source_method} | Min: {min_s} | Max: {max_s}" )
|
||||
# ------------------------------
|
||||
|
||||
# E. Cloud Accumulation
|
||||
@@ -187,8 +417,143 @@ class ObjectLocalizationNode(Node):
|
||||
points_with_id = np.hstack((points_map, class_col))
|
||||
all_cloud_points.append(points_with_id)
|
||||
|
||||
# F. Visualization Markers
|
||||
center_x, center_y, center_z = bbox_data['center']
|
||||
size_x, size_y, size_z = bbox_data['size']
|
||||
qx, qy, qz, qw = bbox_data['rotation']
|
||||
|
||||
# Cube Marker
|
||||
marker_cube = Marker()
|
||||
marker_cube.header.frame_id = "map"
|
||||
marker_cube.header.stamp = rgb_msg.header.stamp
|
||||
marker_cube.ns = "yolo_3d_cubes"
|
||||
marker_cube.id = i
|
||||
marker_cube.type = Marker.CUBE
|
||||
marker_cube.action = Marker.ADD
|
||||
marker_cube.lifetime = rclpy.duration.Duration(seconds=1.0).to_msg()
|
||||
|
||||
marker_cube.pose.position.x = float(center_x)
|
||||
marker_cube.pose.position.y = float(center_y)
|
||||
marker_cube.pose.position.z = float(center_z)
|
||||
|
||||
marker_cube.pose.orientation.x = float(qx)
|
||||
marker_cube.pose.orientation.y = float(qy)
|
||||
marker_cube.pose.orientation.z = float(qz)
|
||||
marker_cube.pose.orientation.w = float(qw)
|
||||
|
||||
marker_cube.scale.x = float(size_x)
|
||||
marker_cube.scale.y = float(size_y)
|
||||
marker_cube.scale.z = float(size_z)
|
||||
|
||||
marker_cube.color.r = 0.0
|
||||
marker_cube.color.g = 1.0
|
||||
marker_cube.color.b = 0.0
|
||||
marker_cube.color.a = 0.4
|
||||
|
||||
marker_array_msg.markers.append(marker_cube)
|
||||
|
||||
# Text Marker
|
||||
marker_text = Marker()
|
||||
marker_text.header.frame_id = "map"
|
||||
marker_text.header.stamp = rgb_msg.header.stamp
|
||||
marker_text.ns = "yolo_3d_labels"
|
||||
marker_text.id = i
|
||||
marker_text.type = Marker.TEXT_VIEW_FACING
|
||||
marker_text.action = Marker.ADD
|
||||
marker_text.lifetime = rclpy.duration.Duration(seconds=1.0).to_msg()
|
||||
|
||||
marker_text.pose.position.x = float(center_x)
|
||||
marker_text.pose.position.y = float(center_y)
|
||||
marker_text.pose.position.z = float(max_pt[2] + 0.15)
|
||||
|
||||
marker_text.pose.orientation.x = 0.0
|
||||
marker_text.pose.orientation.y = 0.0
|
||||
marker_text.pose.orientation.z = 0.0
|
||||
marker_text.pose.orientation.w = 1.0
|
||||
|
||||
marker_text.scale.z = 0.2
|
||||
|
||||
marker_text.color.r = 1.0
|
||||
marker_text.color.g = 1.0
|
||||
marker_text.color.b = 0.0
|
||||
marker_text.color.a = 1.0
|
||||
|
||||
marker_text.text = class_name
|
||||
|
||||
marker_array_msg.markers.append(marker_text)
|
||||
|
||||
# Point Cloud Marker
|
||||
if len(points_map) > 0:
|
||||
marker_pc = Marker()
|
||||
marker_pc.header.frame_id = "map"
|
||||
marker_pc.header.stamp = rgb_msg.header.stamp
|
||||
marker_pc.ns = "yolo_3d_pointclouds"
|
||||
marker_pc.id = i
|
||||
marker_pc.type = Marker.POINTS
|
||||
marker_pc.action = Marker.ADD
|
||||
marker_pc.lifetime = rclpy.duration.Duration(seconds=1.0).to_msg()
|
||||
|
||||
# Cyan color
|
||||
marker_pc.color.r = 0.0
|
||||
marker_pc.color.g = 1.0
|
||||
marker_pc.color.b = 1.0
|
||||
marker_pc.color.a = 0.8
|
||||
|
||||
marker_pc.scale.x = 0.02
|
||||
marker_pc.scale.y = 0.02
|
||||
|
||||
marker_pc.points = [Point(x=float(pt[0]), y=float(pt[1]), z=float(pt[2])) for pt in points_map]
|
||||
pc_marker_array_msg.markers.append(marker_pc)
|
||||
|
||||
# --- STEP 5: PUBLISH ---
|
||||
pub_bbox.publish(bbox_list_msg)
|
||||
pub_markers.publish(marker_array_msg)
|
||||
pub_pc_markers.publish(pc_marker_array_msg)
|
||||
|
||||
# Publish Debug Images
|
||||
try:
|
||||
# Color the depth image for debugging
|
||||
depth_copy = np.copy(cv_depth)
|
||||
if depth_copy.dtype == np.uint16:
|
||||
depth_float = depth_copy.astype(np.float32) * self.depth_scale
|
||||
else:
|
||||
depth_float = depth_copy.astype(np.float32)
|
||||
|
||||
# Clean NaNs and Infs
|
||||
depth_float[~np.isfinite(depth_float)] = 0.0
|
||||
|
||||
# Normalize to 0-255 using actual range
|
||||
max_val = np.max(depth_float)
|
||||
if max_val > 0.01:
|
||||
valid_depths = depth_float[depth_float > 0.01]
|
||||
if len(valid_depths) > 0:
|
||||
p99 = np.percentile(valid_depths, 99)
|
||||
max_dist = float(max(p99, 1.0))
|
||||
else:
|
||||
max_dist = 5.0
|
||||
depth_clipped = np.clip(depth_float, 0.0, max_dist)
|
||||
depth_norm = (depth_clipped / max_dist * 255.0).astype(np.uint8)
|
||||
else:
|
||||
depth_norm = np.zeros_like(depth_float, dtype=np.uint8)
|
||||
|
||||
# Apply jet colormap (invert to make close red and far blue)
|
||||
depth_colored = cv2.applyColorMap(255 - depth_norm, cv2.COLORMAP_JET)
|
||||
|
||||
# Make background black for zero/invalid depth values
|
||||
invalid_mask = (depth_float <= 0.01)
|
||||
depth_colored[invalid_mask] = (0, 0, 0)
|
||||
|
||||
# Convert to message and publish
|
||||
depth_colored_msg = self.bridge.cv2_to_imgmsg(depth_colored, encoding='bgr8')
|
||||
depth_colored_msg.header = depth_msg.header
|
||||
self.pub_debug_depth_colored.publish(depth_colored_msg)
|
||||
|
||||
# Convert segmented BGR to message and publish
|
||||
segmented_msg = self.bridge.cv2_to_imgmsg(segmented_bgr, encoding='bgr8')
|
||||
segmented_msg.header = rgb_msg.header
|
||||
self.pub_debug_segmented_rgb.publish(segmented_msg)
|
||||
except Exception as e:
|
||||
self.get_logger().error(f"Failed to publish debug images: {e}")
|
||||
|
||||
# Publish Point Cloud
|
||||
if all_cloud_points:
|
||||
@@ -206,6 +571,16 @@ class ObjectLocalizationNode(Node):
|
||||
], final_cloud)
|
||||
pub_cloud.publish(pc_msg)
|
||||
|
||||
t_end = time.perf_counter()
|
||||
total_duration_ms = (t_end - t0) * 1000
|
||||
inference_duration_ms = (t_inf_end - t_inf_start) * 1000
|
||||
geometry_duration_ms = total_duration_ms - inference_duration_ms
|
||||
|
||||
self.get_logger().info(
|
||||
f"[{source_name}] FastSAM Latency: {inference_duration_ms:.2f} ms | "
|
||||
f"Geometry/Total: {geometry_duration_ms:.2f}/{total_duration_ms:.2f} ms"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
self.get_logger().error(f"[{source_name}] Pipeline Error: {e}")
|
||||
import traceback
|
||||
@@ -214,13 +589,16 @@ class ObjectLocalizationNode(Node):
|
||||
def main(args=None):
|
||||
rclpy.init(args=args)
|
||||
node = ObjectLocalizationNode()
|
||||
executor = MultiThreadedExecutor()
|
||||
executor.add_node(node)
|
||||
try:
|
||||
rclpy.spin(node)
|
||||
executor.spin()
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
finally:
|
||||
node.destroy_node()
|
||||
rclpy.shutdown()
|
||||
if rclpy.ok():
|
||||
rclpy.shutdown()
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -1,21 +1,24 @@
|
||||
import torch
|
||||
from ultralytics import SAM
|
||||
from ultralytics import SAM, FastSAM
|
||||
|
||||
class SamWrapper:
|
||||
"""Wrapper for Ultralytics SAM2 (Segment Anything Model 2) to handle prompted segmentation via bounding boxes."""
|
||||
"""Wrapper for Ultralytics SAM/SAM2/FastSAM to handle prompted segmentation via bounding boxes."""
|
||||
|
||||
def __init__(self, model_name):
|
||||
"""
|
||||
Initializes SAM2 model.
|
||||
Initializes segmenter model.
|
||||
|
||||
Args:
|
||||
model_name (str): 'sam2_b.pt' (base), 'sam2_t.pt' (tiny), or 'sam2_l.pt' (large).
|
||||
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:
|
||||
self.model = SAM(model_name)
|
||||
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:
|
||||
@@ -32,16 +35,46 @@ class SamWrapper:
|
||||
results = self.model(image, bboxes=bboxes, verbose=False)
|
||||
except Exception as e:
|
||||
print(f"[SamWrapper] Inference failed: {e}")
|
||||
return []
|
||||
return [None] * len(bboxes)
|
||||
|
||||
if not results or results[0].masks is None:
|
||||
return []
|
||||
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()
|
||||
masks_np = masks_tensor.cpu().numpy().astype(bool)
|
||||
|
||||
# Convert to boolean masks
|
||||
masks_bool = masks_np.astype(bool)
|
||||
# Get bounding boxes corresponding to the detected masks
|
||||
detected_boxes = results[0].boxes.xyxy.cpu().numpy()
|
||||
|
||||
return [mask for mask in masks_bool]
|
||||
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
|
||||
@@ -1,206 +1,538 @@
|
||||
#!/usr/bin/env python
|
||||
#!/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 nav_msgs.msg import Odometry
|
||||
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
|
||||
super().__init__('odom_vizualization_node')
|
||||
# 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)]
|
||||
)
|
||||
|
||||
# Initialize storage for robot pose
|
||||
self.latest_odom = None
|
||||
# ----------------------------------------------------------------------
|
||||
# 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 = []
|
||||
|
||||
# Subscribe to robot odometry for pose information
|
||||
self.odom_sub = self.create_subscription(Odometry, '/scene_graph/sync/odom', self.odom_callback, 10)
|
||||
# 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)
|
||||
|
||||
# Create publisher for robot pose visualization
|
||||
# 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)
|
||||
|
||||
# Initialize trajectory tracking variables
|
||||
self.trajectory_points = []
|
||||
self.max_trajectory_points = 1000 # Limit trajectory history to prevent memory overflow
|
||||
# Log node initialization status
|
||||
self.get_logger().info('Odom/SLAM Pose, Loop Closure, and TF Static Filter Node initialized')
|
||||
|
||||
self.get_logger().info('Odom Visualization Node initialized')
|
||||
# pose_callback removed in favor of viz_timer_callback for high frequency visualization
|
||||
|
||||
def odom_callback(self, msg):
|
||||
def info_callback(self, msg):
|
||||
"""
|
||||
Callback for robot odometry data.
|
||||
Callback triggered when new SLAM info/statistics are published by RTAB-Map.
|
||||
|
||||
Stores the latest robot pose and creates visualization markers showing:
|
||||
1. An arrow indicating position and orientation
|
||||
2. A sphere at the robot's position
|
||||
3. A line strip showing the robot's trajectory
|
||||
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 (nav_msgs/Odometry): Robot odometry containing pose and velocity
|
||||
msg (rtabmap_msgs.msg.Info): RTAB-Map status info containing statistics.
|
||||
"""
|
||||
# Store the latest odometry message
|
||||
self.latest_odom = msg
|
||||
# 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"
|
||||
)
|
||||
|
||||
# Create a marker array to hold multiple visualization markers
|
||||
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()
|
||||
|
||||
# 1. Create arrow marker for robot pose (shows both position and orientation)
|
||||
arrow_marker = self.create_pose_arrow(msg)
|
||||
marker_array.markers.append(arrow_marker)
|
||||
|
||||
# 2. Create sphere marker for position only (easier to see than arrow tip)
|
||||
position_marker = self.create_position_sphere(msg)
|
||||
marker_array.markers.append(position_marker)
|
||||
|
||||
# 3. Create and update trajectory line showing robot's path history
|
||||
self.trajectory_points.append(msg.pose.pose.position)
|
||||
|
||||
# Remove oldest point if trajectory exceeds maximum length
|
||||
if len(self.trajectory_points) > self.max_trajectory_points:
|
||||
self.trajectory_points.pop(0)
|
||||
# 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 all visualization markers
|
||||
|
||||
# Publish the updated trajectory to RViz
|
||||
self.pose_marker_pub.publish(marker_array)
|
||||
|
||||
def create_pose_arrow(self, odom_msg):
|
||||
def tf_callback(self, msg):
|
||||
"""
|
||||
Create an ARROW marker showing robot's position and orientation.
|
||||
Callback triggered when a transform message is received on '/tf_old'.
|
||||
|
||||
The arrow points in the direction the robot is facing, providing
|
||||
visual feedback on both location and heading.
|
||||
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:
|
||||
odom_msg (nav_msgs/Odometry): Odometry message with pose information
|
||||
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)
|
||||
|
||||
Returns:
|
||||
visualization_msgs/Marker: Arrow marker for RViz
|
||||
# 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 = odom_msg.header
|
||||
|
||||
# FIXME: use position from SLAM instead of raw odometry
|
||||
marker.header = header
|
||||
marker.header.frame_id = "map"
|
||||
marker.ns = "robot_pose" # Namespace for grouping markers
|
||||
marker.id = 0 # Unique ID within namespace
|
||||
marker.ns = "robot_pose"
|
||||
marker.id = 0
|
||||
marker.type = Marker.ARROW
|
||||
marker.action = Marker.ADD
|
||||
|
||||
# Set pose from odometry (position and orientation)
|
||||
marker.pose = odom_msg.pose.pose
|
||||
marker.pose.position.x = translation.x
|
||||
marker.pose.position.y = translation.y
|
||||
marker.pose.position.z = translation.z
|
||||
marker.pose.orientation = rotation
|
||||
|
||||
# Arrow dimensions (length, width, height)
|
||||
marker.scale.x = 0.5 # Arrow length (0.5 meters)
|
||||
marker.scale.y = 0.05 # Arrow shaft width
|
||||
marker.scale.z = 0.05 # Arrow shaft height
|
||||
marker.scale.x = 0.5 # Shaft/total length
|
||||
marker.scale.y = 0.05 # Shaft width
|
||||
marker.scale.z = 0.05 # Shaft height
|
||||
|
||||
# Color (Red arrow for visibility)
|
||||
marker.color.r = 1.0
|
||||
marker.color.g = 0.0
|
||||
marker.color.b = 0.0
|
||||
marker.color.a = 1.0 # Fully opaque
|
||||
marker.color.a = 1.0
|
||||
|
||||
# Persistent marker (lifetime=0 means it stays until deleted)
|
||||
marker.lifetime = rclpy.duration.Duration(seconds=0).to_msg()
|
||||
|
||||
return marker
|
||||
|
||||
|
||||
def create_position_sphere(self, odom_msg):
|
||||
def create_position_sphere(self, header, translation):
|
||||
"""
|
||||
Create a SPHERE marker at the robot's position.
|
||||
|
||||
This provides an easy-to-see indicator of the robot's current location,
|
||||
complementing the arrow marker.
|
||||
|
||||
Args:
|
||||
odom_msg (nav_msgs/Odometry): Odometry message with pose information
|
||||
|
||||
Returns:
|
||||
visualization_msgs/Marker: Sphere marker for RViz
|
||||
Constructs a semi-transparent green Sphere Marker representing the robot's current position.
|
||||
"""
|
||||
marker = Marker()
|
||||
marker.header = odom_msg.header
|
||||
# FIXME: use position from SLAM instead of raw odometry
|
||||
marker.header = header
|
||||
marker.header.frame_id = "map"
|
||||
marker.ns = "robot_position"
|
||||
marker.id = 1 # Different ID from arrow marker
|
||||
marker.id = 1
|
||||
marker.type = Marker.SPHERE
|
||||
marker.action = Marker.ADD
|
||||
|
||||
# Set position only (orientation doesn't matter for a sphere)
|
||||
marker.pose.position = odom_msg.pose.pose.position
|
||||
marker.pose.orientation.w = 1.0 # Identity quaternion
|
||||
marker.pose.position.x = translation.x
|
||||
marker.pose.position.y = translation.y
|
||||
marker.pose.position.z = translation.z
|
||||
marker.pose.orientation.w = 1.0
|
||||
|
||||
# Sphere size (0.2m diameter)
|
||||
marker.scale.x = 0.2
|
||||
marker.scale.y = 0.2
|
||||
marker.scale.z = 0.2
|
||||
|
||||
# Color (Green sphere)
|
||||
marker.color.r = 0.0
|
||||
marker.color.g = 1.0
|
||||
marker.color.b = 0.0
|
||||
marker.color.a = 0.8 # Semi-transparent
|
||||
marker.color.a = 0.8
|
||||
|
||||
marker.lifetime = rclpy.duration.Duration(seconds=0).to_msg()
|
||||
|
||||
return marker
|
||||
|
||||
|
||||
def create_trajectory(self, frame_id):
|
||||
"""
|
||||
Create a LINE_STRIP marker showing the robot's path history.
|
||||
|
||||
This visualizes where the robot has been by connecting all previous
|
||||
position points with a continuous line.
|
||||
Constructs a Line Strip Marker connecting the historical points of the robot's path.
|
||||
|
||||
Args:
|
||||
frame_id (str): Reference frame for the marker
|
||||
frame_id (str): The coordinate frame ID (typically "map") in which points are defined.
|
||||
|
||||
Returns:
|
||||
visualization_msgs/Marker: Line strip marker for RViz
|
||||
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 # Different ID from pose markers
|
||||
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 width
|
||||
# Line thickness: scale.x defines the width of the line segment in meters
|
||||
marker.scale.x = 0.02
|
||||
|
||||
# Color (Blue trajectory)
|
||||
# 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
|
||||
|
||||
# Add all stored trajectory points to the line
|
||||
# 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 the ROS2 node.
|
||||
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()
|
||||
rclpy.shutdown()
|
||||
# Shutdown ROS2 context safely
|
||||
if rclpy.ok():
|
||||
rclpy.shutdown()
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1 @@
|
||||
# Initialize room_classification package
|
||||
@@ -0,0 +1,151 @@
|
||||
def get_filtered_mpcat40_list():
|
||||
data = """
|
||||
mpcat40index mpcat40 hex wnsynsetkey nyu40 skip labels
|
||||
0 void #ffffff void remove,void
|
||||
1 wall #aec7e8 wall.n.01,baseboard.n.01,paneling.n.01 wall wallpaper
|
||||
2 floor #708090 floor.n.01,rug.n.01,mat.n.01,bath_mat.n.01,landing.n.01 floor,floor mat
|
||||
3 chair #98df8a chair.n.01,beanbag.n.01 chair
|
||||
4 door #c5b0d5 door.n.01,doorframe.n.01,doorway.n.01,doorknob.n.01,archway.n.01 door garage door
|
||||
5 table #ff7f0e table.n.02,dressing.n.04 table,desk counter.n.01
|
||||
6 picture #d62728 picture.n.01,photograph.n.01,picture_frame.n.01 picture
|
||||
7 cabinet #1f77b4 cabinet.n.01,cupboard.n.01 cabinet
|
||||
8 cushion #bcbd22 cushion.n.03 pillow couch cushion
|
||||
9 window #ff9896 window.n.01,windowsill.n.01,window_frame.n.01,windowpane.n.02,window_screen.n.01 window
|
||||
10 sofa #2ca02c sofa.n.01 sofa
|
||||
11 bed #e377c2 bed.n.01,bedpost.n.01,bedstead.n.01,headboard.n.01,footboard.n.01,bedspread.n.01,mattress.n.01,sheet.n.03 bed
|
||||
12 curtain #de9ed6 curtain.n.01 curtain,shower curtain curtain rod,shower curtain rod,shower rod
|
||||
13 chest_of_drawers #9467bd chest_of_drawers.n.01,drawer.n.01 dresser,night stand
|
||||
14 plant #8ca252 plant.n.02
|
||||
15 sink #843c39 sink.n.01 sink
|
||||
16 stairs #9edae5 step.n.04,stairway.n.01,stairwell.n.01
|
||||
17 ceiling #9c9ede ceiling.n.01,roof.n.01 ceiling
|
||||
18 toilet #e7969c toilet.n.01,bidet.n.01 toilet
|
||||
19 stool #637939 stool.n.01
|
||||
20 towel #8c564b towel.n.01 towel
|
||||
21 mirror #dbdb8d mirror.n.01 mirror
|
||||
22 tv_monitor #d6616b display.n.06 television
|
||||
23 shower #cedb9c shower.n.01,showerhead.n.01
|
||||
24 column #e7ba52 column.n.07,post.n.04
|
||||
25 bathtub #393b79 bathtub.n.01 bathtub
|
||||
26 counter #a55194 countertop.n.01,counter.n.01,kitchen_island.n.01 counter
|
||||
27 fireplace #ad494a fireplace.n.01,mantel.n.01
|
||||
28 lighting #b5cf6b lamp.n.02,lampshade.n.01,light.n.02,chandelier.n.01,spotlight.n.02 lamp
|
||||
29 beam #5254a3 beam.n.02
|
||||
30 railing #bd9e39 railing.n.01,bannister.n.02
|
||||
31 shelving #c49c94 bookshelf.n.01,shelf.n.01,rack.n.05 shelves
|
||||
32 blinds #f7b6d2 window_blind.n.01 blinds
|
||||
33 gym_equipment #6b6ecf sports_equipment.n.01,treadmill.n.01,exercise_bike.n.01
|
||||
34 seating #ffbb78 bench.n.01,seat.n.03
|
||||
35 board_panel #c7c7c7 panel.n.01 whiteboard board
|
||||
36 furniture #8c6d31 furniture.n.01 otherfurniture
|
||||
37 appliances #e7cb94 home_appliance.n.01,stove.n.02,dryer.n.01 refridgerator washing machine and dryer
|
||||
38 clothes #ce6dbd clothing.n.01 clothes
|
||||
39 objects #17becf physical_object.n.01,material.n.01 books,paper,box,bag,otherprop structure.n.01,way.n.06,vent.n.01,unknown.n.01,pool.n.01
|
||||
40 misc #7f7f7f person,otherstructure unknown.n.01
|
||||
41 unlabeled #000000 unknown.n.01 unknown
|
||||
"""
|
||||
|
||||
lines = data.strip().split('\n')
|
||||
return [line.split('\t')[1] for line in lines[1:]]
|
||||
|
||||
room_classes = [
|
||||
['a', 'bathroom'], # (should have a toilet and a sink)
|
||||
['b', 'bedroom'],
|
||||
['c', 'closet'],
|
||||
['d', 'dining room'], # (includes “breakfast rooms” other rooms people mainly eat in)
|
||||
['e', 'entryway/foyer/lobby'], # (should be the front door, not any door)
|
||||
['f', 'familyroom'], # (should be a room that a family hangs out in, not any area with couches)
|
||||
['g', 'garage'],
|
||||
['h', 'hallway'],
|
||||
['i', 'library'], # (should be room like a library at a university, not an individual study)
|
||||
['j', 'laundryroom/mudroom'], # (place where people do laundry, etc.)
|
||||
['k', 'kitchen'],
|
||||
['l', 'living room'], # (should be the main “showcase” living room in a house, not any area with couches)
|
||||
['m', 'meetingroom/conferenceroom'],
|
||||
['n', 'lounge'], # (any area where people relax in comfy chairs/couches that is not the family room or living room
|
||||
['o', 'office'], # (usually for an individual, or a small set of people)
|
||||
['p', 'porch/terrace/deck/driveway'], # (must be outdoors on ground level)
|
||||
['r', 'rec/game'], # (should have recreational objects, like pool table, etc.)
|
||||
['s', 'stairs'],
|
||||
['t', 'toilet'], # (should be a small room with ONLY a toilet)
|
||||
['u', 'utilityroom/toolroom'],
|
||||
['v', 'tv'], # (must have theater-style seating)
|
||||
['w', 'workout/gym/exercise'],
|
||||
['x', 'outdoor areas'], # containing grass, plants, bushes, trees, etc.
|
||||
['y', 'balcony'], # (must be outside and must not be on ground floor)
|
||||
['z', 'other room'], # (it is clearly a room, but the function is not clear)
|
||||
['B', 'bar'],
|
||||
['C', 'classroom'],
|
||||
['D', 'dining booth'],
|
||||
['S', 'spa/sauna'],
|
||||
['Z', 'junk'], # (reflections of mirrors, random points floating in space, etc.)
|
||||
['-', 'no label']
|
||||
]
|
||||
|
||||
room_label_blacklist = ['utilityroom/toolroom', 'tv', 'toilet', 'stairs', 'spa/sauna', 'rec/game', 'outdoor areas', 'other room', 'library', 'junk', 'bar', 'garage', 'classroom',
|
||||
'entryway/foyer/lobby', 'familyroom', 'balcony', 'laundryroom/mudroom', 'meetingroom/conferenceroom', 'workout/gym/exercise', 'dining booth', 'porch/terrace/deck/driveway', 'lounge']
|
||||
object_label_blacklist = ['void', 'wall', 'floor', 'objects', 'misc', 'unlabeled']
|
||||
|
||||
room_label_blacklist_ = [
|
||||
'closet',
|
||||
'dining room', # (includes “breakfast rooms” other rooms people mainly eat in)
|
||||
'entryway/foyer/lobby', # (should be the front door, not any door)
|
||||
'familyroom', # (should be a room that a family hangs out in, not any area with couches)
|
||||
'garage',
|
||||
'library', # (should be room like a library at a university, not an individual study)
|
||||
'laundryroom/mudroom', # (place where people do laundry, etc.)
|
||||
'kitchen',
|
||||
'living room', # (should be the main “showcase” living room in a house, not any area with couches)
|
||||
'meetingroom/conferenceroom',
|
||||
'lounge', # (any area where people relax in comfy chairs/couches that is not the family room or living room
|
||||
'office', # (usually for an individual, or a small set of people)
|
||||
'porch/terrace/deck/driveway', # (must be outdoors on ground level)
|
||||
'rec/game', # (should have recreational objects, like pool table, etc.)
|
||||
'stairs',
|
||||
'toilet', # (should be a small room with ONLY a toilet)
|
||||
'utilityroom/toolroom',
|
||||
'tv', # (must have theater-style seating)
|
||||
'workout/gym/exercise',
|
||||
'outdoor areas', # containing grass, plants, bushes, trees, etc.
|
||||
'balcony', # (must be outside and must not be on ground floor)
|
||||
'other room', # (it is clearly a room, but the function is not clear)
|
||||
'bar',
|
||||
'classroom',
|
||||
'dining booth',
|
||||
'spa/sauna',
|
||||
'junk', # (reflections of mirrors, random points floating in space, etc.)
|
||||
'no label'
|
||||
]
|
||||
|
||||
mpcat40_mapping = [
|
||||
['tv', 'tv_monitor'],
|
||||
['potted plant', 'plant'],
|
||||
['couch', 'sofa'],
|
||||
['bottle'],
|
||||
['mouse'],
|
||||
['laptop'],
|
||||
['cup'],
|
||||
['book'],
|
||||
['remote'],
|
||||
['handbag', 'clothes'],
|
||||
['dining table', 'table'],
|
||||
['keyboard'],
|
||||
['scissors'],
|
||||
['refrigerator', 'appliances']
|
||||
]
|
||||
|
||||
|
||||
def object_is_in_mpcat40(detected_object):
|
||||
|
||||
for i in mpcat40_mapping:
|
||||
if detected_object == i[0]:
|
||||
if len(i) > 1:
|
||||
detected_object = i[1]
|
||||
|
||||
mpcat40_list = get_filtered_mpcat40_list()
|
||||
|
||||
for i in range(len(mpcat40_list)):
|
||||
if mpcat40_list[i] == detected_object:
|
||||
return i
|
||||
|
||||
return -1
|
||||
Binary file not shown.
@@ -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
@@ -14,6 +14,12 @@ setup(
|
||||
('share/' + package_name, ['package.xml']),
|
||||
(os.path.join('share', package_name, 'launch'),
|
||||
glob('launch/*.py')),
|
||||
(os.path.join('share', package_name, 'meshes', 'panther'),
|
||||
glob('meshes/panther/*')),
|
||||
(os.path.join('share', package_name, 'meshes', 'WH01'),
|
||||
glob('meshes/WH01/*')),
|
||||
(os.path.join('share', package_name, 'model'),
|
||||
['scene_graph_room_classification/room_classification/rf_classifier.pkl']),
|
||||
],
|
||||
install_requires=['setuptools', 'open3d', 'shapely', "huggingface_hub"],
|
||||
zip_safe=True,
|
||||
@@ -31,7 +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'
|
||||
'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'
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
@@ -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)
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
|
||||
Reference in New Issue
Block a user