diff --git a/scene_graph_room_classification/sam/geometry_utils.py b/scene_graph_room_classification/sam/geometry_utils.py index aad2796..1befbad 100644 --- a/scene_graph_room_classification/sam/geometry_utils.py +++ b/scene_graph_room_classification/sam/geometry_utils.py @@ -5,4 +5,51 @@ class GeometryUtils: Handles all 3D geometric projections and transformations. Strictly stateless (math only). """ - pass \ No newline at end of file + @staticmethod + def project_mask_to_3d(depth_img, mask, intrinsics, depth_scale=1.0): + """ + Converts a specific boolean mask from a depth image into a 3D point cloud + in the Camera Optical Frame. + + Args: + depth_img (np.array): HxW depth image. + mask (np.array): HxW boolean mask (True = object pixel). + intrinsics (dict): {'fx', 'fy', 'cx', 'cy'}. + depth_scale (float): Factor to convert depth to meters (e.g., 0.001 for mm). + + Returns: + np.array: (N, 3) array of points [x, y, z] in camera frame. + """ + # 1. Get indices of pixels that belong to the object + # np.where returns rows (v) and columns (u) + vs, us = np.where(mask) + + if len(vs) == 0: + return np.empty((0, 3)) + + # 2. Extract depth values for these pixels + zs = depth_img[vs, us] * depth_scale + + # 3. Filter invalid depth + # RealSense/Kinect often give 0 for "unknown" and >10m is usually unreliable + valid_mask = (zs > 0.1) & (zs < 10.0) + + if np.sum(valid_mask) == 0: + return np.empty((0, 3)) + + # Apply validity filter to u, v, z + us = us[valid_mask] + vs = vs[valid_mask] + zs = zs[valid_mask] + + # 4. Vectorized Pinhole Projection + # x = (u - cx) * z / fx + # y = (v - cy) * z / fy + xs = (us - intrinsics['cx']) * zs / intrinsics['fx'] + ys = (vs - intrinsics['cy']) * zs / intrinsics['fy'] + + # 5. Stack into (N, 3) matrix + # Shape: [[x1, y1, z1], [x2, y2, z2], ...] + points_cam = np.vstack((xs, ys, zs)).T + + return points_cam \ No newline at end of file