diff --git a/scene_graph_room_classification/scene_graph_fusion/scene_graph_fusion_node.py b/scene_graph_room_classification/scene_graph_fusion/scene_graph_fusion_node.py index 117e123..4eeaf77 100644 --- a/scene_graph_room_classification/scene_graph_fusion/scene_graph_fusion_node.py +++ b/scene_graph_room_classification/scene_graph_fusion/scene_graph_fusion_node.py @@ -334,35 +334,30 @@ class GraphManagementNode(Node): if new_points_np is None or len(new_points_np) == 0: return existing_pcd - # 1. Neue Punkte in Open3D Cloud wandeln + # New Points -> o3d new_pcd = o3d.geometry.PointCloud() new_pcd.points = o3d.utility.Vector3dVector(new_points_np) - # 2. VOR-Filterung: Rauschen aus der neuen Messung entfernen - # nb_neighbors: Wie viele Nachbarn betrachten? - # std_ratio: Wie strikt? Kleiner = strikter (mehr Punkte weg) + # remove noise if remove_outliers and len(new_pcd.points) > 10: new_pcd, _ = new_pcd.remove_statistical_outlier(nb_neighbors=20, std_ratio=2.0) - # Initialisierung falls noch keine Cloud existiert + # Initialize if existing_pcd is None: existing_pcd = o3d.geometry.PointCloud() - # Falls existing_pcd fälschlicherweise noch ein numpy array ist if isinstance(existing_pcd, np.ndarray): tmp = o3d.geometry.PointCloud() tmp.points = o3d.utility.Vector3dVector(existing_pcd) existing_pcd = tmp - # 3. Merging (Addition) + # Add PointClouds existing_pcd += new_pcd - # 4. Downsampling (Fusioniert Punkte im gleichen Voxel) - # Dies ist der wichtigste Schritt gegen unendliches Wachstum der Cloud + # Downsample existing_pcd = existing_pcd.voxel_down_sample(voxel_size=voxel_size) - # 5. NACH-Filterung: Artefakte des Mergings entfernen (Radius Outlier Removal) - # Entfernt Punkte, die isoliert schweben (weniger als 4 Punkte in einer 2x Voxel-Kugel) + # Remove Artifacts if remove_outliers and len(existing_pcd.points) > 10: existing_pcd, _ = existing_pcd.remove_radius_outlier(nb_points=4, radius=voxel_size * 2.5) @@ -530,7 +525,6 @@ class GraphManagementNode(Node): base_label = getattr(base_data, "class_id", None) merged_count = 0 - # Kandidatenliste vorab bauen (nicht während Iteration am Graph rumschneiden) candidates = [] for node_id, attrs in self.scene_graph.nodes(data=True): if node_id == base_id: @@ -539,7 +533,6 @@ class GraphManagementNode(Node): if other is None or not isinstance(other, ObjectNode): continue - # Nur gleiche Klasse mergen if base_label is not None and getattr(other, "class_id", None) != base_label: continue @@ -551,11 +544,10 @@ class GraphManagementNode(Node): if dist <= merge_threshold: candidates.append((node_id, dist)) - # Optional: erst die nächsten mergen candidates.sort(key=lambda x: x[1]) for other_id, _dist in candidates: - # Node könnte schon weg sein (falls vorher gemerged) + # does node exist? if other_id not in self.scene_graph: continue @@ -563,12 +555,12 @@ class GraphManagementNode(Node): if other_data is None or not isinstance(other_data, ObjectNode): continue - # 1) Pointcloud mergen (base <- other) + # merge clouds (base <- other) other_pts = np.asarray(other_data.point_cloud.points) if other_pts.size > 0: base_data.point_cloud = self.merge_point_clouds(base_data.point_cloud, other_pts) - # 2) graspable mergen (OR-Policy) + # merge graspable via OR base_g = getattr(base_data, "graspable", None) other_g = getattr(other_data, "graspable", None) if base_g is None: @@ -576,7 +568,7 @@ class GraphManagementNode(Node): elif other_g is not None: base_data.graspable = bool(base_g) or bool(other_g) - # 3) bounding_box (AABB) optional vereinigen, falls ihr das Feld nutzt + # bbox merge if hasattr(base_data, "bounding_box") and hasattr(other_data, "bounding_box"): bb_a = getattr(base_data, "bounding_box", None) bb_b = getattr(other_data, "bounding_box", None) @@ -596,7 +588,7 @@ class GraphManagementNode(Node): base_data.bounding_box = [min_pt, max_pt] - # 4) Edges übernehmen: alle Nachbarn von other_id an base_id hängen + # copy edges other_neighbors = list(self.scene_graph.neighbors(other_id)) for nb in other_neighbors: if nb == base_id: @@ -604,11 +596,11 @@ class GraphManagementNode(Node): if not self.scene_graph.has_edge(nb, base_id): self.scene_graph.add_edge(nb, base_id) - # 5) Node entfernen (damit keine Zombie-Couch bleibt) + # remove old node self.scene_graph.remove_node(other_id) merged_count += 1 - # 6) base_centroid aktualisieren, weil base_cloud jetzt gewachsen ist + # update centroid base_centroid = self._get_node_centroid(base_data) if base_centroid is None: break @@ -617,7 +609,7 @@ class GraphManagementNode(Node): def _process_yolo_bboxes(self, msg: Object3DBoundingBoxList): - # 0) No detections -> nothing to do + # No detections -> nothing to do if not msg.bbox: return @@ -861,11 +853,11 @@ class GraphManagementNode(Node): if node_data is None: continue - # Wir interessieren uns nur für FunctionalElementNode + # only look at functionalelementnodes if not isinstance(node_data, FunctionalElementNode): continue - # optional: nur gleiches functional_label vergleichen + # only same functional label allowed if functional_label and node_data.functional_label != functional_label: continue @@ -910,21 +902,20 @@ class GraphManagementNode(Node): node_data = self.scene_graph.nodes[node]['data'] - # Wir suchen nur nach ObjectNodes + # only look for objectnodes if isinstance(node_data, ObjectNode): - # Optional: Filter nach Label (z.B. nur "chair" suchen) + # only look for fitting labels if label and node_data.class_id != label: continue - # Zentroid der existierenden Objekt-Pointcloud berechnen + # calculate centroid points = np.asarray(node_data.point_cloud.points) + # cloud empty? if points.size == 0: - # Leere Wolke -> nichts zum Vergleichen continue obj_centroid = np.mean(points, axis=0) - # Euklidische Distanz zwischen beiden Zentroiden dist = math.sqrt( (obj_centroid[0] - centroid[0]) ** 2 + (obj_centroid[1] - centroid[1]) ** 2 + @@ -958,28 +949,28 @@ class GraphManagementNode(Node): func_node = self.scene_graph.nodes[func_node_id]['data'] - # 1) Falls bereits ein Object-Parent existiert → nichts ändern + # 1) If an Object parent already exists → do nothing neighbors = list(self.scene_graph.neighbors(func_node_id)) for n in neighbors: ndata = self.scene_graph.nodes[n]['data'] if isinstance(ndata, ObjectNode): - # Parent schon gesetzt + # Parent already set func_node.parent_object_id = n return n - # 2) Versuch: nächstes Objekt im Umkreis finden + # 2) Try to find the nearest object within the radius parent_node_id = self._find_closest_object_node( centroid, - label=None, # funktionale Labels ≠ Objekt-Labels + label=None, # functional labels ≠ object labels threshold=object_threshold ) if parent_node_id is not None: - # Edge Objekt → Functional-Element setzen (falls nicht vorhanden) + # Create edge Object → Functional element (if not already present) if not self.scene_graph.has_edge(parent_node_id, func_node_id): self.scene_graph.add_edge(parent_node_id, func_node_id) - # Falls der Node vorher als Orphan an einem Raum hing → Kante entfernen + # If the node was previously attached to a room as an orphan → remove that edge for n in neighbors: ndata = self.scene_graph.nodes[n]['data'] if isinstance(ndata, RoomNode) and self.scene_graph.has_edge(n, func_node_id): @@ -989,8 +980,8 @@ class GraphManagementNode(Node): func_node.room_id = None return parent_node_id - # 3) Kein Objekt in der Nähe → Orphan: an aktuellen Raum hängen - room_id = self.current_room_id # Default-Raum (id=1) aktuell + # 3) No object nearby → orphan: attach to the current room + room_id = self.current_room_id # Current default room (id=1) if not self.scene_graph.has_edge(room_id, func_node_id): self.scene_graph.add_edge(room_id, func_node_id) @@ -1000,7 +991,8 @@ class GraphManagementNode(Node): - def main_loop_callback(self): #TODO auf Funktional Edges anpassen + + def main_loop_callback(self): #TODO rework with functional edges """ Timer callback that runs at 2 Hz for periodic graph maintenance. @@ -1222,9 +1214,6 @@ class GraphManagementNode(Node): self.last_yolo_stamp = msg.header.stamp self._try_process_yolo() - # Optional: sehr selten loggen (z.B. alle ~5s), sonst nervt's - # self.get_logger().info(f"YOLO cloud buffered: {cloud_np.shape[0]} points") - except Exception as e: self.get_logger().warn(f"Fehler beim Verarbeiten der YOLO-Cloud: {e}") @@ -1251,9 +1240,6 @@ class GraphManagementNode(Node): self.last_rtdetr_stamp = msg.header.stamp self._try_process_rtdetr() - # Optionales Debug-Logging (sparsam verwenden) - # self.get_logger().info(f"RT-DETR cloud buffered: {cloud_np.shape[0]} points") - except Exception as e: self.get_logger().warn(f"Fehler beim Verarbeiten der RT-DETR-Cloud: {e}") @@ -1289,7 +1275,7 @@ class GraphManagementNode(Node): return point_cloud2.create_cloud(header, fields, cloud_data) - def publish_markers(self): #TODO ohne bbox + def publish_markers(self): """ Publish visualization markers for all nodes and edges in the scene graph. @@ -1461,14 +1447,14 @@ class GraphManagementNode(Node): # ==================================================================== # 4.2 OBJECT ↔ FUNCTIONAL ELEMENT EDGES # ==================================================================== - edge_id = len(line_marker_array.markers) # weiterzählen, damit IDs einzigartig bleiben + edge_id = len(line_marker_array.markers) # continue counting so IDs remain unique for node_id, node_attrs in self.scene_graph.nodes(data=True): node_data = node_attrs.get('data', None) if node_data is None: continue - # Wir interessieren uns nur für FunctionalElementNodes + # We are only interested in FunctionalElementNodes if not isinstance(node_data, FunctionalElementNode): continue @@ -1476,7 +1462,7 @@ class GraphManagementNode(Node): if func_centroid is None: continue - # Nachbarn checken: Object-Parent finden + # Check neighbors: find Object parent neighbors = list(self.scene_graph.neighbors(node_id)) for nb in neighbors: nb_data = self.scene_graph.nodes[nb].get('data', None) @@ -1487,25 +1473,25 @@ class GraphManagementNode(Node): if obj_centroid is None: continue - # Marker für diese Kante erzeugen + # Create marker for this edge marker = Marker() marker.header.frame_id = "map" marker.header.stamp = self.get_clock().now().to_msg() marker.ns = "object_functional_edges" marker.id = edge_id - marker.type = Marker.LINE_LIST # oder LINE_STRIP mit 2 Punkten + marker.type = Marker.LINE_LIST # alternatively LINE_STRIP with 2 points marker.action = Marker.ADD - # Linienbreite - marker.scale.x = 0.01 # dünne Linie + # Line width + marker.scale.x = 0.01 # thin line - # Farbe (z.B. cyan) + # Color (e.g. cyan) marker.color.a = 1.0 marker.color.r = 0.0 marker.color.g = 1.0 marker.color.b = 1.0 - # Start- und Endpunkt + # Start and end point p1 = Point() p1.x, p1.y, p1.z = float(obj_centroid[0]), float(obj_centroid[1]), float(obj_centroid[2]) @@ -1525,7 +1511,7 @@ class GraphManagementNode(Node): functional_marker_array = MarkerArray() functional_text_array = MarkerArray() func_id = 0 - text_id_offset = 10000 # damit IDs nicht mit anderen Textmarkern kollidieren + text_id_offset = 10000 # prevent ID collisions with other text markers for node in nodes: if node in self.scene_graph and 'data' in self.scene_graph.nodes[node]: @@ -1537,18 +1523,18 @@ class GraphManagementNode(Node): pos = (float(centroid[0]), float(centroid[1]), float(centroid[2])) - # hat dieses FunctionalElement einen Objekt-Parent? + # Does this FunctionalElement have an Object parent? has_parent = any( isinstance(self.scene_graph.nodes[n]['data'], ObjectNode) for n in self.scene_graph.neighbors(node) ) - # 1) Kugelmarker + # 1) Sphere marker functional_marker_array.markers.append( self.create_functional_marker(pos, func_id, has_parent=has_parent) ) - # 2) Textmarker mit functional_label oder erster Affordance + # 2) Text marker with functional_label or first affordance label_text = data.functional_label if not label_text: if data.affordances: @@ -1557,7 +1543,7 @@ class GraphManagementNode(Node): label_text = "functional" text_marker = self.create_text_marker( - (pos[0], pos[1], pos[2] + 0.05), # leicht drüber + (pos[0], pos[1], pos[2] + 0.05), # slightly above label_text, text_id_offset + func_id ) @@ -2227,11 +2213,10 @@ class GraphManagementNode(Node): """ centroid = self._get_node_centroid(object_node) if centroid is None: - # Fallback: Nullpunkt, falls Wolke leer ist return (0.0, 0.0) return (float(centroid[0]), float(centroid[1])) - def is_object_in_graph(self, object): #TODO ohne bbox + def is_object_in_graph(self, object): """ Check if a detected object already exists in the scene graph. @@ -2820,7 +2805,7 @@ class GraphManagementNode(Node): return False - def export_scene_graph_to_json(self, filename): #TODO ohne bbox + def export_scene_graph_to_json(self, filename): #TODO rework """ Export the current scene graph to a hierarchical JSON file.