File size: 12,315 Bytes
868a5eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Shared helpers for the DROID render-alignment pipeline.

Conventions
-----------
* pose6 = [x, y, z, rx, ry, rz] (metres / scipy euler 'xyz'), cam->base for extrinsics.
* K is a 3x3 pinhole matrix at the camera's NATIVE MP4 resolution (1280x720, or 672x376 for a
  few early wrist cameras).  Pixel (u, v) = (col, row) with the pixel CENTRE at integer coords.
* pybullet's ER_TINY_RENDERER samples every row one pixel too high with a plain OpenGL
  projection matrix (verified in out/diag/pixel_center*, scripts/diag/pixel_center_test.py and
  pixel_center_depthplane.py).  gl_projection_matrix(..., tiny_renderer=True) compensates with
  cy + TINY_RENDERER_ROW_BIAS (cx unchanged).  The compensation is OPT-IN: the default
  (tiny_renderer=None -> TINY_RENDERER_DEFAULT = False) returns the plain matrix, so scripts that
  add the +1 row themselves (scripts/diag/residual_analysis.py seg_render(fix_y=True),
  pixel_center_*.py, yshift_*.py, ...) are not double-shifted.  render_episode.RobotRenderer
  passes tiny_renderer=True explicitly; any other ER_TINY_RENDERER caller must do the same
  (scripts/refine_time_ext.py / refine_calib.py: together with scale_K, see DIAGNOSIS P0.2).
* Resolution changes must use scale_K (f' = f*s, c' = (c + 0.5)*s - 0.5), never K[:2] *= s.
"""
import functools
import hashlib
import json
from pathlib import Path

import numpy as np
from scipy.spatial.transform import Rotation as R

ROOT = Path(__file__).resolve().parent.parent

# OpenCV camera (x right, y down, z forward) -> OpenGL camera (x right, y up, z back)
CV2GL = np.diag([1.0, -1.0, -1.0, 1.0])

# rows TinyRenderer draws too high with a plain OpenGL projection (px, full res, any size)
TINY_RENDERER_ROW_BIAS = 1.0
TINY_RENDERER_COL_BIAS = 0.0
# value used by gl_projection_matrix when tiny_renderer is None.  False: plain matrix (legacy
# behaviour of every direct caller); a script may set dutils.TINY_RENDERER_DEFAULT = True to get
# the compensation for all of its own direct calls.
TINY_RENDERER_DEFAULT = False


def pose6_to_mat(pose6):
    """[x,y,z,rx,ry,rz] (scipy euler 'xyz') -> 4x4 homogeneous matrix."""
    m = np.eye(4)
    m[:3, :3] = R.from_euler("xyz", np.asarray(pose6, dtype=float)[3:6]).as_matrix()
    m[:3, 3] = np.asarray(pose6, dtype=float)[0:3]
    return m


def mat_to_pose6(T):
    """4x4 homogeneous matrix -> [x,y,z,rx,ry,rz] (scipy euler 'xyz'); inverse of pose6_to_mat."""
    T = np.asarray(T, dtype=float)
    return np.concatenate([T[:3, 3], R.from_matrix(T[:3, :3]).as_euler("xyz")])


def md5_file(path, chunk=1 << 20):
    """Hex md5 of a file's bytes."""
    h = hashlib.md5()
    with open(path, "rb") as f:
        while True:
            b = f.read(chunk)
            if not b:
                break
            h.update(b)
    return h.hexdigest()


def md5_json(obj):
    """Hex md5 of the canonical JSON form (sorted keys, compact separators) of a JSON-able object;
    numpy arrays / scalars are converted first.  Used as a content id for parameter sets that
    have no file (render_episode.mount_params_md5)."""
    def conv(o):
        if isinstance(o, dict):
            return {str(k): conv(v) for k, v in o.items()}
        if isinstance(o, np.ndarray):
            return [conv(v) for v in o.tolist()]
        if isinstance(o, (list, tuple)):
            return [conv(v) for v in o]
        if isinstance(o, bool):
            return o
        if isinstance(o, (int, float, np.floating, np.integer)):
            return float(o)  # 2 and 2.0 are the same value
        return o
    return hashlib.md5(json.dumps(conv(obj), sort_keys=True, separators=(",", ":")).encode()).hexdigest()


# --------------------------------------------------------------------------- calibration files

@functools.lru_cache(maxsize=4)
def _load_superset(path_str):
    return json.load(open(path_str))


@functools.lru_cache(maxsize=4)
def _load_intrinsics_compact(path_str):
    """intrinsics.json (125 MB) -> {uuid: {serial: (fx, cx, fy, cy, width, height)}} (tuples only, so
    the cached copy stays small); degenerate entries are kept as-is and filtered by _entry_ok."""
    raw = json.load(open(path_str))
    out = {}
    for u, cams in raw.items():
        d = {}
        for s, e in cams.items():
            cm = e.get("cameraMatrix") or [0.0, 0.0, 0.0, 0.0]
            if len(cm) < 4:
                cm = [0.0, 0.0, 0.0, 0.0]
            d[str(s)] = (float(cm[0]), float(cm[1]), float(cm[2]), float(cm[3]),
                         int(e.get("width") or 0), int(e.get("height") or 0))
        out[u] = d
    del raw
    return out


def _entry_ok(e):
    """A usable intrinsics entry: positive focal lengths and a known image size."""
    return (e is not None and np.isfinite(e[:4]).all() and e[0] > 0 and e[2] > 0
            and e[4] > 0 and e[5] > 0)


def _median_entry(vals, wh_pref=None):
    """Median of valid (fx,cx,fy,cy,w,h) tuples, restricted to ONE image size so that a serial
    re-used at two resolutions (ZED HD720 1280x720 vs VGA 672x376 are different crop/FOV modes,
    not a rescale) is not blended: the size wh_pref=(w,h) when entries of that size exist, else
    the dominant size.  Returns ((fx,cx,fy,cy,w,h), n_used)."""
    arr = np.array(vals, dtype=float)
    sizes, counts = np.unique(arr[:, 4:6], axis=0, return_counts=True)
    w, h = sizes[np.argmax(counts)]
    if wh_pref is not None:
        pw, ph = int(wh_pref[0]), int(wh_pref[1])
        if np.any((sizes[:, 0] == pw) & (sizes[:, 1] == ph)):
            w, h = pw, ph
    sel = arr[(arr[:, 4] == w) & (arr[:, 5] == h)]
    med = np.median(sel[:, :4], axis=0)
    return (float(med[0]), float(med[1]), float(med[2]), float(med[3]), int(w), int(h)), int(len(sel))


def load_calib_full(uuid, calib_dir=None, wh_hint=None):
    """Everything load_calib knows about an episode, as a dict:
         ext        {serial: cam2base pose6 (np.array[6])} from the superset ({} if the uuid is
                    not in the superset; see in_superset -- callers fall back to a v2 file / h5)
         ext_source {serial: 'GT' | 'Pred' | None}        superset <serial>_source
         ext_quality{serial: float | None}                superset <serial>_quality_metric
         in_superset bool
         K          {serial: 3x3} at native resolution (exterior + wrist)
         wh         {serial: (width, height)} native MP4 size of each camera
         K_source   {serial: 'own' | 'lab_median(n=..)' | 'global_median(n=..)'
                             [+ '|wh_mismatch(<w>x<h> requested)' when wh_hint could not be met]}
    Intrinsics entries that are missing, all-zero (fx == 0) or without an image size (width == 0)
    are replaced by the median over same-lab episodes that used the same serial (ZED intrinsics
    are per-camera hardware constants, fx std <= 0.23 px), then over all labs.  The median is
    taken over ONE image size: wh_hint[serial] = (w, h) (e.g. the real MP4 size) when such
    entries exist for that serial, else the dominant size; a fallback whose size differs from the
    hint is tagged 'wh_mismatch' (ZED VGA 672x376 is a different FOV mode, not a rescale of
    HD720; the caller must treat such a K as degraded).
    """
    calib_dir = Path(calib_dir) if calib_dir else ROOT / "calib"
    sup = _load_superset(str(calib_dir / "cam2base_extrinsic_superset.json"))
    intr = _load_intrinsics_compact(str(calib_dir / "intrinsics.json"))
    entry = sup.get(uuid)
    in_superset = entry is not None
    entry = entry or {}
    ext = {k: np.array(v, dtype=float) for k, v in entry.items() if k.isdigit()}
    ext_source = {k: entry.get(f"{k}_source") for k in ext}
    ext_quality = {k: entry.get(f"{k}_quality_metric") for k in ext}
    wh_hint = {str(k): (int(v[0]), int(v[1])) for k, v in (wh_hint or {}).items()}

    own = intr.get(uuid, {})
    wanted = list(ext) + [s for s in own if s not in ext] + [s for s in wh_hint if s not in ext and s not in own]
    meta_path = ROOT / "data" / uuid / "metadata.json"
    if meta_path.exists():
        try:
            meta = json.load(open(meta_path))
            for key in ("wrist_cam_serial", "ext1_cam_serial", "ext2_cam_serial"):
                ws = str(meta.get(key) or "")
                if ws.isdigit() and ws not in wanted:
                    wanted.append(ws)
        except (KeyError, ValueError, OSError):
            pass
    lab = uuid.split("+")[0]
    K, wh, K_source = {}, {}, {}
    for serial in wanted:
        e = own.get(serial)
        if _entry_ok(e):
            src = "own"
        else:
            vals = [v[serial] for u, v in intr.items()
                    if u.startswith(lab + "+") and serial in v and _entry_ok(v[serial])]
            tag = "lab_median"
            if not vals:
                vals = [v[serial] for v in intr.values() if serial in v and _entry_ok(v[serial])]
                tag = "global_median"
            if not vals:
                continue  # no usable intrinsics anywhere for this serial
            e, n = _median_entry(vals, wh_hint.get(serial))
            src = f"{tag}(n={n})"
            if serial in wh_hint and (int(e[4]), int(e[5])) != wh_hint[serial]:
                src += f"|wh_mismatch({wh_hint[serial][0]}x{wh_hint[serial][1]} requested)"
        fx, cx, fy, cy, w, h = e
        K[serial] = np.array([[fx, 0.0, cx], [0.0, fy, cy], [0.0, 0.0, 1.0]])
        wh[serial] = (int(w), int(h))
        K_source[serial] = src
    return dict(ext=ext, ext_source=ext_source, ext_quality=ext_quality, in_superset=in_superset,
                K=K, wh=wh, K_source=K_source)


def load_calib(uuid, calib_dir=None, with_size=False):
    """Return ({serial: cam2base 6d}, {serial: 3x3 K at native resolution}) for an episode.
    with_size=True additionally returns {serial: (width, height)}.  See load_calib_full."""
    c = load_calib_full(uuid, calib_dir)
    if with_size:
        return c["ext"], c["K"], c["wh"]
    return c["ext"], c["K"]


# --------------------------------------------------------------------------- intrinsics scaling

def scale_K(K, s_x, s_y=None):
    """Intrinsics for an image resampled by (s_x, s_y) with the pixel-centre convention used by
    cv2.resize / area sampling:  f' = f * s,  c' = (c + 0.5) * s - 0.5.
    (K[:2] *= s is WRONG by (s - 1)/2 px, i.e. -0.25 px at half resolution.)"""
    s_y = s_x if s_y is None else s_y
    K2 = np.array(K, dtype=float).copy()
    K2[0, 0] *= s_x
    K2[0, 1] *= s_x
    K2[1, 1] *= s_y
    K2[0, 2] = (K2[0, 2] + 0.5) * s_x - 0.5
    K2[1, 2] = (K2[1, 2] + 0.5) * s_y - 0.5
    return K2


def scale_K_to(K, wh_from, wh_to):
    """scale_K with the factors implied by two image sizes (w, h) -> (w', h')."""
    return scale_K(K, wh_to[0] / wh_from[0], wh_to[1] / wh_from[1])


# --------------------------------------------------------------------------- OpenGL matrices

def gl_view_matrix(T_base2cam):
    """Column-major OpenGL view matrix for pybullet from an OpenCV-style base->cam transform."""
    V = CV2GL @ T_base2cam
    return tuple(V.T.flatten())


def gl_projection_matrix(K, width, height, near=0.01, far=10.0, tiny_renderer=None):
    """Column-major OpenGL projection matrix from pinhole intrinsics (pixel origin top-left,
    pixel centres at integer coordinates).

    tiny_renderer=True compensates pybullet ER_TINY_RENDERER's rasterisation, which draws
    geometry TINY_RENDERER_ROW_BIAS (= 1) row too high: the principal point is shifted to cy + 1
    (cx unchanged).  render_episode.RobotRenderer passes True; every other ER_TINY_RENDERER
    caller must pass True itself.  tiny_renderer=None (default) uses the module flag
    TINY_RENDERER_DEFAULT (False = plain matrix, exact pixel-centre sampling / legacy behaviour),
    so scripts that add the +1 row to K themselves are not double-shifted.
    """
    if tiny_renderer is None:
        tiny_renderer = TINY_RENDERER_DEFAULT
    fx, fy = K[0, 0], K[1, 1]
    cx, cy = K[0, 2], K[1, 2]
    if tiny_renderer:
        cx = cx + TINY_RENDERER_COL_BIAS
        cy = cy + TINY_RENDERER_ROW_BIAS
    P = np.zeros((4, 4))
    P[0, 0] = 2 * fx / width
    P[0, 2] = 1.0 - 2 * cx / width
    P[1, 1] = 2 * fy / height
    P[1, 2] = 2 * cy / height - 1.0
    P[2, 2] = -(far + near) / (far - near)
    P[2, 3] = -2 * far * near / (far - near)
    P[3, 2] = -1.0
    return tuple(P.T.flatten())