File size: 12,829 Bytes
3e56913
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
"""Two-frame monocular 3D detection samples from SimLingo logs (stage-2 perception).

Each sample is the front image at frame t and at t-1 (0.25 s earlier, the 4 Hz log interval), the
ego motion between them, and CenterNet-style targets for the ground-truth boxes of frame t
(dataloader.detection_labels). Box coordinates are in SimLingo's ego frame, whose origin is the
ego bounding-box centre; the camera sits at (-1.5, 0, 2.0) relative to the actor origin on the
ground, i.e. CAMERA_Z above the box-frame origin.
"""
import glob
import hashlib
import math
import zlib
from pathlib import Path

import numpy as np
import torch
from PIL import Image
from torch.utils.data import Dataset
from torchvision.io import ImageReadMode, decode_jpeg, read_file

from dataloader.detection_labels import (
    EGO_SPEED, EGO_X, EGO_Y, EGO_YAW, OBJ_BANK_VISIBLE, OBJ_CLASS, OBJ_HALF_H, OBJ_HALF_L, OBJ_HALF_W,
    OBJ_LIDAR_POINTS, OBJ_SPEED, OBJ_X, OBJ_Y, OBJ_YAW, OBJ_Z,
)
from dataloader.object_bank import CLASS_CAR, CLASS_WALKER, NUM_CLASSES, normalize_angle

IMAGE_W, IMAGE_H = 896, 448  # model input (the 1024x512 log images resized, same 110 degree FOV)
FOV_DEG = 110.0
FOCAL = IMAGE_W / (2.0 * math.tan(math.radians(FOV_DEG / 2.0)))
CAMERA_X = -1.5
CAMERA_Z = 2.0 - 0.745  # camera height above the box-frame origin (half height of the MKZ ego)
STRIDE = 8
GRID_W, GRID_H = IMAGE_W // STRIDE, IMAGE_H // STRIDE
MAX_TARGETS = 64
# per-target regression layout
(T_OFF_U, T_OFF_V, T_LOG_DEPTH, T_LOG_L, T_LOG_W, T_LOG_H, T_SIN, T_COS, T_VX, T_VY) = range(10)
TARGET_DIM = 10


def ego_to_camera(xyz):
    """Box-frame points [..., 3] -> camera frame (forward, right, up)."""
    xyz = np.asarray(xyz, dtype=np.float64)
    return np.stack((xyz[..., 0] - CAMERA_X, xyz[..., 1], xyz[..., 2] - CAMERA_Z), -1)


def project(cam):
    """Camera-frame points [..., 3] (forward > 0) -> pixels [..., 2] in the model image."""
    return np.stack((IMAGE_W / 2 + FOCAL * cam[..., 1] / cam[..., 0],
                     IMAGE_H / 2 - FOCAL * cam[..., 2] / cam[..., 0]), -1)


def box_corners(rows):
    """[N, OBJ_DIM] -> box-frame corners [N, 8, 3]."""
    signs = np.array([[sx, sy, sz] for sx in (-1, 1) for sy in (-1, 1) for sz in (-1, 1)], dtype=np.float64)
    ext = rows[:, [OBJ_HALF_L, OBJ_HALF_W, OBJ_HALF_H]].astype(np.float64)
    local = signs[None] * ext[:, None]
    c, s = np.cos(rows[:, OBJ_YAW]), np.sin(rows[:, OBJ_YAW])
    x = c[:, None] * local[..., 0] - s[:, None] * local[..., 1] + rows[:, None, OBJ_X]
    y = s[:, None] * local[..., 0] + c[:, None] * local[..., 1] + rows[:, None, OBJ_Y]
    return np.stack((x, y, local[..., 2] + rows[:, None, OBJ_Z]), -1)


def gaussian_radius(height, width, min_overlap=0.7):
    """CenterNet's radius for which a shifted box keeps IoU >= min_overlap (in grid cells)."""
    a1, b1 = 1, height + width
    c1 = width * height * (1 - min_overlap) / (1 + min_overlap)
    r1 = (b1 + np.sqrt(b1 ** 2 - 4 * a1 * c1)) / 2
    a2, b2 = 4, 2 * (height + width)
    c2 = (1 - min_overlap) * width * height
    r2 = (b2 + np.sqrt(b2 ** 2 - 4 * a2 * c2)) / 2
    a3, b3 = 4 * min_overlap, -2 * min_overlap * (height + width)
    c3 = (min_overlap - 1) * width * height
    r3 = (b3 + np.sqrt(b3 ** 2 - 4 * a3 * c3)) / 2
    return min(r1, r2, r3)


def draw_gaussian(heatmap, cx, cy, radius):
    radius = max(0, int(radius))
    sigma = (2 * radius + 1) / 6.0
    ys, xs = np.ogrid[-radius:radius + 1, -radius:radius + 1]
    g = np.exp(-(xs * xs + ys * ys) / (2 * sigma * sigma))
    h, w = heatmap.shape
    left, right = min(cx, radius), min(w - cx, radius + 1)
    top, bottom = min(cy, radius), min(h - cy, radius + 1)
    if right <= -left or bottom <= -top:
        return
    region = heatmap[cy - top:cy + bottom, cx - left:cx + right]
    np.maximum(region, g[radius - top:radius + bottom, radius - left:radius + right], out=region)


def is_positive(rows, max_range, min_lidar_points=1):
    """Boxes the detector must find: pass the bank's visibility test, are in range and were hit by
    the lidar (the bank's BEV test does not know about buildings, terrain or fog-free sight lines)."""
    dist = np.hypot(rows[:, OBJ_X] - CAMERA_X, rows[:, OBJ_Y])
    return (rows[:, OBJ_BANK_VISIBLE] > 0.5) & (dist <= max_range) & (rows[:, OBJ_LIDAR_POINTS] >= min_lidar_points)


def build_targets(rows, max_range, min_lidar_points=1):
    """CenterNet targets for one frame.

    rows: [N, OBJ_DIM] labels of frame t. Positives see is_positive; every other labelled box only
    switches off the negative loss around its centre, since whether it is visible is uncertain.
    """
    heatmap = np.zeros((NUM_CLASSES, GRID_H, GRID_W), dtype=np.float32)
    ignore = np.zeros((GRID_H, GRID_W), dtype=np.float32)
    index = np.zeros(MAX_TARGETS, dtype=np.int64)
    cls = np.zeros(MAX_TARGETS, dtype=np.int64)
    target = np.zeros((MAX_TARGETS, TARGET_DIM), dtype=np.float32)
    mask = np.zeros(MAX_TARGETS, dtype=np.float32)
    if len(rows) == 0:
        return heatmap, ignore, index, cls, target, mask
    centre = ego_to_camera(rows[:, [OBJ_X, OBJ_Y, OBJ_Z]])
    corners = ego_to_camera(box_corners(rows))
    positives = is_positive(rows, max_range, min_lidar_points)
    k = 0
    for i in range(len(rows)):
        if centre[i, 0] < 1.0:
            continue
        uv = project(centre[i])
        cu, cv = uv[0] / STRIDE, uv[1] / STRIDE
        if not (0 <= cu < GRID_W and 0 <= cv < GRID_H):
            continue
        front = corners[i][corners[i][:, 0] > 0.3]
        if len(front) < 2:
            continue
        box_uv = project(front)
        bw = (np.clip(box_uv[:, 0].max(), 0, IMAGE_W) - np.clip(box_uv[:, 0].min(), 0, IMAGE_W)) / STRIDE
        bh = (np.clip(box_uv[:, 1].max(), 0, IMAGE_H) - np.clip(box_uv[:, 1].min(), 0, IMAGE_H)) / STRIDE
        radius = max(0.0, gaussian_radius(max(bh, 1e-3), max(bw, 1e-3)))
        ix, iy = int(cu), int(cv)
        if not positives[i]:
            draw_gaussian(ignore, ix, iy, max(radius, 1.0))
            continue
        c = int(rows[i, OBJ_CLASS])
        draw_gaussian(heatmap[c], ix, iy, radius)
        if k >= MAX_TARGETS:
            continue
        yaw = float(rows[i, OBJ_YAW])
        alpha = normalize_angle(yaw - math.atan2(centre[i, 1], centre[i, 0]))
        speed = float(rows[i, OBJ_SPEED])
        index[k] = iy * GRID_W + ix
        cls[k] = c
        target[k] = (cu - ix, cv - iy, math.log(centre[i, 0]),
                     math.log(rows[i, OBJ_HALF_L]), math.log(rows[i, OBJ_HALF_W]), math.log(rows[i, OBJ_HALF_H]),
                     math.sin(alpha), math.cos(alpha), speed * math.cos(yaw), speed * math.sin(yaw))
        mask[k] = 1.0
        k += 1
    # a positive's own peak must not be switched off by an overlapping ignored box
    ignore = np.where(heatmap.max(0) > 0.0, 0.0, ignore)
    return heatmap, ignore, index, cls, target, mask


def ego_motion(ego_prev, ego_now):
    """Previous ego pose in the current ego frame (dx forward, dy right, dyaw) and current speed."""
    dxw, dyw = ego_prev[EGO_X] - ego_now[EGO_X], ego_prev[EGO_Y] - ego_now[EGO_Y]
    c, s = math.cos(ego_now[EGO_YAW]), math.sin(ego_now[EGO_YAW])
    return np.array((c * dxw + s * dyw, -s * dxw + c * dyw,
                     normalize_angle(float(ego_prev[EGO_YAW] - ego_now[EGO_YAW])), ego_now[EGO_SPEED]),
                    dtype=np.float32)


def _route_flags(label_file):
    with np.load(label_file) as z:
        objects, count = z["objects"], z["count"]
    flags = np.zeros((len(count), 2), dtype=np.uint8)
    for f in range(len(count)):
        rows = objects[f, :count[f]]
        pos = is_positive(rows, 50.0)
        flags[f, 0] = min(255, int((pos & (rows[:, OBJ_CLASS] == CLASS_WALKER)).sum()))
        flags[f, 1] = min(255, int((pos & (rows[:, OBJ_CLASS] == CLASS_CAR) & (rows[:, OBJ_SPEED] > 1.0)).sum()))
    return flags


def build_frame_flags(data_root="simlingo_data", workers=64):
    """Per-frame [walker positives, moving-car positives] counts for every route, cached once in
    detection_labels/frame_flags.npz (used for sampling weights)."""
    from multiprocessing import Pool
    data_root = Path(data_root).resolve()
    files = sorted(glob.glob(str(data_root / "detection_labels/simlingo/*/*/*/Town*/labels.npz")))
    with Pool(workers) as pool:
        flags = pool.map(_route_flags, files, chunksize=8)
    rel = [str(Path(f).parent.relative_to(data_root / "detection_labels")) for f in files]
    lengths = np.array([len(x) for x in flags])
    np.savez(data_root / "detection_labels/frame_flags.npz", routes=np.array(rel), lengths=lengths,
             flags=np.concatenate(flags))


def route_split(route_dir, val_mod=50):
    """Deterministic route-level split: about 1/val_mod of the routes are validation."""
    return "val" if zlib.crc32(str(route_dir).encode()) % val_mod == 0 else "train"


def route_fold(route_dir, num_folds):
    """Deterministic cross-fitting fold of a route (md5: crc32 is affine, so it would correlate with route_split)."""
    return int(hashlib.md5(str(route_dir).encode()).hexdigest(), 16) % num_folds


def load_image(path):
    try:
        return decode_jpeg(read_file(path), mode=ImageReadMode.RGB)
    except RuntimeError:
        return torch.from_numpy(np.asarray(Image.open(path).convert("RGB"))).permute(2, 0, 1).contiguous()


class DetectionDataset(Dataset):
    """(image_t, image_t-1, ego motion, targets) over every SimLingo route of one split."""

    def __init__(self, data_root="simlingo_data", split="train", max_range=50.0, min_lidar_points=1,
                 frame_stride=1, route_filter=None, val_mod=50):
        self.data_root = Path(data_root).resolve()
        self.max_range = float(max_range)
        self.min_lidar_points = int(min_lidar_points)
        label_files = sorted(glob.glob(str(self.data_root / "detection_labels/simlingo/*/*/*/Town*/labels.npz")))
        routes, index = [], []
        for lf in label_files:
            route_dir = Path(lf).parent
            rel = route_dir.relative_to(self.data_root / "detection_labels")
            if route_split(rel, val_mod) != split:
                continue
            if route_filter is not None and not route_filter(str(rel)):
                continue
            with np.load(lf) as z:
                n = len(z["count"])
            r = len(routes)
            routes.append((str(self.data_root / "data" / rel), lf))
            index.extend((r, f) for f in range(1, n, frame_stride))
        self.routes = routes
        self.index = np.asarray(index, dtype=np.int32).reshape(-1, 2)
        self._cache = {}

    def __len__(self):
        return len(self.index)

    def _labels(self, r):
        if r not in self._cache:
            if len(self._cache) > 64:
                self._cache.clear()
            with np.load(self.routes[r][1]) as z:
                self._cache[r] = (z["objects"], z["count"], z["ego"])
        return self._cache[r]

    def __getitem__(self, i):
        r, f = (int(v) for v in self.index[i])
        route_dir = self.routes[r][0]
        objects, count, ego = self._labels(r)
        rows = objects[f, :count[f]]
        heatmap, ignore, index, cls, target, mask = build_targets(rows, self.max_range, self.min_lidar_points)
        return dict(
            image=load_image(f"{route_dir}/rgb/{f:04d}.jpg"),
            image_prev=load_image(f"{route_dir}/rgb/{f - 1:04d}.jpg"),
            ego_motion=torch.from_numpy(ego_motion(ego[f - 1], ego[f])),
            heatmap=torch.from_numpy(heatmap), ignore=torch.from_numpy(ignore),
            index=torch.from_numpy(index), cls=torch.from_numpy(cls),
            target=torch.from_numpy(target), mask=torch.from_numpy(mask),
            sample=torch.tensor((r, f), dtype=torch.int32),
        )

    def sample_weights(self, walker_weight=5.0, moving_weight=2.0):
        """Per-sample weights that oversample frames with walkers and with moving cars (needs
        build_frame_flags)."""
        with np.load(self.data_root / "detection_labels/frame_flags.npz") as z:
            starts = np.concatenate(([0], np.cumsum(z["lengths"])[:-1]))
            where = {r: (s, n) for r, s, n in zip(z["routes"], starts, z["lengths"])}
            flags = z["flags"]
        per_route = []
        for route_dir, _ in self.routes:
            s, n = where[str(Path(route_dir).relative_to(self.data_root / "data"))]
            per_route.append(flags[s:s + n])
        f = np.stack([per_route[r][i] for r, i in self.index]).astype(np.float64)
        return 1.0 + (walker_weight - 1.0) * (f[:, 0] > 0) + (moving_weight - 1.0) * (f[:, 1] > 0)

    def gt_rows(self, i):
        """Raw ground-truth rows of sample i (for evaluation)."""
        r, f = (int(v) for v in self.index[i])
        objects, count, _ = self._labels(r)
        return objects[f, :count[f]]