Download eval/source/robot_tools/droid/scripts/refine_time_ext.py from JiayiWuLeo/RobotZero: direct link, hf CLI and curl.
- Browser
- Download file 4.19 kB
-
https://huggingface.co/datasets/JiayiWuLeo/RobotZero/resolve/main/eval/source/robot_tools/droid/scripts/refine_time_ext.py
- Command line
-
hf download hf://datasets/JiayiWuLeo/RobotZero/eval/source/robot_tools/droid/scripts/refine_time_ext.py
-
curl -L -o refine_time_ext.py https://huggingface.co/datasets/JiayiWuLeo/RobotZero/resolve/main/eval/source/robot_tools/droid/scripts/refine_time_ext.py
4.19 kB
| """Refine (a) a global time offset for camera capture timestamps and (b) a | |
| per-exterior-camera 6DoF extrinsic correction, by minimizing the chamfer | |
| distance from rendered robot silhouette edges to real image edges. | |
| Writes <episode_dir>/calib_refined.json, which EpisodeSession auto-loads. | |
| Usage: python refine_time_ext.py <episode_dir> | |
| """ | |
| import json | |
| import sys | |
| from pathlib import Path | |
| import cv2 | |
| import numpy as np | |
| import pybullet as p | |
| from scipy.optimize import minimize | |
| from dutils import gl_projection_matrix, gl_view_matrix, pose6_to_mat | |
| from render_episode import EpisodeSession, W, H | |
| RW, RH = 640, 360 | |
| CLIP = 25.0 # px, robustness clip for chamfer | |
| def robot_edges(sess, serial, T_base2cam, scale): | |
| Ks = sess.K[serial].copy() | |
| Ks[:2] *= scale | |
| V = gl_view_matrix(T_base2cam) | |
| P = gl_projection_matrix(Ks, RW, RH) | |
| _, _, _, _, seg = p.getCameraImage(RW, RH, viewMatrix=V, projectionMatrix=P, | |
| renderer=p.ER_TINY_RENDERER, | |
| flags=p.ER_SEGMENTATION_MASK_OBJECT_AND_LINKINDEX) | |
| mask = (np.asarray(seg).reshape(RH, RW) >= 0).astype(np.uint8) * 255 | |
| return cv2.morphologyEx(mask, cv2.MORPH_GRADIENT, np.ones((3, 3), np.uint8)) > 0 | |
| def main(ep_dir): | |
| sess = EpisodeSession(ep_dir, wrist=False) | |
| scale = RW / W | |
| ext_serials = [s for s in sess.serials] | |
| # sample steps weighted toward motion | |
| dq = np.abs(np.diff(sess.qs, axis=0)).max(axis=1) | |
| order = np.argsort(dq) | |
| steps = sorted(set(order[-14:].tolist() + list(np.linspace(5, sess.n - 5, 10).astype(int)))) | |
| steps = [s for s in steps if 2 <= s < sess.n - 3] | |
| # distance transforms of real image edges | |
| dts = {} | |
| for serial in ext_serials: | |
| cap = cv2.VideoCapture(str(sess.ep_dir / f"recordings/MP4/{serial}.mp4")) | |
| for s in steps: | |
| cap.set(cv2.CAP_PROP_POS_FRAMES, int(s)) | |
| ok, fr = cap.read() | |
| g = cv2.cvtColor(cv2.resize(fr, (RW, RH)), cv2.COLOR_BGR2GRAY) | |
| edges = cv2.Canny(g, 40, 120) | |
| dts[(serial, s)] = cv2.distanceTransform(255 - edges, cv2.DIST_L2, 3) | |
| cap.release() | |
| def chamfer(serial, s, delta_ms, D=np.eye(4)): | |
| q, g = sess.state_at(sess.cap_ts[serial][s] + delta_ms) | |
| sess.rr.set_state(q, g) | |
| e = robot_edges(sess, serial, D @ sess.T_ext[serial], scale) | |
| if e.sum() < 300: | |
| return CLIP | |
| return float(np.minimum(dts[(serial, s)][e], CLIP).mean()) | |
| # ---- stage A: global time offset ---- | |
| print("time-offset sweep (mean chamfer px over", len(steps), "steps x 2 cams):") | |
| best = (1e9, 0.0) | |
| for delta in np.arange(-150, 151, 25): | |
| c = np.mean([chamfer(serial, s, delta) for serial in ext_serials for s in steps]) | |
| print(f" delta {delta:+6.0f} ms -> {c:.3f}") | |
| if c < best[0]: | |
| best = (c, float(delta)) | |
| # local refine around best | |
| for delta in best[1] + np.array([-15, -10, -5, 5, 10, 15]): | |
| c = np.mean([chamfer(serial, s, delta) for serial in ext_serials for s in steps]) | |
| if c < best[0]: | |
| best = (c, float(delta)) | |
| delta_ms = best[1] | |
| print(f"BEST TIME OFFSET: {delta_ms:+.0f} ms (chamfer {best[0]:.3f})") | |
| # ---- stage B: per-camera extrinsic delta (camera frame) ---- | |
| ext_delta = {} | |
| for serial in ext_serials: | |
| def score(x): | |
| D = pose6_to_mat(x) | |
| return np.mean([chamfer(serial, s, delta_ms, D) for s in steps]) | |
| c0 = score(np.zeros(6)) | |
| res = minimize(score, np.zeros(6), method="Nelder-Mead", | |
| options={"xatol": 2e-4, "fatol": 1e-3, "maxiter": 220}) | |
| print(f"cam {serial}: chamfer {c0:.3f} -> {res.fun:.3f}") | |
| print(f" EXT_DELTA[{serial}] = [{', '.join(f'{v:.5f}' for v in res.x)}]") | |
| ext_delta[serial] = [float(v) for v in res.x] | |
| out = Path(ep_dir) / "calib_refined.json" | |
| tmp = out.with_suffix(".json.tmp") | |
| json.dump({"time_offset_ms": delta_ms, "ext_delta": ext_delta}, open(tmp, "w"), indent=1) | |
| tmp.rename(out) # atomic: never leave a truncated file if killed mid-write | |
| print("wrote", out) | |
| if __name__ == "__main__": | |
| main(sys.argv[1]) | |