File size: 7,099 Bytes
7fedee6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# SPDX-License-Identifier: Apache-2.0
"""The shipped samples and their CPU references (host tool, needs onnxruntime and OpenCV 4.11):

    python -m tt_visionpilot.tools.make_samples --weights DIR --out code/tt_visionpilot/samples

``synthetic_road_<k>.png`` (k = 0, 1): a procedurally drawn 1920 x 1080 road scene (sky, a two-lane road with dashed
markings curving slightly, two cars seen from behind, one in the ego lane, one in the right lane), generated here from a fixed seed: no third-party data,
Apache-2.0. Frame 1 is frame 0 with the cars 1.5 % larger (a pair for AutoDrive). Next to them,
``synthetic_road.<net>.reference.json``: the ``/predict`` body of the fp32 onnxruntime reference of the published
file on the same request (VisionPilot's pre-processing; AutoDrive with the 50 deg centre crop of a 54 deg camera as
homography), which the smoke test compares the served body with.
"""
from __future__ import annotations

import argparse
import json
import os
from pathlib import Path

import numpy as np

from ..host.prep import center_crop_homography, front_image, warped_image
from ..models import IMAGENET_MEAN, IMAGENET_STD
from ..outputs import AutoDriveOutput, AutoSpeedOutput, AutoSteerOutput, autospeed_decode

W, H = 1920, 1080
HFOV = 54.0


def car(img: np.ndarray, cx: int, bottom: int, w: int, body) -> None:
    """A car seen from behind: shadow, tyres, body, cabin, rear window, tail lights, plate, bumper."""
    import cv2

    h = int(w * 0.75)
    x0, y0 = cx - w // 2, bottom - h
    P = lambda fx, fy: (x0 + int(w * fx), y0 + int(h * fy))
    cv2.ellipse(img, (cx, bottom + 4), (int(w * 0.55), int(w * 0.06)), 0, 0, 360, (30, 30, 30), -1)
    cv2.rectangle(img, P(0.05, 0.82), (x0 + int(w * 0.22), bottom + 2), (15, 15, 15), -1)
    cv2.rectangle(img, P(0.78, 0.82), (x0 + int(w * 0.95), bottom + 2), (15, 15, 15), -1)
    cv2.rectangle(img, P(0.0, 0.40), P(1.0, 0.90), body, -1)
    cv2.fillPoly(img, [np.array([P(0.12, 0.40), P(0.22, 0.0), P(0.78, 0.0), P(0.88, 0.40)], np.int32)], body)
    cv2.fillPoly(img, [np.array([P(0.18, 0.37), P(0.26, 0.06), P(0.74, 0.06), P(0.82, 0.37)], np.int32)], (60, 70, 80))
    cv2.rectangle(img, P(0.03, 0.48), P(0.20, 0.60), (200, 30, 30), -1)
    cv2.rectangle(img, P(0.80, 0.48), P(0.97, 0.60), (200, 30, 30), -1)
    cv2.rectangle(img, P(0.37, 0.66), P(0.63, 0.76), (235, 235, 235), -1)
    cv2.rectangle(img, P(0.0, 0.86), P(1.0, 0.92), (25, 25, 25), -1)


def draw(k: int) -> np.ndarray:
    """Synthetic RGB uint8 road scene, frame k."""
    import cv2

    rng = np.random.default_rng(1234)
    img = np.zeros((H, W, 3), np.uint8)
    horizon = 540
    for y in range(horizon):                                       # sky gradient
        t = y / horizon
        img[y] = (np.array([120, 170, 230]) * (1 - t) + np.array([200, 215, 230]) * t).astype(np.uint8)
    img[horizon:] = (95, 110, 70)                                   # grass
    vp = (W // 2 + 40, horizon)                                     # vanishing point, slightly right: gentle curve
    road = np.array([[vp[0] - 30, horizon], [vp[0] + 30, horizon], [W - 80, H], [80, H]], np.int32)
    cv2.fillPoly(img, [road], (80, 80, 85))
    noise = rng.integers(-8, 9, (H - horizon, W, 1))
    img[horizon:] = np.clip(img[horizon:].astype(np.int16) + noise, 0, 255).astype(np.uint8)
    for x_bottom, dashed in ((140, False), (W // 2 + 20, True), (W - 140, False)):
        for i in range(40):
            if dashed and i % 2:
                continue
            t0, t1 = i / 40, (i + 1) / 40
            p0 = (int(vp[0] + (x_bottom - vp[0]) * t0 ** 1.0), int(horizon + (H - horizon) * t0))
            p1 = (int(vp[0] + (x_bottom - vp[0]) * t1 ** 1.0), int(horizon + (H - horizon) * t1))
            cv2.line(img, p0, p1, (235, 235, 235), max(1, int(14 * t1)))
    scale = 1.0 + 0.015 * k
    car(img, W // 2 - 40, 820, int(260 * scale), (150, 150, 155))       # ahead, in the ego lane
    car(img, 1130, 700, int(130 * scale), (40, 60, 140))                 # further ahead, right lane
    return img


def net_input(rgb: np.ndarray, imagenet: bool) -> np.ndarray:
    x = rgb.astype(np.float32) * np.float32(1.0 / 255.0)
    if imagenet:
        x = (x - np.asarray(IMAGENET_MEAN, np.float32)) / np.asarray(IMAGENET_STD, np.float32)
    return np.ascontiguousarray(x.transpose(2, 0, 1)[None])


def main(argv=None) -> int:
    import cv2
    import onnxruntime as ort

    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument("--weights", required=True)
    ap.add_argument("--out", required=True)
    args = ap.parse_args(argv)
    out = Path(args.out)
    out.mkdir(parents=True, exist_ok=True)
    frames = [draw(k) for k in range(2)]
    for k, f in enumerate(frames):
        cv2.imwrite(str(out / f"synthetic_road_{k}.png"), cv2.cvtColor(f, cv2.COLOR_RGB2BGR))
    # read back what the server will decode (PNG is lossless, so these are the same arrays)
    so = ort.SessionOptions()
    so.intra_op_num_threads = int(os.environ.get("VP_THREADS", "4"))
    sess = lambda n: ort.InferenceSession(str(Path(args.weights) / f"{n}_fp32.onnx"), so,
                                          providers=["CPUExecutionProvider"])
    img, geom = front_image(frames[1])
    a, b = sess("autosteer").run(None, {"input": net_input(img, False)})
    body = AutoSteerOutput(a, b, model="auto_steer-p150", frame_id="front", meta={"geometry": geom}).to_dict()
    (out / "synthetic_road.autosteer.reference.json").write_text(json.dumps(body, indent=1))
    (o,) = sess("autospeed").run(None, {"input": net_input(img, False)})
    bx, sc, cl, cp = autospeed_decode(o)
    body = AutoSpeedOutput(bx, sc, cl, cp, geometry=geom, model="auto_speed-p150", frame_id="front").to_dict()
    (out / "synthetic_road.autospeed.reference.json").write_text(json.dumps(body, indent=1))
    Hm = center_crop_homography(W, H, HFOV)
    d, c, fl = sess("autodrive").run(None, {"image_prev": net_input(warped_image(frames[0], Hm), True),
                                            "image_curr": net_input(warped_image(frames[1], Hm), True)})
    body = AutoDriveOutput(d.ravel()[0], c.ravel()[0], fl.ravel()[0], model="auto_drive-p150").to_dict()
    body["homography"] = Hm.ravel().tolist()
    (out / "synthetic_road.autodrive.reference.json").write_text(json.dumps(body, indent=1))
    (out / "README.md").write_text(
        "# Samples\n\n`synthetic_road_0.png`, `synthetic_road_1.png`: procedurally drawn 1920x1080 road scenes "
        "(`tools/make_samples.py`, fixed seed; no third-party data; Apache-2.0). `synthetic_road.<net>.reference.json`: "
        "the `/predict` body of the fp32 onnxruntime reference of the published ONNX file on the same request "
        "(AutoSteer / AutoSpeed: frame 1; AutoDrive: frames 0, 1 with the homography stored in the file), "
        f"opencv {cv2.__version__}, onnxruntime {ort.__version__}.\n")
    print("samples written to", out, "| autospeed detections:", len(sc), "| autodrive", body["distance_m"],
          body["flag_prob"])
    return 0


if __name__ == "__main__":
    raise SystemExit(main())