Spaces:
Running on Zero
Running on Zero
Release polish: shared depth colouring module, readable captions, CC BY-NC 4.0, visitor README
b655101 verified Download ldpt/utils/depth_image.py from pointcept-bot/L-DPT: direct link, hf CLI and curl.
- Browser
- Download file 8.96 kB
-
https://huggingface.co/spaces/pointcept-bot/L-DPT/resolve/main/ldpt/utils/depth_image.py
- Command line
-
hf download hf://spaces/pointcept-bot/L-DPT/ldpt/utils/depth_image.py
-
curl -L -o depth_image.py https://huggingface.co/spaces/pointcept-bot/L-DPT/resolve/main/ldpt/utils/depth_image.py
8.96 kB
| """ | |
| Depth as images, one convention for scripts/demo_depth.py, scripts/highres_infer.py and | |
| the demo (demo/hf_space): | |
| - colour: log depth stretched to its 1-99 % range, matplotlib "Spectral", near = warm | |
| (a photo's depth spans orders of magnitude: on a linear scale everything near shares | |
| one colour); | |
| - 16-bit: a grayscale PNG mapped linearly from the depth's minimum to its maximum, | |
| ``depth = lo + value / 65535 * (hi - lo)``, with lo / hi (and any metadata) as JSON in | |
| its tEXt chunk "l-dpt". | |
| from ldpt.utils.depth_image import colorize, write_depth16 | |
| rgb = colorize(depth) # HxW relative depth -> HxWx3 uint8 RGB | |
| info = write_depth16("d.png", depth) # {"lo": ..., "hi": ..., ...} | |
| Only numpy is imported here; matplotlib (the colormaps) and OpenCV (the PNG codec) are | |
| imported when used. Large maps are processed in blocks of CHUNK_PIXELS pixels: a 100 MP | |
| depth needs no full-size float copy. | |
| Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com) | |
| Please cite our work if the code is helpful to you. | |
| """ | |
| import functools | |
| import json | |
| import math | |
| import os | |
| import struct | |
| import zlib | |
| from pathlib import Path | |
| from typing import Any, Dict, Mapping, Optional, Tuple | |
| import numpy as np | |
| __all__ = [ | |
| "COLORMAPS", | |
| "DEPTH16_FORMAT", | |
| "DISPLAY_CMAP", | |
| "DISPLAY_PERCENTILES", | |
| "PNG_TEXT_KEY", | |
| "colorize", | |
| "colormap_lut", | |
| "decode_depth16", | |
| "depth16_png", | |
| "depth_range", | |
| "encode_depth16", | |
| "read_depth16", | |
| "write_depth16", | |
| ] | |
| # colormaps by name, each oriented so that near is warm / bright | |
| COLORMAPS: Dict[str, str] = { | |
| "Spectral": "Spectral", # near red, far blue | |
| "Turbo": "turbo_r", | |
| "Inferno": "inferno_r", | |
| "Gray": "gray_r", # near white | |
| } | |
| DISPLAY_CMAP = "Spectral" | |
| DISPLAY_PERCENTILES = (1.0, 99.0) | |
| CHUNK_PIXELS = 1 << 22 # pixels per block | |
| _LOG_FLOOR = 1e-12 | |
| # ---- colour | |
| def colormap_lut(cmap: str = DISPLAY_CMAP) -> np.ndarray: | |
| """[256, 3] uint8 RGB of a COLORMAPS entry (ValueError for another name).""" | |
| if cmap not in COLORMAPS: | |
| raise ValueError(f"unknown colormap {cmap!r}: one of {list(COLORMAPS)}") | |
| import matplotlib | |
| rgba = matplotlib.colormaps[COLORMAPS[cmap]](np.linspace(0.0, 1.0, 256)) | |
| lut = np.round(rgba[:, :3] * 255).astype(np.uint8) | |
| lut.setflags(write=False) | |
| return lut | |
| def depth_range( | |
| depth: np.ndarray, | |
| percentiles: Tuple[float, float] = DISPLAY_PERCENTILES, | |
| max_samples: int = CHUNK_PIXELS, | |
| *, | |
| log: bool = True, | |
| ) -> Tuple[float, float]: | |
| """Colour range (lo, hi): ``percentiles`` of the finite values of log(depth) (of | |
| depth with ``log=False``), on a strided sample of at most about ``max_samples`` | |
| values. A flat map gives (v, v + 1).""" | |
| flat = depth.reshape(-1) | |
| sample = flat[:: max(1, flat.size // max_samples)] | |
| if log: | |
| sample = np.log(np.maximum(sample.astype(np.float64), _LOG_FLOOR)) | |
| sample = sample[np.isfinite(sample)] | |
| if sample.size == 0: | |
| return 0.0, 1.0 | |
| lo, hi = (float(v) for v in np.percentile(sample, percentiles)) | |
| if not hi > lo: | |
| lo, hi = float(sample.min()), float(sample.max()) | |
| if not hi > lo: | |
| hi = lo + 1.0 | |
| return lo, hi | |
| def colorize( | |
| depth: np.ndarray, | |
| cmap: str = DISPLAY_CMAP, | |
| lo: Optional[float] = None, | |
| hi: Optional[float] = None, | |
| *, | |
| log: bool = True, | |
| percentiles: Tuple[float, float] = DISPLAY_PERCENTILES, | |
| bgr: bool = False, | |
| ) -> np.ndarray: | |
| """Relative depth (larger = farther) -> uint8 colour image, near = warm. | |
| The colours follow log(depth) (depth with ``log=False``) from ``lo`` to ``hi`` | |
| (values of that scale; default: depth_range at ``percentiles``); values outside | |
| clip, NaN and +inf take the far end. ``bgr`` writes the channels in OpenCV order. | |
| Shapes: | |
| depth: [H, W] -> [H, W, 3] uint8 | |
| """ | |
| lut = colormap_lut(cmap) | |
| if bgr: | |
| lut = lut[:, ::-1] | |
| if lo is None or hi is None: | |
| lo, hi = depth_range(depth, percentiles, log=log) | |
| scale = 255.0 / max(hi - lo, 1e-12) | |
| out = np.empty(depth.shape + (3,), np.uint8) | |
| rows = max(1, CHUNK_PIXELS // max(1, depth.shape[1])) | |
| for r in range(0, depth.shape[0], rows): | |
| x = depth[r : r + rows].astype(np.float32) | |
| if log: | |
| x = np.log(np.maximum(x, np.float32(_LOG_FLOOR))) | |
| x = (x - np.float32(lo)) * np.float32(scale) | |
| np.nan_to_num(x, copy=False, nan=255.0, posinf=255.0, neginf=0.0) | |
| out[r : r + rows] = lut[np.clip(x + 0.5, 0, 255).astype(np.uint8)] | |
| return out | |
| # ---- 16-bit PNG: depth = lo + value / 65535 * (hi - lo), lo / hi in a tEXt chunk | |
| DEPTH16_FORMAT = "l-dpt-depth16/1" | |
| PNG_TEXT_KEY = "l-dpt" | |
| _PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n" | |
| def encode_depth16(depth: np.ndarray) -> Tuple[np.ndarray, float, float]: | |
| """(uint16 map, lo, hi): linear from the minimum (0) to the maximum (65535), | |
| rounded. Finite depth only (ValueError). | |
| Shapes: | |
| depth: [H, W] -> [H, W] uint16 | |
| """ | |
| lo, hi = float(np.min(depth)), float(np.max(depth)) | |
| if not (math.isfinite(lo) and math.isfinite(hi)): | |
| raise ValueError("non-finite depth: the 16-bit PNG holds finite values only") | |
| out = np.empty(depth.shape, np.uint16) | |
| scale = 65535.0 / (hi - lo) if hi > lo else 0.0 | |
| rows = max(1, CHUNK_PIXELS // max(1, depth.shape[1])) | |
| for r in range(0, depth.shape[0], rows): | |
| x = (depth[r : r + rows].astype(np.float64) - lo) * scale | |
| out[r : r + rows] = np.clip(np.round(x), 0, 65535).astype(np.uint16) | |
| return out, lo, hi | |
| def decode_depth16(values: np.ndarray, lo: float, hi: float) -> np.ndarray: | |
| """Inverse of encode_depth16, up to half a level ((hi - lo) / 131070).""" | |
| return (lo + values.astype(np.float64) / 65535.0 * (hi - lo)).astype(np.float32) | |
| def png_text_chunk(key: str, text: str) -> bytes: | |
| data = key.encode("latin-1") + b"\0" + text.encode("latin-1") | |
| body = b"tEXt" + data | |
| return struct.pack(">I", len(data)) + body + struct.pack(">I", zlib.crc32(body)) | |
| def add_png_text(png: bytes, key: str, text: str) -> bytes: | |
| """``png`` with a tEXt chunk right after IHDR.""" | |
| if png[:8] != _PNG_SIGNATURE or png[12:16] != b"IHDR": | |
| raise ValueError("not a PNG stream") | |
| end = 8 + 12 + struct.unpack(">I", png[8:12])[0] | |
| return png[:end] + png_text_chunk(key, text) + png[end:] | |
| def png_texts(png: bytes) -> Dict[str, str]: | |
| """The tEXt chunks of a PNG stream before its image data (CRC checked).""" | |
| if png[:8] != _PNG_SIGNATURE: | |
| raise ValueError("not a PNG stream") | |
| texts, pos = {}, 8 | |
| while pos + 12 <= len(png): | |
| (length,) = struct.unpack(">I", png[pos : pos + 4]) | |
| kind = png[pos + 4 : pos + 8] | |
| data = png[pos + 8 : pos + 8 + length] | |
| (crc,) = struct.unpack(">I", png[pos + 8 + length : pos + 12 + length]) | |
| if kind == b"tEXt": | |
| if zlib.crc32(kind + data) != crc: | |
| raise ValueError("corrupt tEXt chunk") | |
| key, _, text = data.partition(b"\0") | |
| texts[key.decode("latin-1")] = text.decode("latin-1") | |
| if kind in (b"IDAT", b"IEND"): # our tEXt chunk comes before the data | |
| break | |
| pos += 12 + length | |
| return texts | |
| def depth16_png( | |
| depth: np.ndarray, meta: Optional[Mapping[str, Any]] = None | |
| ) -> Tuple[bytes, Dict[str, Any]]: | |
| """(PNG file bytes, info): the 16-bit grayscale PNG of ``depth`` and the JSON of its | |
| tEXt chunk "l-dpt" (format, lo, hi, the decoding formula, then ``meta``).""" | |
| import cv2 | |
| values, lo, hi = encode_depth16(depth) | |
| info = dict( | |
| format=DEPTH16_FORMAT, | |
| lo=lo, | |
| hi=hi, | |
| mapping="minmax", | |
| decode="depth = lo + value / 65535 * (hi - lo)", | |
| depth="relative depth, larger = farther, up to an affine map", | |
| ) | |
| info.update(meta or {}) | |
| ok, buf = cv2.imencode(".png", values, [cv2.IMWRITE_PNG_COMPRESSION, 1]) | |
| if not ok: | |
| raise RuntimeError("PNG encoding failed") | |
| text = json.dumps(info, ensure_ascii=True, sort_keys=True) | |
| return add_png_text(buf.tobytes(), PNG_TEXT_KEY, text), info | |
| def write_depth16( | |
| path: os.PathLike, depth: np.ndarray, meta: Optional[Mapping[str, Any]] = None | |
| ) -> Dict[str, Any]: | |
| """Write depth16_png(depth, meta) to ``path``; returns its info.""" | |
| data, info = depth16_png(depth, meta) | |
| Path(path).write_bytes(data) | |
| return info | |
| def read_depth16(path: os.PathLike) -> Tuple[np.ndarray, Dict[str, Any]]: | |
| """(float32 depth, info) of a write_depth16 file.""" | |
| import cv2 | |
| data = Path(path).read_bytes() | |
| info = json.loads(png_texts(data)[PNG_TEXT_KEY]) | |
| values = cv2.imdecode(np.frombuffer(data, np.uint8), cv2.IMREAD_UNCHANGED) | |
| if values is None or values.dtype != np.uint16 or values.ndim != 2: | |
| raise ValueError(f"{path} is not a 16-bit grayscale PNG") | |
| return decode_depth16(values, info["lo"], info["hi"]), info | |