MCPcopy Create free account
hub / github.com/InternRobotics/G2VLM / write_depth

Function write_depth

eval_code/recons/models/moge/utils/io.py:110–154  ·  view source on GitHub ↗

Encode and write a depth image as 16-bit PNG format. ### Parameters: - `path: Union[str, os.PathLike, IO]` The file path or file object to write to. - `depth: np.ndarray` The depth array, float32 array of shape (H, W). May contain `NaN` for invalid values an

(
    path: Union[str, os.PathLike, IO], 
    depth: np.ndarray, 
    unit: float = None,
    max_range: float = 1e5,
    compression_level: int = 7,
)

Source from the content-addressed store, hash-verified

108
109
110def write_depth(
111 path: Union[str, os.PathLike, IO],
112 depth: np.ndarray,
113 unit: float = None,
114 max_range: float = 1e5,
115 compression_level: int = 7,
116):
117 """
118 Encode and write a depth image as 16-bit PNG format.
119 ### Parameters:
120 - `path: Union[str, os.PathLike, IO]`
121 The file path or file object to write to.
122 - `depth: np.ndarray`
123 The depth array, float32 array of shape (H, W).
124 May contain `NaN` for invalid values and `Inf` for infinite values.
125 - `unit: float = None`
126 The unit of the depth values.
127
128 Depth values are encoded as follows:
129 - 0: unknown
130 - 1 ~ 65534: depth values in logarithmic
131 - 65535: infinity
132
133 metadata is stored in the PNG file as text fields:
134 - `near`: the minimum depth value
135 - `far`: the maximum depth value
136 - `unit`: the unit of the depth values (optional)
137 """
138 mask_values, mask_nan, mask_inf = np.isfinite(depth), np.isnan(depth),np.isinf(depth)
139
140 depth = depth.astype(np.float32)
141 mask_finite = depth
142 near = max(depth[mask_values].min(), 1e-5)
143 far = max(near * 1.1, min(depth[mask_values].max(), near * max_range))
144 depth = 1 + np.round((np.log(np.nan_to_num(depth, nan=0).clip(near, far) / near) / np.log(far / near)).clip(0, 1) * 65533).astype(np.uint16) # 1~65534
145 depth[mask_nan] = 0
146 depth[mask_inf] = 65535
147
148 pil_image = Image.fromarray(depth)
149 pnginfo = PngImagePlugin.PngInfo()
150 pnginfo.add_text('near', str(near))
151 pnginfo.add_text('far', str(far))
152 if unit is not None:
153 pnginfo.add_text('unit', str(unit))
154 pil_image.save(path, pnginfo=pnginfo, compress_level=compression_level)
155
156
157def read_segmentation(path: Union[str, os.PathLike, IO]) -> Tuple[np.ndarray, Dict[str, int]]:

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected