Download code/tt_meteor2/host/inputs.py from changh95/METEOR-2-p150: direct link, hf CLI and curl.
- Browser
- Download file 7.69 kB
-
https://huggingface.co/changh95/METEOR-2-p150/resolve/main/code/tt_meteor2/host/inputs.py
- Command line
-
hf download hf://changh95/METEOR-2-p150/code/tt_meteor2/host/inputs.py
-
curl -L -o inputs.py https://huggingface.co/changh95/METEOR-2-p150/resolve/main/code/tt_meteor2/host/inputs.py
7.69 kB
| # SPDX-License-Identifier: Apache-2.0 | |
| """Request -> network inputs of METEOR 2 (numpy + OpenCV; no device). | |
| - ``images``: the eight cameras (``reference.config.CAMERAS``), raw RGB frames of any size with the network's aspect | |
| ratio 16:9; each is brought to 1152 x 648 the way tier4/METEOR's pipeline does (``bevlane/dataset.py``): the 0..1 | |
| float image resized with ``cv2.INTER_CUBIC`` when enlarging (``INTER_AREA`` when shrinking), rounded and clipped to | |
| uint8; its intrinsics rows 0 and 1 scaled by the same factor; | |
| - ``calibration``: per camera ``intrinsics`` (of the image as sent) and ``T_ref_from_camera`` (camera optical frame | |
| -> ego / base_link); T_cam_ego = inv(float32 T_ref_from_camera) as upstream. The NPU form ignores them (its rig is | |
| in the weights); the Gather form needs them; | |
| - ``ego_speed`` (m/s, the graph's v0), ``acc`` (m/s^2, past samples only), ``ego_hist`` [32] (8 rows x (speed / 10, | |
| acceleration / 3, yaw rate / 0.5, curvature / 0.1), newest first) and ``route`` [13] (6 points / 10 + flag), as | |
| the caller computes them (tt-autoware ``scripts/autoware/meteor2_lib.py``); absent ones are zeros, as the model | |
| card allows ("rows without history are zeros", "all zeros = no route"). | |
| The cameras go straight into the stem's space-to-depth uint8 buffer (``tt.model.s2d_camera_u8``), one thread per | |
| camera. | |
| """ | |
| from __future__ import annotations | |
| from dataclasses import dataclass, field | |
| from typing import Any, Dict, Mapping, Optional, Sequence | |
| import numpy as np | |
| from .. import io as tio | |
| from ..reference import config as C | |
| __all__ = ["Meteor2Frame", "prepare_request", "resize_camera", "ego_vector"] | |
| class Meteor2Frame: | |
| img: np.ndarray # uint8 [1, 1, 8*327*579, 12] (the device input) | |
| K: Optional[np.ndarray] # [8, 3, 3] at 1152 x 648 (None without calibration) | |
| T_cam_ego: Optional[np.ndarray] # [8, 4, 4] | |
| v0: float | |
| acc: float | |
| ego_hist: np.ndarray # [32] | |
| route: np.ndarray # [13] | |
| meta: Dict[str, Any] = field(default_factory=dict) | |
| def resize_camera(img: np.ndarray, mode: str = "fast") -> np.ndarray: | |
| """RGB uint8 [h, w, 3] -> [648, 1152, 3] (unchanged when already that size). ``exact``: upstream's rule on the 0..1 | |
| float image (``cv2.INTER_CUBIC`` when enlarging, ``INTER_AREA`` when shrinking), rounded to the graph's uint8 | |
| input (4.1 ms per 768x432 camera here); ``fast``: the same interpolation on the uint8 image (OpenCV's fixed-point | |
| path, 0.2 ms), which differs from ``exact`` by 1 grey level on 0.016 % of the pixels of the TIER IV demo frames.""" | |
| h, w = img.shape[:2] | |
| if (h, w) == (C.IMG_H, C.IMG_W): | |
| return np.ascontiguousarray(img, np.uint8) | |
| if abs(C.IMG_W / w - C.IMG_H / h) > 1e-6: | |
| raise tio.InputError(f"camera image {w}x{h} does not scale uniformly to {C.IMG_W}x{C.IMG_H} (16:9)") | |
| import cv2 | |
| interp = cv2.INTER_CUBIC if w < C.IMG_W else cv2.INTER_AREA | |
| if mode == "fast": | |
| return cv2.resize(np.ascontiguousarray(img, np.uint8), (C.IMG_W, C.IMG_H), interpolation=interp) | |
| f = cv2.resize(img.astype(np.float32) / np.float32(255.0), (C.IMG_W, C.IMG_H), interpolation=interp) | |
| return np.clip(np.rint(f * np.float32(255.0)), 0, 255).astype(np.uint8) | |
| def ego_vector(value: Any, n: int, name: str) -> np.ndarray: | |
| if value is None: | |
| return np.zeros(n, np.float32) | |
| try: | |
| a = np.asarray(value, np.float32).reshape(-1) | |
| except (TypeError, ValueError): | |
| raise tio.InputError(f"{name} must be {n} numbers") from None | |
| if a.size != n or not np.all(np.isfinite(a)): | |
| raise tio.InputError(f"{name} must be {n} finite numbers, got {a.size}") | |
| return a | |
| def _scalar(value: Any, name: str, default: Optional[float] = None) -> float: | |
| if value is None: | |
| if default is None: | |
| raise tio.InputError(f"this model needs {name!r}") | |
| return float(default) | |
| try: | |
| v = float(value) | |
| except (TypeError, ValueError): | |
| raise tio.InputError(f"{name} must be a number, got {value!r}") from None | |
| if not np.isfinite(v): | |
| raise tio.InputError(f"{name} must be finite") | |
| return v | |
| def load_cameras_parallel(images: Any, calibration: Any, need_calibration: bool, calib_dir=None, pool=None) -> list: | |
| """``ttaw.io.load_cameras`` with the per-camera decoding (file / bytes / base64 -> RGB) on ``pool``; the same | |
| checks and camera order. CameraImage entries (the server's decoded request) pass through unchanged.""" | |
| if pool is None or images is None: | |
| return tio.load_cameras(images, calibration, order=C.CAMERAS, require_calibration=need_calibration, | |
| calib_dir=calib_dir) | |
| calib = tio.resolve_calibration(calibration, calib_dir) if calibration is not None else None | |
| if isinstance(images, Mapping) and not ({"camera", "image", "path", "data"} & set(images)): | |
| entries = [(str(k), v) for k, v in images.items()] | |
| else: | |
| entries = [(None, v) for v in (list(images) if isinstance(images, (list, tuple)) else [images])] | |
| cams = list(pool.map(lambda kv: tio.load_camera(kv[1], name=kv[0], calibration=calib, | |
| require_calibration=need_calibration), entries)) | |
| names = [c.name for c in cams] | |
| missing = [n for n in C.CAMERAS if n not in names] | |
| extra = [n for n in names if n not in C.CAMERAS] | |
| if missing or extra or len(set(names)) != len(names): | |
| raise tio.InputError(f"cameras must be exactly {list(C.CAMERAS)} once each; missing {missing}, " | |
| f"unexpected {extra}") | |
| by = {c.name: c for c in cams} | |
| return [by[n] for n in C.CAMERAS] | |
| def prepare_request(images: Any, calibration: Optional[Mapping[str, Any]], *, ego_speed: Any, acc: Any = None, | |
| ego_hist: Any = None, route: Any = None, need_calibration: bool = True, buffer=None, pool=None, | |
| calib_dir=None, resize: str = "fast") -> Meteor2Frame: | |
| from ..tt.model import S2D_H, S2D_W, s2d_camera_u8 | |
| v0 = _scalar(ego_speed, "ego_speed") | |
| a = _scalar(acc, "acc", 0.0) | |
| hist = ego_vector(ego_hist, C.EGO_HIST, "ego_hist") | |
| rt = ego_vector(route, C.ROUTE, "route") | |
| if images is None: | |
| raise tio.InputError("this model takes the eight camera images 'images'") | |
| cams = load_cameras_parallel(images, calibration, need_calibration, calib_dir, pool) | |
| if buffer is None: | |
| buffer = np.empty((1, 1, C.N_CAM * S2D_H * S2D_W, 12), np.uint8) | |
| per = buffer.reshape(C.N_CAM, S2D_H, S2D_W, 12) | |
| sizes = [tuple(c.image.shape[:2]) for c in cams] | |
| def one(i: int) -> None: | |
| s2d_camera_u8(resize_camera(cams[i].image, resize), per[i]) | |
| if pool is not None: | |
| list(pool.map(one, range(C.N_CAM))) | |
| else: | |
| for i in range(C.N_CAM): | |
| one(i) | |
| K = T = None | |
| if all(c.intrinsics is not None and c.T_ref_from_camera is not None for c in cams): | |
| K = np.zeros((C.N_CAM, 3, 3), np.float32) | |
| T = np.zeros((C.N_CAM, 4, 4), np.float32) | |
| for i, c in enumerate(cams): | |
| s = np.float32(C.IMG_W / sizes[i][1]) | |
| k = np.asarray(c.intrinsics, np.float32).copy() | |
| k[:2] *= s | |
| K[i] = k | |
| T[i] = np.linalg.inv(np.asarray(c.T_ref_from_camera, np.float32)).astype(np.float32) | |
| elif need_calibration: | |
| raise tio.InputError("the gather form needs intrinsics and T_ref_from_camera for every camera") | |
| return Meteor2Frame(buffer, K, T, v0, a, hist, rt, {"cameras": [c.name for c in cams], | |
| "input_hw": sorted(set(sizes))}) | |