Added project_mask_to_3d using vectorized pinhole camera mathematics

This commit is contained in:
2025-11-24 22:32:31 +01:00
parent d478b80fc5
commit aee122bf55
@@ -5,4 +5,51 @@ class GeometryUtils:
Handles all 3D geometric projections and transformations.
Strictly stateless (math only).
"""
pass
@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