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