Thresholds a depth map using percentile-based limits and optional maximum depth clamping. Steps: 1. If `max_depth > 0`, clamp all values above `max_depth` to zero. 2. Compute `max_percentile` and `min_percentile` thresholds using nanpercentile. 3. Zero out values above/be
(
depth_map: np.ndarray,
max_percentile: float = 99,
min_percentile: float = 1,
max_depth: float = -1,
)
| 2 | |
| 3 | |
| 4 | def threshold_depth_map( |
| 5 | depth_map: np.ndarray, |
| 6 | max_percentile: float = 99, |
| 7 | min_percentile: float = 1, |
| 8 | max_depth: float = -1, |
| 9 | ) -> np.ndarray: |
| 10 | """ |
| 11 | Thresholds a depth map using percentile-based limits and optional maximum depth clamping. |
| 12 | |
| 13 | Steps: |
| 14 | 1. If `max_depth > 0`, clamp all values above `max_depth` to zero. |
| 15 | 2. Compute `max_percentile` and `min_percentile` thresholds using nanpercentile. |
| 16 | 3. Zero out values above/below these thresholds, if thresholds are > 0. |
| 17 | |
| 18 | Args: |
| 19 | depth_map (np.ndarray): |
| 20 | Input depth map (H, W). |
| 21 | max_percentile (float): |
| 22 | Upper percentile (0-100). Values above this will be set to zero. |
| 23 | min_percentile (float): |
| 24 | Lower percentile (0-100). Values below this will be set to zero. |
| 25 | max_depth (float): |
| 26 | Absolute maximum depth. If > 0, any depth above this is set to zero. |
| 27 | If <= 0, no maximum-depth clamp is applied. |
| 28 | |
| 29 | Returns: |
| 30 | np.ndarray: |
| 31 | Depth map (H, W) after thresholding. Some or all values may be zero. |
| 32 | Returns None if depth_map is None. |
| 33 | """ |
| 34 | if depth_map is None: |
| 35 | return None |
| 36 | |
| 37 | # depth_map = depth_map.astype(float, copy=True) |
| 38 | |
| 39 | # Optional clamp by max_depth |
| 40 | if max_depth > 0: |
| 41 | depth_map[depth_map > max_depth] = 0.0 |
| 42 | |
| 43 | # Percentile-based thresholds |
| 44 | depth_max_thres = ( |
| 45 | np.nanpercentile(depth_map, max_percentile) if max_percentile > 0 else None |
| 46 | ) |
| 47 | depth_min_thres = ( |
| 48 | np.nanpercentile(depth_map, min_percentile) if min_percentile > 0 else None |
| 49 | ) |
| 50 | |
| 51 | # Apply the thresholds if they are > 0 |
| 52 | if depth_max_thres is not None and depth_max_thres > 0: |
| 53 | depth_map[depth_map > depth_max_thres] = 0.0 |
| 54 | if depth_min_thres is not None and depth_min_thres > 0: |
| 55 | depth_map[depth_map < depth_min_thres] = 0.0 |
| 56 | |
| 57 | return depth_map |