11 changed files with 1328 additions and 344 deletions
+2 -1
View File
@@ -5,4 +5,5 @@ pipeline.png
/build/
/install/
/log/
~/.cache
~/.cache
.vscode/
+86
View File
@@ -0,0 +1,86 @@
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=[]
)
return LaunchDescription([
rtabmap_slam,
object_detection_node,
object_localization_node,
scene_graph_fusion_node,
odom_vizualization_node
])
+4
View File
@@ -19,6 +19,10 @@
<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 -->
@@ -1,33 +1,31 @@
#!/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
# 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')
@@ -36,12 +34,10 @@ class ObjectDetectionNode(Node):
# 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 +45,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 +94,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 +102,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,12 +124,6 @@ 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()
@@ -194,13 +142,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 +200,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 +210,6 @@ class ObjectDetectionNode(Node):
object_details.append({
'class': class_name,
'confidence': confidence,
'graspable': is_graspable,
'bbox': (x1, y1, x2, y2)
})
@@ -282,7 +219,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 +234,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 +252,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):
@@ -9,8 +9,34 @@ Structure: Each entry is (label_name, is_graspable)
# Vocabulary with graspability affordances
# Format: (label_name: str, is_graspable: bool)
# added 58 more classed to the dictionary
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 +46,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,8 @@
import numpy as np
import math
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 +23,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 +38,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):
@@ -100,4 +243,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
@@ -6,12 +6,15 @@ 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
from tf2_ros import Buffer, TransformListener
from visualization_msgs.msg import Marker, MarkerArray
from .sam_wrapper import SamWrapper
from .geometry_utils import GeometryUtils
@@ -21,17 +24,19 @@ class ObjectLocalizationNode(Node):
super().__init__('object_localization_node')
# --- 1. CONFIGURATION ---
model_name = 'sam2_b.pt'
model_name = 'FastSAM-s.pt'
self.depth_scale = 0.001
# --- 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()
self.tf_listener = TransformListener(self.tf_buffer, self)
# --- 4. SUBSCRIBERS ---
# A. Camera Intrinsics
@@ -41,31 +46,22 @@ class ObjectLocalizationNode(Node):
# B. Base Synchronized Inputs
self.sub_rgb = message_filters.Subscriber(self, Image, '/scene_graph/sync/color/image_raw')
self.sub_depth = message_filters.Subscriber(self, Image, '/scene_graph/sync/depth/image_raw')
self.sub_odom = message_filters.Subscriber(self, Odometry, '/scene_graph/sync/odom')
# C. Object Detection Inputs
self.sub_yolo = message_filters.Subscriber(self, ObjectList, '/scene_graph/yolo')
self.sub_rtdetr = message_filters.Subscriber(self, FunObjectList, '/scene_graph/rtdetr')
# --- 5. SYNCHRONIZERS ---
# Chain 1: RGB + Depth + Odom + YOLO
# Chain 1: RGB + Depth + YOLO
self.ts_yolo = message_filters.ApproximateTimeSynchronizer(
[self.sub_rgb, self.sub_depth, self.sub_odom, self.sub_yolo],
[self.sub_rgb, self.sub_depth, self.sub_yolo],
queue_size=10, slop=0.1)
self.ts_yolo.registerCallback(self.yolo_callback)
# Chain 2: RGB + Depth + Odom + RT-DETR
self.ts_rtdetr = message_filters.ApproximateTimeSynchronizer(
[self.sub_rgb, self.sub_depth, self.sub_odom, self.sub_rtdetr],
queue_size=10, slop=0.1)
self.ts_rtdetr.registerCallback(self.rtdetr_callback)
# --- 6. PUBLISHERS ---
self.pub_bbox_yolo = self.create_publisher(Object3DBoundingBoxList, '/bounding_boxes_3d/yolo', 10)
self.pub_cloud_yolo = self.create_publisher(PointCloud2, '/object_clouds/yolo', 10)
self.pub_bbox_rtdetr = self.create_publisher(FunObject3DBoundingBoxList, '/bounding_boxes_3d/rtdetr', 10)
self.pub_cloud_rtdetr = self.create_publisher(PointCloud2, '/object_clouds/rtdetr', 10)
self.pub_markers_yolo = self.create_publisher(MarkerArray, '/scene_graph/viz/current_bounding_boxes_3d', 10)
self.pub_pc_markers_yolo = self.create_publisher(MarkerArray, '/bounding_boxes_3d/point_cloud_markers', 10)
self.get_logger().info("Object Localization Node Initialized. Waiting for data...")
@@ -77,22 +73,15 @@ 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):
def yolo_callback(self, rgb_msg, depth_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",
rgb_msg, depth_msg, objects,
self.pub_bbox_yolo, self.pub_cloud_yolo, self.pub_markers_yolo, self.pub_pc_markers_yolo, source_name="YOLO",
target_list_class=Object3DBoundingBoxList, target_item_class=Object3DBoundingBox)
def rtdetr_callback(self, rgb_msg, depth_msg, odom_msg, rtdetr_objs_msg):
objects = rtdetr_objs_msg.fun_objects
self.process_segmentation_pipeline(
rgb_msg, depth_msg, odom_msg, objects,
self.pub_bbox_rtdetr, self.pub_cloud_rtdetr, source_name="RT-DETR",
target_list_class=FunObject3DBoundingBoxList, target_item_class=FunObject3DBoundingBox)
def process_segmentation_pipeline(self, rgb_msg, depth_msg, odom_msg, objects,
pub_bbox, pub_cloud, source_name,
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 +91,44 @@ class ObjectLocalizationNode(Node):
return
try:
t0 = time.perf_counter()
# --- STEP 0: LOOKUP TF TRANSFORM ---
try:
# Try exact timestamp lookup
transform = self.tf_buffer.lookup_transform(
'map',
depth_msg.header.frame_id,
depth_msg.header.stamp,
rclpy.duration.Duration(seconds=0.1)
)
except Exception as e:
# Fallback: get the latest available transform in case of clock mismatch
try:
transform = self.tf_buffer.lookup_transform(
'map',
depth_msg.header.frame_id,
rclpy.time.Time()
)
except Exception as fallback_err:
self.get_logger().warn(
f"[{source_name}] TF lookup from 'map' to '{depth_msg.header.frame_id}' failed: "
f"Exact: {e} | Fallback: {fallback_err}",
throttle_duration_sec=2.0
)
return
trans = transform.transform.translation
rot = transform.transform.rotation
translation = np.array([trans.x, trans.y, trans.z])
rotation = np.array([rot.x, rot.y, rot.z, rot.w])
# --- STEP 1: PREPARE DATA ---
cv_bgr = self.bridge.imgmsg_to_cv2(rgb_msg, desired_encoding='bgr8')
cv_rgb = cv2.cvtColor(cv_bgr, cv2.COLOR_BGR2RGB)
cv_depth = self.bridge.imgmsg_to_cv2(depth_msg, desired_encoding='passthrough')
# --- STEP 2: PREPARE BBOXES FOR SAM ---
# --- STEP 2: PREPARE BBOXES FOR FASTSAM ---
bboxes = []
valid_obj_indices = []
@@ -123,28 +144,44 @@ 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]]
# Try to use FastSAM mask if available
points_cam = None
if i < len(masks) and masks[i] is not None:
# A1. Project Mask to 3D
points_cam = GeometryUtils.project_mask_to_3d(
cv_depth, masks[i], self.intrinsics, self.depth_scale)
# Fallback to direct 2D bounding box cropping if mask projection is empty/fails
if points_cam is None or len(points_cam) < 10:
# A2. Project BBox to 3D
points_cam = GeometryUtils.project_bbox_to_3d(
cv_depth, bbox, self.intrinsics, self.depth_scale, shrink_ratio=0.15)
points_clean = GeometryUtils.clean_outliers(points_cam, std_ratio=1.5)
if len(points_clean) < 10:
continue
# B. Transform to Map Frame
points_map = GeometryUtils.transform_points_camera_to_map(
points_clean, odom_msg.pose.pose)
points_map = GeometryUtils.transform_points(
points_clean, translation, rotation)
# C. Compute 3D BBox
bbox_data = GeometryUtils.compute_3d_bbox(points_map)
@@ -153,9 +190,7 @@ class ObjectLocalizationNode(Node):
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
@@ -169,6 +204,18 @@ class ObjectLocalizationNode(Node):
p_max.x, p_max.y, p_max.z = [float(x) for x in bbox_data['max']]
bbox_msg.bounding_box = [p_min, p_max]
# Generate PointCloud2 for this object
pc_msg = PointCloud2()
pc_msg.header.stamp = rgb_msg.header.stamp
pc_msg.header.frame_id = "map"
if len(points_map) > 0:
pc_msg = pc2.create_cloud_xyz32(pc_msg.header, points_map.astype(np.float32))
if hasattr(bbox_msg, 'point_cloud'):
bbox_msg.point_cloud = pc_msg
bbox_list_msg.bbox.append(bbox_msg)
# ----------- LOGGER -----------
@@ -178,7 +225,10 @@ class ObjectLocalizationNode(Node):
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 (i < len(masks) and masks[i] is not None and len(points_cam) >= 10) else "BBox-Fallback"
self.get_logger().info( f"[{source_name}] ID: {i} | Class: '{class_name}'{grasp_info} | Method: {source_method} | Min: {min_s} | Max: {max_s}" )
# ------------------------------
# E. Cloud Accumulation
@@ -187,8 +237,103 @@ class ObjectLocalizationNode(Node):
points_with_id = np.hstack((points_map, class_col))
all_cloud_points.append(points_with_id)
# F. Visualization Markers
min_pt = bbox_data['min']
max_pt = bbox_data['max']
center_x = (min_pt[0] + max_pt[0]) / 2.0
center_y = (min_pt[1] + max_pt[1]) / 2.0
center_z = (min_pt[2] + max_pt[2]) / 2.0
size_x = abs(max_pt[0] - min_pt[0])
size_y = abs(max_pt[1] - min_pt[1])
size_z = abs(max_pt[2] - min_pt[2])
# Cube Marker
marker_cube = Marker()
marker_cube.header.frame_id = "map"
marker_cube.header.stamp = rgb_msg.header.stamp
marker_cube.ns = "yolo_3d_cubes"
marker_cube.id = i
marker_cube.type = Marker.CUBE
marker_cube.action = Marker.ADD
marker_cube.lifetime = rclpy.duration.Duration(seconds=1.0).to_msg()
marker_cube.pose.position.x = float(center_x)
marker_cube.pose.position.y = float(center_y)
marker_cube.pose.position.z = float(center_z)
marker_cube.pose.orientation.x = 0.0
marker_cube.pose.orientation.y = 0.0
marker_cube.pose.orientation.z = 0.0
marker_cube.pose.orientation.w = 1.0
marker_cube.scale.x = float(size_x)
marker_cube.scale.y = float(size_y)
marker_cube.scale.z = float(size_z)
marker_cube.color.r = 0.0
marker_cube.color.g = 1.0
marker_cube.color.b = 0.0
marker_cube.color.a = 0.4
marker_array_msg.markers.append(marker_cube)
# Text Marker
marker_text = Marker()
marker_text.header.frame_id = "map"
marker_text.header.stamp = rgb_msg.header.stamp
marker_text.ns = "yolo_3d_labels"
marker_text.id = i
marker_text.type = Marker.TEXT_VIEW_FACING
marker_text.action = Marker.ADD
marker_text.lifetime = rclpy.duration.Duration(seconds=1.0).to_msg()
marker_text.pose.position.x = float(center_x)
marker_text.pose.position.y = float(center_y)
marker_text.pose.position.z = float(max_pt[2] + 0.15)
marker_text.pose.orientation.x = 0.0
marker_text.pose.orientation.y = 0.0
marker_text.pose.orientation.z = 0.0
marker_text.pose.orientation.w = 1.0
marker_text.scale.z = 0.2
marker_text.color.r = 1.0
marker_text.color.g = 1.0
marker_text.color.b = 0.0
marker_text.color.a = 1.0
marker_text.text = class_name
marker_array_msg.markers.append(marker_text)
# Point Cloud Marker
if len(points_map) > 0:
marker_pc = Marker()
marker_pc.header.frame_id = "map"
marker_pc.header.stamp = rgb_msg.header.stamp
marker_pc.ns = "yolo_3d_pointclouds"
marker_pc.id = i
marker_pc.type = Marker.POINTS
marker_pc.action = Marker.ADD
marker_pc.lifetime = rclpy.duration.Duration(seconds=1.0).to_msg()
# Cyan color
marker_pc.color.r = 0.0
marker_pc.color.g = 1.0
marker_pc.color.b = 1.0
marker_pc.color.a = 0.8
marker_pc.scale.x = 0.02
marker_pc.scale.y = 0.02
marker_pc.points = [Point(x=float(pt[0]), y=float(pt[1]), z=float(pt[2])) for pt in points_map]
pc_marker_array_msg.markers.append(marker_pc)
# --- STEP 5: PUBLISH ---
pub_bbox.publish(bbox_list_msg)
pub_markers.publish(marker_array_msg)
pub_pc_markers.publish(pc_marker_array_msg)
# Publish Point Cloud
if all_cloud_points:
@@ -206,6 +351,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
@@ -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:
@@ -1,205 +1,431 @@
#!/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 rclpy
from rclpy.node import Node
from nav_msgs.msg import Odometry
from rclpy.qos import QoSProfile, DurabilityPolicy
# 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
# Initialize the parent Node class with the node name 'odom_vizualization_node'
super().__init__('odom_vizualization_node')
# 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)
# ----------------------------------------------------------------------
# ROS2 Subscribers (Subscriptions)
# ----------------------------------------------------------------------
# Subscribe to RTAB-Map's localization pose.
# Topic: '/rtabmap/localizationPose' (geometry_msgs/PoseWithCovarianceStamped)
# Purpose: Retrieves the real-time estimated position and orientation of the robot
# with respect to the map frame, updated by the SLAM/localization node.
self.pose_sub = self.create_subscription(
PoseWithCovarianceStamped,
'/rtabmap/localizationPose',
self.pose_callback,
10
)
# Create publisher for robot pose visualization
# 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')
def odom_callback(self, msg):
def pose_callback(self, msg):
"""
Callback for robot odometry data.
Callback triggered when a new localization pose is received.
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
Stores the incoming pose, logs the coordinates, and creates visualization
markers (an arrow for heading and a sphere for position) to render in RViz.
Args:
msg (nav_msgs/Odometry): Robot odometry containing pose and velocity
msg (geometry_msgs.msg.PoseWithCovarianceStamped): The estimated pose of the robot.
"""
# Store the latest odometry message
self.latest_odom = msg
# Update the latest pose storage
self.latest_pose = msg
# Create a marker array to hold multiple visualization markers
# Extract position fields for easy logging and inspection
pos = msg.pose.pose.position
self.get_logger().info(f"[ROBOT POSE] x: {pos.x:.3f}, y: {pos.y:.3f}, z: {pos.z:.3f}")
# Instantiate a MarkerArray to hold both visual components (Arrow and Sphere)
marker_array = MarkerArray()
# 1. Create arrow marker for robot pose (shows both position and orientation)
# 1. Generate an arrow marker representing the robot's orientation and position
arrow_marker = self.create_pose_arrow(msg)
marker_array.markers.append(arrow_marker)
# 2. Create sphere marker for position only (easier to see than arrow tip)
# 2. Generate a sphere marker to mark the central position coordinate clearly
position_marker = self.create_position_sphere(msg)
marker_array.markers.append(position_marker)
# 3. Create and update trajectory line showing robot's path history
self.trajectory_points.append(msg.pose.pose.position)
# Remove oldest point if trajectory exceeds maximum length
if len(self.trajectory_points) > self.max_trajectory_points:
self.trajectory_points.pop(0)
trajectory_marker = self.create_trajectory(msg.header.frame_id)
marker_array.markers.append(trajectory_marker)
# Publish all visualization markers
# Publish the MarkerArray to RViz
self.pose_marker_pub.publish(marker_array)
def create_pose_arrow(self, odom_msg):
def info_callback(self, msg):
"""
Create an ARROW marker showing robot's position and orientation.
Callback triggered when new SLAM info/statistics are published by RTAB-Map.
The arrow points in the direction the robot is facing, providing
visual feedback on both location and heading.
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:
odom_msg (nav_msgs/Odometry): Odometry message with pose information
msg (rtabmap_msgs.msg.Info): RTAB-Map status info containing statistics.
"""
# If loop_closure_id is greater than 0, it means RTAB-Map has successfully
# matched the current frame with a previously visited location (loop closure).
if msg.loop_closure_id > 0:
self.get_logger().info(
f"\n=========================================\n"
f"[LOOP CLOSURE] Detected loop closure!\n"
f"Current Node ID: {msg.ref_id} ===> Historical Node ID: {msg.loop_closure_id}\n"
f"=========================================\n"
)
def map_graph_callback(self, msg):
"""
Callback triggered when the optimized MapGraph is published by RTAB-Map.
Extracts the list of positions from the optimized poses in the graph, updates
the local trajectory points representation, and republishes the path history
as a line strip marker.
Args:
msg (rtabmap_msgs.msg.MapGraph): The map graph message containing poses.
"""
# Extract the position components from all keyframe poses in the graph message.
# This reflects the optimized trajectory updated after loop closures.
self.trajectory_points = [pose.position for pose in msg.poses]
# Create the MarkerArray to visualize the updated path
marker_array = MarkerArray()
# Create a line strip marker connecting all trajectory coordinates
trajectory_marker = self.create_trajectory(msg.header.frame_id)
marker_array.markers.append(trajectory_marker)
# Publish the updated trajectory to RViz
self.pose_marker_pub.publish(marker_array)
def tf_callback(self, msg):
"""
Callback triggered when a transform message is received on '/tf_old'.
Filters out any transforms that have 'map' as the parent (frame_id) or the child
(child_frame_id) frame to avoid conflicting coordinate frame definitions on the
active '/tf' topic. Only forwards non-map transforms.
Args:
msg (tf2_msgs.msg.TFMessage): List of coordinate frame transforms.
"""
filtered_transforms = []
for transform in msg.transforms:
# We filter out 'map' transforms because RTAB-Map or another SLAM system publishes
# the primary map -> odom transform. Subscribing to tf_old and republishing allows
# us to pass through base_link, sensor frames, etc., without messing up the map frame tree.
if transform.header.frame_id != 'map' and transform.child_frame_id != 'map':
filtered_transforms.append(transform)
# If we have any remaining valid transforms, package them and publish to /tf
if filtered_transforms:
out_msg = TFMessage()
out_msg.transforms = filtered_transforms
self.tf_pub.publish(out_msg)
def tf_static_callback(self, msg):
"""
Callback triggered when a static transform message is received on '/tf_static_old'.
Caches new static transforms and updates existing ones if their frame relationships
change. It then republishes the entire accumulated set of static transforms to
'/tf_static' to ensure late-joining nodes have complete access to the coordinate system.
Args:
msg (tf2_msgs.msg.TFMessage): List of static coordinate frame transforms.
"""
updated = False
for transform in msg.transforms:
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 = transform.header.stamp
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 create_pose_arrow(self, pose_msg):
"""
Constructs a red 3D Arrow Marker representing the robot's current position and orientation.
Args:
pose_msg (geometry_msgs.msg.PoseWithCovarianceStamped): Pose data source.
Returns:
visualization_msgs/Marker: Arrow marker for RViz
visualization_msgs.msg.Marker: Fully populated arrow marker ready for publishing.
"""
marker = Marker()
marker.header = odom_msg.header
# FIXME: use position from SLAM instead of raw odometry
# Copy the header (timestamp) from the pose message, but force the frame_id to "map"
marker.header = pose_msg.header
marker.header.frame_id = "map"
marker.ns = "robot_pose" # Namespace for grouping markers
marker.id = 0 # Unique ID within namespace
# Namespace and ID: uniquely identifies this marker within RViz to allow updates/overwrites
marker.ns = "robot_pose"
marker.id = 0
# Marker shape type: ARROW
marker.type = Marker.ARROW
# Action: ADD (creates or updates the marker)
marker.action = Marker.ADD
# Set pose from odometry (position and orientation)
marker.pose = odom_msg.pose.pose
# Assign the complete pose (position coordinates and orientation quaternion)
marker.pose = pose_msg.pose.pose
# Arrow dimensions (length, width, height)
marker.scale.x = 0.5 # Arrow length (0.5 meters)
marker.scale.y = 0.05 # Arrow shaft width
marker.scale.z = 0.05 # Arrow shaft height
# Set physical dimensions of the arrow (in meters)
marker.scale.x = 0.5 # Shaft/total length
marker.scale.y = 0.05 # Shaft width
marker.scale.z = 0.05 # Shaft height
# Color (Red arrow for visibility)
# Set color to solid bright red (RGBA: 1.0, 0.0, 0.0, 1.0)
marker.color.r = 1.0
marker.color.g = 0.0
marker.color.b = 0.0
marker.color.a = 1.0 # Fully opaque
# Persistent marker (lifetime=0 means it stays until deleted)
# Lifetime: Setting to 0 indicates the marker should persist indefinitely until replaced or deleted
marker.lifetime = rclpy.duration.Duration(seconds=0).to_msg()
return marker
def create_position_sphere(self, odom_msg):
def create_position_sphere(self, pose_msg):
"""
Create a SPHERE marker at the robot's position.
This provides an easy-to-see indicator of the robot's current location,
complementing the arrow marker.
Constructs a semi-transparent green Sphere Marker representing the robot's current position.
Args:
odom_msg (nav_msgs/Odometry): Odometry message with pose information
pose_msg (geometry_msgs.msg.PoseWithCovarianceStamped): Pose data source.
Returns:
visualization_msgs/Marker: Sphere marker for RViz
visualization_msgs.msg.Marker: Fully populated sphere marker ready for publishing.
"""
marker = Marker()
marker.header = odom_msg.header
# FIXME: use position from SLAM instead of raw odometry
# Setup header details with frame fixed to "map"
marker.header = pose_msg.header
marker.header.frame_id = "map"
# Separate namespace and unique ID to ensure it doesn't conflict with the arrow marker
marker.ns = "robot_position"
marker.id = 1 # Different ID from arrow marker
marker.id = 1
# Marker shape type: SPHERE
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
# Copy the position coordinates. Orientation quaternion is set to identity (w=1.0)
# since rotation does not affect the visual presentation of a sphere.
marker.pose.position = pose_msg.pose.pose.position
marker.pose.orientation.w = 1.0
# Sphere size (0.2m diameter)
# Set diameter of the sphere to 0.2 meters in all axes
marker.scale.x = 0.2
marker.scale.y = 0.2
marker.scale.z = 0.2
# Color (Green sphere)
# Set color to semi-transparent green (RGBA: 0.0, 1.0, 0.0, 0.8)
marker.color.r = 0.0
marker.color.g = 1.0
marker.color.b = 0.0
marker.color.a = 0.8 # Semi-transparent
marker.color.a = 0.8 # Slightly transparent to make the arrow inside visible
# Indefinite persistence
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 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()
# Shutdown ROS2 context
rclpy.shutdown()
if __name__ == '__main__':
@@ -30,6 +30,7 @@ from rclpy.duration import Duration
from std_srvs.srv import SetBool
from scene_graph_interfaces.msg import Object3DBoundingBox, Object3DBoundingBoxList, ClassifiedRoom, RoomPolygonList
from scene_graph_interfaces.msg import FunObject3DBoundingBox, FunObject3DBoundingBoxList
from rtabmap_msgs.msg import Info, MapGraph
from visualization_msgs.msg import Marker, MarkerArray
from geometry_msgs.msg import Point32, Point
from scene_graph_interfaces.msg import GraphObject, GraphFunctionalElement
@@ -104,6 +105,10 @@ class ObjectNode:
self.functional_element_ids = set()
# Loop closure tracking fields
self.reference_keyframe_id = None
self.cached_keyframe_pose = None
if point_cloud is not None and len(point_cloud) > 0:
# Convert from Numpy Array (N,3) to Open3D
self.point_cloud.points = o3d.utility.Vector3dVector(point_cloud)
@@ -118,6 +123,11 @@ class FunctionalElementNode:
self.class_id = class_id
self.point_cloud = o3d.geometry.PointCloud()
# Loop closure tracking fields
self.reference_keyframe_id = None
self.cached_keyframe_pose = None
if point_cloud is not None and len(point_cloud) > 0:
self.point_cloud.points = o3d.utility.Vector3dVector(point_cloud)
@@ -174,6 +184,12 @@ class GraphManagementNode(Node):
self.create_subscription(PointCloud2, '/object_clouds/rtdetr',
self.rtdetr_cloud_callback, 10)
# Subscribe to RTAB-Map Info for keyframe mapping
self.create_subscription(Info, '/rtabmap/info', self.rtabmap_info_callback, 10)
# Subscribe to RTAB-Map MapGraph for SLAM graph optimization callbacks
self.create_subscription(MapGraph, '/rtabmap/mapGraph', self.rtabmap_map_graph_callback, 10)
# Subscribe to current Task Information
self.create_subscription(std_msgs.msg.String, '/current_task',
self.task_processing_callback, 10)
@@ -285,6 +301,10 @@ class GraphManagementNode(Node):
# Track marker IDs for deletion
self.old_marker_ids = []
# Keyframe buffers for retroactive loop closure correction
self.keyframe_time_buffer = [] # Ring buffer of (timestamp_sec, keyframe_id)
self.keyframe_poses_cache = {} # Cached map of keyframe_id -> 4x4 numpy matrix
# Buffer-Helper
self.last_yolo_cloud_np = None
self.last_yolo_stamp = None
@@ -357,6 +377,155 @@ class GraphManagementNode(Node):
self.get_logger().info('Graph Management Node initialized')
def rtabmap_info_callback(self, msg):
"""
Tracks the current active RTAB-Map keyframe ref_id by its timestamp.
"""
stamp_sec = GraphManagementNode.stamp_to_sec(msg.header.stamp)
self.keyframe_time_buffer.append((stamp_sec, msg.ref_id))
if len(self.keyframe_time_buffer) > 200:
self.keyframe_time_buffer.pop(0)
def get_closest_keyframe_id(self, timestamp):
"""
Finds the closest keyframe ID matching a given timestamp.
"""
if not self.keyframe_time_buffer:
return None
closest = min(self.keyframe_time_buffer, key=lambda x: abs(x[0] - timestamp))
if abs(closest[0] - timestamp) > 5.0:
return None
return closest[1]
def pose_to_matrix(self, pose):
"""
Converts geometry_msgs/Pose to a 4x4 matrix.
"""
T = np.identity(4)
T[0, 3] = pose.position.x
T[1, 3] = pose.position.y
T[2, 3] = pose.position.z
q = [pose.orientation.x, pose.orientation.y, pose.orientation.z, pose.orientation.w]
r = R.from_quat(q)
T[:3, :3] = r.as_matrix()
return T
def rtabmap_map_graph_callback(self, msg):
"""
Handles SLAM optimized map graph updates to correct object coordinates.
"""
# 1. Map optimized poses from message
updated_poses = {}
for node_id, pose_msg in zip(msg.poses_id, msg.poses):
updated_poses[node_id] = self.pose_to_matrix(pose_msg)
# Update cache
self.keyframe_poses_cache.update(updated_poses)
# 2. Acquire graph lock
while self.graph_lock:
time.sleep(0.01)
self.graph_lock = True
try:
# Shift count tracking for logging
shift_count = 0
# Iterate through all objects in the scene graph
for node in list(self.scene_graph.nodes):
node_data = self.scene_graph.nodes[node].get('data')
# We want to correct both ObjectNode and orphan FunctionalElementNode
if not (isinstance(node_data, ObjectNode) or isinstance(node_data, FunctionalElementNode)):
continue
# If it's a child functional element of a parent object, it will be transformed
# with the parent object. So we don't transform it independently to avoid double transform.
if isinstance(node_data, FunctionalElementNode) and node_data.parent_object_id is not None:
continue
k_id = node_data.reference_keyframe_id
if k_id is None or k_id not in updated_poses:
continue
T_new = updated_poses[k_id]
T_old = node_data.cached_keyframe_pose
# Check if the baseline keyframe has shifted
if T_old is not None and not np.allclose(T_old, T_new, atol=1e-4):
# Compute delta transform matrix: T_delta = T_new * inv(T_old)
T_delta = T_new @ np.linalg.inv(T_old)
# Update object point cloud
node_data.point_cloud.transform(T_delta)
# Update bounding box representation if it's an ObjectNode
if isinstance(node_data, ObjectNode) and len(node_data.point_cloud.points) > 0:
points = np.asarray(node_data.point_cloud.points)
p_min = points.min(axis=0)
p_max = points.max(axis=0)
node_data.bounding_box = [
Point32(x=float(p_min[0]), y=float(p_min[1]), z=float(p_min[2])),
Point32(x=float(p_max[0]), y=float(p_max[1]), z=float(p_max[2]))
]
# Update child FunctionalElementNodes recursively
if isinstance(node_data, ObjectNode):
for child_id in list(node_data.functional_element_ids):
if child_id in self.scene_graph and 'data' in self.scene_graph.nodes[child_id]:
child_data = self.scene_graph.nodes[child_id]['data']
if isinstance(child_data, FunctionalElementNode):
child_data.point_cloud.transform(T_delta)
child_data.cached_keyframe_pose = T_new
# Update cached baseline pose
node_data.cached_keyframe_pose = T_new
shift_count += 1
# Recalculate room containment if room boundaries/polygons exist
if isinstance(node_data, ObjectNode):
self._update_room_containment(node_data)
if shift_count > 0:
self.get_logger().info(f"Retroactively corrected {shift_count} object positions via loop closure delta.")
finally:
self.graph_lock = False
def _update_room_containment(self, object_node: ObjectNode):
"""
Updates the room containment edge in the scene graph for a given ObjectNode.
Finds the room containing this object and connects them.
"""
# Remove any existing room edges for this object
for neighbor in list(self.scene_graph.neighbors(object_node.id)):
if neighbor in self.scene_graph and 'data' in self.scene_graph.nodes[neighbor]:
neighbor_data = self.scene_graph.nodes[neighbor].get('data')
if isinstance(neighbor_data, RoomNode):
self.scene_graph.remove_edge(neighbor, object_node.id)
# Find which room now contains the object
assigned_room = 1 # Default to default_room (ID 1)
for node in list(self.scene_graph.nodes):
if node in self.scene_graph and 'data' in self.scene_graph.nodes[node]:
room_data = self.scene_graph.nodes[node].get('data')
if isinstance(room_data, RoomNode) and room_data.polygon is not None:
coords = [(p.x, p.y) for p in room_data.polygon]
poly = ShapelyPolygon(coords)
# Get object centroid 2D
obj_x, obj_y = self.get_object_2d_position(object_node)
point = ShapelyPoint(obj_x, obj_y)
if poly.contains(point) or poly.touches(point):
assigned_room = room_data.id
break
# Connect to the assigned room
self.scene_graph.add_edge(assigned_room, object_node.id)
def set_update_state_callback(self, request, response):
"""
Set Scene Graph Update State
@@ -538,6 +707,10 @@ class GraphManagementNode(Node):
centroid = np.mean(obj_cloud, axis=0)
# Get closest keyframe ID for this detection
detection_time = GraphManagementNode.stamp_to_sec(msg.header.stamp)
closest_k_id = self.get_closest_keyframe_id(detection_time)
# 5) Find a matching object node (by label + spatial proximity)
match_id = self._find_closest_object_node(
centroid,
@@ -549,6 +722,10 @@ class GraphManagementNode(Node):
# 6a) Merge into existing object node
obj_node = self.scene_graph.nodes[match_id]['data']
if obj_node.reference_keyframe_id is None and closest_k_id is not None:
obj_node.reference_keyframe_id = closest_k_id
obj_node.cached_keyframe_pose = self.keyframe_poses_cache.get(closest_k_id, np.identity(4))
# Merge point clouds
t0 = time.perf_counter()
obj_node.point_cloud = self.merge_point_clouds(obj_node.point_cloud, obj_cloud)
@@ -580,6 +757,8 @@ class GraphManagementNode(Node):
class_id=label,
point_cloud=None
)
new_obj.reference_keyframe_id = closest_k_id
new_obj.cached_keyframe_pose = self.keyframe_poses_cache.get(closest_k_id, np.identity(4)) if closest_k_id is not None else np.identity(4)
new_obj.graspable = graspable_msg
new_obj.bounding_box = [pmin, pmax]
@@ -658,6 +837,10 @@ class GraphManagementNode(Node):
centroid = np.mean(func_cloud, axis=0)
# Get closest keyframe ID for this detection
detection_time = GraphManagementNode.stamp_to_sec(msg.header.stamp)
closest_k_id = self.get_closest_keyframe_id(detection_time)
# 5) Find a matching functional node (by label + spatial proximity)
match_id = self._find_matching_functional_node(
centroid,
@@ -669,6 +852,10 @@ class GraphManagementNode(Node):
# 6a) Merge into existing functional node
fn_node = self.scene_graph.nodes[match_id]['data']
if fn_node.reference_keyframe_id is None and closest_k_id is not None:
fn_node.reference_keyframe_id = closest_k_id
fn_node.cached_keyframe_pose = self.keyframe_poses_cache.get(closest_k_id, np.identity(4))
fn_node.point_cloud = self.merge_point_clouds(fn_node.point_cloud, func_cloud)
self.get_logger().info(
@@ -694,6 +881,8 @@ class GraphManagementNode(Node):
point_cloud=None,
affordances={aff},
)
new_fn.reference_keyframe_id = closest_k_id
new_fn.cached_keyframe_pose = self.keyframe_poses_cache.get(closest_k_id, np.identity(4)) if closest_k_id is not None else np.identity(4)
# Initialize point cloud via merge helper
new_fn.point_cloud = self.merge_point_clouds(new_fn.point_cloud, func_cloud)
+182
View File
@@ -0,0 +1,182 @@
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_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)