Download code/tt_visionpilot/outputs.py from changh95/auto_steer-p150: direct link, hf CLI and curl.
- Browser
- Download file 6.88 kB
-
https://huggingface.co/changh95/auto_steer-p150/resolve/main/code/tt_visionpilot/outputs.py
- Command line
-
hf download hf://changh95/auto_steer-p150/code/tt_visionpilot/outputs.py
-
curl -L -o outputs.py https://huggingface.co/changh95/auto_steer-p150/resolve/main/code/tt_visionpilot/outputs.py
6.88 kB
| # SPDX-License-Identifier: Apache-2.0 | |
| """Outputs of the three networks, decoded as VisionPilot's C++ decodes them (``modules/models/src``): | |
| - AutoSteer: ``xp`` and ``h_vector``, the two [64] outputs as they come (``auto_steer.cpp``); | |
| - AutoSpeed: per anchor ``cx, cy, w, h`` and the class with the highest ``1 / (1 + exp(-p))`` of the four class | |
| outputs ``p``, kept when that is at least ``conf_threshold`` (0.6), then greedy NMS at IoU ``iou_threshold`` | |
| (0.45) (``auto_speed.cpp post_process`` / ``nms``). The ONNX file's class outputs are already sigmoid | |
| probabilities, so VisionPilot's rule keeps ``p >= 0.405`` and reports scores in [0.5, 0.731]; it is reproduced as | |
| is (the raw probabilities are in ``class_prob``). Boxes are in network pixels (1024 x 512) and, with the | |
| geometry of the top-crop / resize, in the input frame (``box_xyxy_input``); | |
| - AutoDrive: ``dist_normalized``, ``curvature_raw``, ``flag_prob = sigmoid(flag_logit)`` (``auto_drive.cpp``), plus | |
| ``distance_m = 150 * (1 - dist_normalized)`` (``longitudinal_fusion.cpp``) and ``curvature_per_m = 0.21 * | |
| curvature_raw`` (``CURV_SCALE`` of ``load_data_auto_drive.py``). | |
| """ | |
| from __future__ import annotations | |
| from typing import Any, Dict, List, Optional | |
| import numpy as np | |
| from .ttaw.io import to_jsonable | |
| D_MAX_M = 150.0 | |
| CURV_SCALE = 0.21 | |
| def _envelope(model: str, frame_id: str, meta: dict, timing_ms: dict) -> Dict[str, Any]: | |
| return {"model": model, "frame_id": frame_id, "meta": to_jsonable(meta), "timing_ms": to_jsonable(timing_ms)} | |
| class AutoSteerOutput: | |
| def __init__(self, xp: np.ndarray, h_vector: np.ndarray, *, model: str, frame_id: str = "camera", | |
| meta: Optional[dict] = None): | |
| self.xp = np.asarray(xp, np.float32).reshape(-1) | |
| self.h_vector = np.asarray(h_vector, np.float32).reshape(-1) | |
| self.model, self.frame_id, self.meta, self.timing_ms = model, frame_id, dict(meta or {}), {} | |
| def to_dict(self, output_format: str = "json") -> Dict[str, Any]: | |
| d = _envelope(self.model, self.frame_id, self.meta, self.timing_ms) | |
| d.update({"xp": self.xp.tolist(), "h_vector": self.h_vector.tolist()}) | |
| return d | |
| def autospeed_decode(output: np.ndarray, conf_threshold: float = 0.6, iou_threshold: float = 0.45): | |
| """``output`` [1, 4 + K, N] -> (boxes xyxy [M, 4], scores [M], class ids [M], class_prob [M, K]) in VisionPilot's | |
| order (score-descending NMS keep order).""" | |
| o = np.asarray(output, np.float32).reshape(output.shape[-2], output.shape[-1]) | |
| cx, cy, w, h = o[0], o[1], o[2], o[3] | |
| probs = o[4:] | |
| with np.errstate(over="ignore"): | |
| s = (1.0 / (1.0 + np.exp(-probs))).astype(np.float32) # VisionPilot's sigmoid on the class outputs | |
| best = np.argmax(s, axis=0) | |
| score = s[best, np.arange(s.shape[1])] | |
| keep = np.nonzero(score >= np.float32(conf_threshold))[0] | |
| boxes = np.stack([cx - w * 0.5, cy - h * 0.5, cx + w * 0.5, cy + h * 0.5], axis=1)[keep] | |
| sc, cl, cp = score[keep], best[keep], probs[:, keep].T | |
| order = np.argsort(-sc, kind="stable") | |
| boxes, sc, cl, cp = boxes[order], sc[order], cl[order], cp[order] | |
| area = (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1]) | |
| suppressed = np.zeros(len(sc), bool) | |
| out: List[int] = [] | |
| for i in range(len(sc)): | |
| if suppressed[i]: | |
| continue | |
| out.append(i) | |
| ix1 = np.maximum(boxes[i, 0], boxes[i + 1:, 0]) | |
| iy1 = np.maximum(boxes[i, 1], boxes[i + 1:, 1]) | |
| ix2 = np.minimum(boxes[i, 2], boxes[i + 1:, 2]) | |
| iy2 = np.minimum(boxes[i, 3], boxes[i + 1:, 3]) | |
| inter = np.maximum(0.0, ix2 - ix1) * np.maximum(0.0, iy2 - iy1) | |
| iou = inter / (area[i] + area[i + 1:] - inter + np.float32(1e-6)) | |
| suppressed[i + 1:] |= iou > iou_threshold | |
| k = np.asarray(out, np.int64) | |
| return boxes[k], sc[k], cl[k], cp[k] | |
| class AutoSpeedOutput: | |
| LABELS = ("class_0", "class_1", "class_2", "class_3") | |
| def __init__(self, boxes: np.ndarray, scores: np.ndarray, class_ids: np.ndarray, class_prob: np.ndarray, *, | |
| geometry: dict, model: str, frame_id: str = "camera", meta: Optional[dict] = None): | |
| self.boxes = np.asarray(boxes, np.float32).reshape(-1, 4) | |
| self.scores = np.asarray(scores, np.float32).reshape(-1) | |
| self.class_ids = np.asarray(class_ids, np.int64).reshape(-1) | |
| self.class_prob = np.asarray(class_prob, np.float32).reshape(len(self.scores), len(self.LABELS)) | |
| self.geometry = geometry | |
| self.model, self.frame_id, self.meta, self.timing_ms = model, frame_id, dict(meta or {}), {} | |
| def boxes_input(self) -> np.ndarray: | |
| g = self.geometry | |
| b = self.boxes.astype(np.float64).copy() | |
| b[:, [0, 2]] *= g["scale_x"] | |
| b[:, [1, 3]] = b[:, [1, 3]] * g["scale_y"] + g["crop_top"] | |
| return b | |
| def to_dict(self, output_format: str = "json") -> Dict[str, Any]: | |
| d = _envelope(self.model, self.frame_id, dict(self.meta, geometry=self.geometry), self.timing_ms) | |
| bi = self.boxes_input() | |
| d["detections"] = [{"class_id": int(c), "score": float(s), "box_xyxy": [float(v) for v in b], | |
| "box_xyxy_input": [float(v) for v in bb], "class_prob": [float(v) for v in p]} | |
| for b, bb, s, c, p in zip(self.boxes, bi, self.scores, self.class_ids, self.class_prob)] | |
| d["num_detections"] = len(self.scores) | |
| return d | |
| class AutoDriveOutput: | |
| """``ready`` is False for the first frame of a stream (one image per call): VisionPilot also returns nothing | |
| until it has two frames; every value is then None.""" | |
| def __init__(self, distance: Optional[float], curvature: Optional[float], flag_logit: Optional[float], *, | |
| model: str, frame_id: str = "camera", meta: Optional[dict] = None): | |
| self.ready = distance is not None | |
| self.dist_normalized = None if distance is None else float(distance) | |
| self.curvature_raw = None if curvature is None else float(curvature) | |
| self.flag_logit = None if flag_logit is None else float(flag_logit) | |
| self.flag_prob = None if flag_logit is None else float(1.0 / (1.0 + np.exp(-np.float32(flag_logit)))) | |
| self.model, self.frame_id, self.meta, self.timing_ms = model, frame_id, dict(meta or {}), {} | |
| def to_dict(self, output_format: str = "json") -> Dict[str, Any]: | |
| d = _envelope(self.model, self.frame_id, self.meta, self.timing_ms) | |
| r = self.ready | |
| d.update({"ready": r, "dist_normalized": self.dist_normalized, | |
| "distance_m": D_MAX_M * (1.0 - self.dist_normalized) if r else None, | |
| "curvature_raw": self.curvature_raw, | |
| "curvature_per_m": CURV_SCALE * self.curvature_raw if r else None, | |
| "flag_logit": self.flag_logit, "flag_prob": self.flag_prob}) | |
| return d | |