File size: 20,642 Bytes
25450de | 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 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 | """HRDexDB dataset access for the aligned-render pipeline (no pybullet here).
Dataset: /home/wujiayir/robot_tools/HRDexDB (HF HRDexDB/HRDexDB, see ../README.md)
<emb>/<object>/<seq>/vid/<cam_id>.mp4 2048x1536, container 30 fps (real capture ~33 Hz), already undistorted
<emb>/<object>/<seq>/cam_param/intrinsics.json per cam: intrinsics_undistort (use), original_intrinsics, dist_params, width/height
<emb>/<object>/<seq>/cam_param/extrinsics.json per cam: 3x4 cam_from_world (static rig cameras)
<emb>/<object>/<seq>/cam_param/ego_calib.json human only: intrinsics + per-video-frame 3x4 cam_from_world of the head cams
<emb>/<object>/<seq>/C2R.npy 4x4 world_from_robot (official: cam_from_robot = ext @ C2R)
<emb>/<object>/<seq>/raw/{arm,hand,timestamps} robot only (see qpos_on_video_timeline)
<emb>/<object>/<seq>/hand/mano/%05d.obj human only: MANO hand mesh per video frame, world frame (778 V / 1538 F)
object_6d_pose_v2/<emb>/<object>_<seq>.npz frame_<k>: 4x4 world pose of assets/mesh_v2/<object>/<object>.obj for video frame k
Ego-rig cameras: 25452062 / 25452066 are the two head-mounted cameras in human episodes (per-frame extrinsics, 4.8 cm
baseline) and the same two devices mounted statically above the workspace in robot episodes (25452062 ~1.09 m above
the base looking down, 25452066 ~0.68 m, closer). They exist in every episode of every embodiment.
Conventions: all 4x4 are OpenCV camera frames (x right, y down, z forward). Video frame v (0-based) <-> raw/timestamps
frame_id v+1 (official load_video_frame: frame_pos = frame_id - 1) <-> object pose frame_v <-> mano %05d=v <-> ego ext %05d=v.
"""
import json
import os
import re
import xml.etree.ElementTree as ET
from functools import lru_cache
from pathlib import Path
import cv2
import numpy as np
DS_ROOT = Path("/home/wujiayir/robot_tools/HRDexDB")
ROOT = Path(__file__).resolve().parent.parent # hrdexdb_render
EGO_CAMS = ("25452062", "25452066")
W, H = 2048, 1536
FPS = 30.0 # container fps of every video (output videos use the same so frame k <-> frame k)
ROBOT_EMBODIMENTS = ("allegro_v5", "inspire_dftp", "inspire_f1", "robotiq_2f85")
EMBODIMENTS = ROBOT_EMBODIMENTS + ("human",)
URDF = {
"allegro_v5": DS_ROOT / "assets/robots/xarm_allegro_v5.urdf",
"inspire_dftp": DS_ROOT / "assets/robots/xarm_inspire_DFTP.urdf",
"inspire_f1": DS_ROOT / "assets/robots/xarm_inspire_f1_right.urdf",
"robotiq_2f85": DS_ROOT / "assets/robots/xarm_robotiq_2f85.urdf",
}
# official hrdexdb_contact_heatmaps/hrdexdb_io.py::load_robot_qpos default: arm_time_offset=0.09 s (arm states are
# stamped ~90 ms early w.r.t. the camera clock); hand_time_offset=0.0. Both are overridable via calib/hd_calib.json.
DEFAULT_DT = {"arm": 0.09, "hand": 0.0}
def load_npy(path):
"""float array from a .npy (the raw/ arrays are pickled object-dtype floats, like the official loader)."""
a = np.load(path, allow_pickle=True)
return np.asarray(a, dtype=float)
def _h(m):
m = np.asarray(m, dtype=float)
if m.shape == (3, 4):
return np.vstack([m, [0.0, 0.0, 0.0, 1.0]])
assert m.shape == (4, 4), m.shape
return m
# ---------------------------------------------------------------------------- episode listing
def list_episodes(embodiments=EMBODIMENTS, require_cams=EGO_CAMS):
"""Sorted 'emb/object/seq' of every episode dir that has vid/<cam>.mp4 for every cam in require_cams."""
out = []
for emb in embodiments:
d = DS_ROOT / emb
if not d.is_dir():
continue
for obj in sorted(os.listdir(d)):
od = d / obj
if not od.is_dir():
continue
for seq in sorted(os.listdir(od), key=lambda s: (len(s), s)):
ed = od / seq
if (ed / "vid").is_dir() and all((ed / "vid" / f"{c}.mp4").exists() for c in require_cams):
out.append(f"{emb}/{obj}/{seq}")
return out
# ---------------------------------------------------------------------------- hand signal -> URDF qpos (official formulas)
def inspire_action_to_qpos_dof6(a):
"""inspire_dftp hand/position.npy (0..1000 per finger) -> URDF [thumb_1, thumb_2, index_1, middle_1, ring_1, little_1]."""
a = np.asarray(a, dtype=float)
q = np.zeros((a.shape[0], 6))
q[:, 0] = 1.40 * (1.0 - a[:, 5] / 1000.0)
q[:, 1] = 0.60 * (1.0 - a[:, 4] / 1000.0)
for dst, src in ((2, 3), (3, 2), (4, 1), (5, 0)):
q[:, dst] = (-4e-8 * a[:, src] ** 3 + 3e-5 * a[:, src] ** 2 - 0.0704 * a[:, src] + 83.572) * np.pi / 180.0
return q
def inspire_f1_action_to_qpos_dof6(a):
"""inspire_f1 hand/right_joint_states.npy (raw servo units) -> URDF [thumb_1, thumb_2, index_1, middle_1, ring_1, little_1]."""
a = np.asarray(a, dtype=float)
q = np.zeros((a.shape[0], 6))
q[:, 0] = (1800.0 - a[:, 0]) * np.pi / 1800.0
q[:, 1] = (1350.0 - a[:, 1]) * np.pi / 1800.0
for i in range(2, 6):
q[:, i] = (1740.0 - a[:, i]) * np.pi / 1800.0
return q
HAND_SPEC = { # embodiment -> (data file candidates, time file candidates, converter, n_dof)
"allegro_v5": (("position.npy", "action.npy"), ("time.npy",), None, 16),
"inspire_dftp": (("position.npy", "action.npy"), ("time.npy",), inspire_action_to_qpos_dof6, 6),
"inspire_f1": (("right_joint_states.npy", "right_commands.npy"), ("right_joint_states_time.npy", "right_commands_time.npy"),
inspire_f1_action_to_qpos_dof6, 6),
"robotiq_2f85": (("position.npy",), ("time.npy",), None, 1), # radians of robotiq_85_left_knuckle_joint (0..0.8)
}
def resample(t_src, x_src, t_dst):
"""Per-column linear interpolation (clamped at both ends), x_src (N, D)."""
t_src = np.asarray(t_src, dtype=float).ravel()
x_src = np.asarray(x_src, dtype=float)
n = min(len(t_src), len(x_src))
t_src, x_src = t_src[:n], x_src[:n]
o = np.argsort(t_src, kind="stable")
t_src, x_src = t_src[o], x_src[o]
if n == 1:
return np.repeat(x_src[:1], len(t_dst), axis=0)
return np.stack([np.interp(t_dst, t_src, x_src[:, i]) for i in range(x_src.shape[1])], axis=1)
# ---------------------------------------------------------------------------- URDF joint order
@lru_cache(maxsize=None)
def urdf_joint_spec(urdf_path):
"""(actuated joint names in file order, {mimic_joint: (parent, multiplier, offset)}) from the URDF."""
root = ET.parse(str(urdf_path)).getroot()
actuated, mimic = [], {}
for j in root.findall("joint"):
if j.get("type") == "fixed":
continue
m = j.find("mimic")
if m is not None:
mimic[j.get("name")] = (m.get("joint"), float(m.get("multiplier") or 1.0), float(m.get("offset") or 0.0))
else:
actuated.append(j.get("name"))
return tuple(actuated), mimic
# ---------------------------------------------------------------------------- ego-camera override (uncalibrated sessions)
EGO_OVERRIDE_PATH = ROOT / "calib/ego_override.json"
_EGO_OVERRIDE = None
def load_ego_override(path=EGO_OVERRIDE_PATH):
global _EGO_OVERRIDE
if _EGO_OVERRIDE is None:
_EGO_OVERRIDE = json.load(open(path)) if Path(path).exists() else {}
return _EGO_OVERRIDE
SESSION_REFINE_PATH = ROOT / "calib/session_refine.json"
_SESSION_REFINE = None
def load_session_refine(path=SESSION_REFINE_PATH):
"""calib/session_refine.json: {"episodes": {rel: {cam: {"delta6": [x,y,z,rx,ry,rz], "dt_arm": s}}}} from merge_refine.py
(per-session camera-frame correction fitted against the real video: cam_from_world' = pose6_to_mat(delta6) @ cam_from_world)."""
global _SESSION_REFINE
if _SESSION_REFINE is None:
_SESSION_REFINE = json.load(open(path)) if Path(path).exists() else {}
return _SESSION_REFINE
def pose6_to_mat(pose6):
from scipy.spatial.transform import Rotation as R
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
# ---------------------------------------------------------------------------- episode
class Episode:
def __init__(self, rel):
self.rel = rel.strip("/")
self.emb, self.obj, self.seq = self.rel.split("/")
assert self.emb in EMBODIMENTS, self.emb
self.dir = DS_ROOT / self.rel
assert self.dir.is_dir(), self.dir
self.is_human = self.emb == "human"
self._cams = None
self._ego = None
# -- files -------------------------------------------------------------------------------
def video_path(self, cam):
return self.dir / "vid" / f"{cam}.mp4"
@property
def urdf(self):
return None if self.is_human else URDF[self.emb]
@property
def object_mesh(self):
p = DS_ROOT / "assets/mesh_v2" / self.obj / f"{self.obj}.obj"
return p if p.exists() else None
@property
def object_pose_file(self):
p = DS_ROOT / "object_6d_pose_v2" / self.emb / f"{self.obj}_{self.seq}.npz"
return p if p.exists() else None
def has_raw(self):
return (self.dir / "raw/timestamps/timestamp.npy").exists() and (self.dir / "raw/arm/position.npy").exists()
def grasp_success(self):
p = self.dir / "grasp_result.json"
if not p.exists():
return None
return json.load(open(p)).get("grasp_success")
# -- cameras ------------------------------------------------------------------------------
def C2R(self):
"""4x4 world_from_robot (identity if missing)."""
p = self.dir / "C2R.npy"
return _h(load_npy(p)) if p.exists() else np.eye(4)
def _load_cams(self):
if self._cams is not None:
return
intr = json.load(open(self.dir / "cam_param/intrinsics.json"))
extr = json.load(open(self.dir / "cam_param/extrinsics.json"))
cams = {}
for cid, pl in intr.items():
K = np.asarray(pl.get("intrinsics_undistort", pl.get("original_intrinsics")), dtype=float)
cams[cid] = dict(K=K, wh=(int(pl["width"]), int(pl["height"])), static=cid in extr,
ext=_h(extr[cid]) if cid in extr else None, dist_params=pl.get("dist_params"))
# ego-rig cameras without per-episode calibration (all inspire_f1 sessions, 3 robotiq episodes): calib/ego_override.json
# {"episodes": {rel: {cam: {"K": 3x3, "ext": 4x4 cam_from_world, "source": ...}}}} written by hd_fit_ego.py (see README)
ov = load_ego_override().get("episodes", {}).get(self.rel, {})
for cid, o in ov.items():
if cid not in cams or cams[cid]["ext"] is None:
cams[cid] = dict(K=np.asarray(o["K"], dtype=float), wh=(W, H), static=True, ext=_h(o["ext"]), dist_params=None,
override=o.get("source", "ego_override.json"))
for cid, rf in load_session_refine().get("episodes", {}).get(self.rel, {}).items():
if cid in cams and cams[cid]["ext"] is not None:
cams[cid]["ext_nominal"] = cams[cid]["ext"]
cams[cid]["ext"] = pose6_to_mat(rf["delta6"]) @ cams[cid]["ext"]
cams[cid]["refine"] = rf
ego = {}
pe = self.dir / "cam_param/ego_calib.json"
if pe.exists():
d = json.load(open(pe))
for cid, pl in d.get("intrinsics", {}).items():
K = np.asarray(pl.get("intrinsics_undistort", pl.get("original_intrinsics")), dtype=float)
frames = {int(k): _h(v) for k, v in d.get("extrinsics", {}).get(cid, {}).items()}
ego[cid] = dict(K=K, wh=(int(pl["width"]), int(pl["height"])), frames=frames)
cams.setdefault(cid, dict(K=K, wh=ego[cid]["wh"], static=False, ext=None, dist_params=pl.get("dist_params")))
self._cams, self._ego = cams, ego
def cam_ids(self):
self._load_cams()
return sorted(self._cams)
def K(self, cam):
self._load_cams()
if cam in self._ego:
return self._ego[cam]["K"]
return self._cams[cam]["K"]
def wh(self, cam):
self._load_cams()
return tuple(self._cams[cam]["wh"])
def calib_source(self, cam):
self._load_cams()
if cam in self._ego:
return "ego_calib.json"
c = self._cams.get(cam)
if c is None or c["ext"] is None:
return None
return c.get("override", "extrinsics.json")
def refine_info(self, cam):
self._load_cams()
return self._cams.get(cam, {}).get("refine")
def refined_dt_arm(self, cams=EGO_CAMS):
"""Session-refined arm time offset (mean over the given cams that have one) or None."""
self._load_cams()
v = [self._cams[c]["refine"]["dt_arm"] for c in cams if c in self._cams and self._cams[c].get("refine") and "dt_arm" in self._cams[c]["refine"]]
return float(np.mean(v)) if v else None
def cam_from_world_nominal(self, cam):
self._load_cams()
c = self._cams.get(cam, {})
return c.get("ext_nominal", c.get("ext"))
def is_ego_moving(self, cam):
self._load_cams()
return cam in self._ego
def cam_from_world(self, cam, frame=None):
"""4x4 cam_from_world; for moving ego cams the frame's extrinsic (nearest available frame id)."""
self._load_cams()
if cam in self._ego:
fr = self._ego[cam]["frames"]
if frame in fr:
return fr[frame]
keys = np.array(sorted(fr))
if frame is None:
return fr[int(keys[0])]
i = int(np.clip(np.searchsorted(keys, frame), 0, len(keys) - 1))
if i > 0 and abs(keys[i - 1] - frame) <= abs(keys[i] - frame):
i -= 1
return fr[int(keys[i])]
return self._cams[cam]["ext"]
def ego_frame_ids(self, cam):
self._load_cams()
return np.array(sorted(self._ego[cam]["frames"])) if cam in self._ego else None
def cam_from_robot(self, cam, frame=None):
return self.cam_from_world(cam, frame) @ self.C2R()
# -- video --------------------------------------------------------------------------------
def n_frames(self, cam):
cap = cv2.VideoCapture(str(self.video_path(cam)))
try:
return int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
finally:
cap.release()
def iter_frames(self, cam, start=0, stop=None):
"""Yields (v, bgr) sequentially decoded video frames v in [start, stop)."""
cap = cv2.VideoCapture(str(self.video_path(cam)))
try:
if not cap.isOpened():
raise IOError(f"cannot open {self.video_path(cam)}")
if start:
cap.set(cv2.CAP_PROP_POS_FRAMES, start)
v = start
while stop is None or v < stop:
ok, f = cap.read()
if not ok:
break
yield v, f
v += 1
finally:
cap.release()
# -- robot timeline -----------------------------------------------------------------------
def frame_times(self):
"""(timestamps, frame_ids 1-based) from raw/timestamps."""
ts = load_npy(self.dir / "raw/timestamps/timestamp.npy").ravel()
fid = np.asarray(np.load(self.dir / "raw/timestamps/frame_id.npy"), dtype=int).ravel()
n = min(len(ts), len(fid))
return ts[:n], fid[:n]
def video_times(self, n_video):
"""Capture time of video frames 0..n_video-1 (frame_id = v+1; dropped ids interpolated, ends extrapolated)."""
ts, fid = self.frame_times()
o = np.argsort(fid, kind="stable")
ts, fid = ts[o], fid[o]
dt = float(np.median(np.diff(ts))) if len(ts) > 1 else 1.0 / FPS
v = np.arange(n_video) + 1
t = np.interp(v, fid, ts)
t = np.where(v < fid[0], ts[0] - (fid[0] - v) * dt, t)
t = np.where(v > fid[-1], ts[-1] + (v - fid[-1]) * dt, t)
return t
def _series(self, d, data_cands, time_cands):
for f in data_cands:
p = self.dir / "raw" / d / f
if p.exists():
x = load_npy(p)
x = x.reshape(len(x), -1)
for tf in time_cands:
tp = self.dir / "raw" / d / tf
if tp.exists():
t = load_npy(tp).ravel()
n = min(len(t), len(x))
return x[:n], t[:n], f
raise FileNotFoundError(f"no time file for raw/{d}/{f} in {self.dir}")
raise FileNotFoundError(f"none of raw/{d}/{data_cands} in {self.dir}")
def qpos_on_video_timeline(self, n_video, dt_arm=None, dt_hand=None):
"""(qpos (n_video, 6+hand_dof) in URDF actuated-joint order, joint names, info).
State at video frame v = interpolation of the raw series at time video_times[v] - dt (dt: raw clock offset)."""
dt_arm = DEFAULT_DT["arm"] if dt_arm is None else float(dt_arm)
dt_hand = DEFAULT_DT["hand"] if dt_hand is None else float(dt_hand)
t_vid = self.video_times(n_video)
arm, t_arm, arm_file = self._series("arm", ("position.npy", "action_qpos.npy"), ("time.npy",))
dc, tc, conv, ndof = HAND_SPEC[self.emb]
hand, t_hand, hand_file = self._series("hand", dc, tc)
if conv is not None:
hand = conv(hand)
assert hand.shape[1] == ndof, (self.rel, hand.shape)
q_arm = resample(t_arm + dt_arm, arm[:, :6], t_vid)
q_hand = resample(t_hand + dt_hand, hand, t_vid)
names, _ = urdf_joint_spec(self.urdf)
assert len(names) == 6 + ndof, (names, ndof)
info = dict(arm_file=arm_file, hand_file=hand_file, dt_arm=dt_arm, dt_hand=dt_hand, arm_hz=float(1 / np.median(np.diff(t_arm))),
hand_hz=float(1 / np.median(np.diff(t_hand))), arm_span=[float(t_arm[0] - t_vid[0]), float(t_arm[-1] - t_vid[0])],
hand_span=[float(t_hand[0] - t_vid[0]), float(t_hand[-1] - t_vid[0])], video_span=[0.0, float(t_vid[-1] - t_vid[0])],
n_timestamps=int(len(self.frame_times()[0])))
return np.concatenate([q_arm, q_hand], axis=1), list(names), info
# -- object / hand geometry ---------------------------------------------------------------
def object_poses(self):
"""(n, 4, 4) world poses of the object mesh for video frames 0..n-1, or None."""
p = self.object_pose_file
if p is None:
return None
z = np.load(p)
keys = sorted(z.keys(), key=lambda k: int(k.split("_")[1]))
idx = [int(k.split("_")[1]) for k in keys]
assert idx == list(range(len(idx))), (p, idx[:5])
return np.stack([_h(z[k]) for k in keys])
def mano_files(self):
d = self.dir / "hand/mano"
return sorted(d.glob("*.obj")) if d.is_dir() else []
@staticmethod
def read_obj(path):
"""(V (n,3) float, F (m,3) int 0-based) from a simple OBJ (v / f lines, triangles)."""
V, F = [], []
with open(path) as fh:
for line in fh:
if line.startswith("v "):
V.append([float(x) for x in line.split()[1:4]])
elif line.startswith("f "):
F.append([int(x.split("/")[0]) - 1 for x in line.split()[1:4]])
return np.asarray(V, dtype=float), np.asarray(F, dtype=np.int32)
def __repr__(self):
return f"Episode({self.rel})"
if __name__ == "__main__":
import sys
eps = list_episodes()
import collections
print(len(eps), "episodes with both ego cams:", dict(collections.Counter(e.split("/")[0] for e in eps)))
for rel in sys.argv[1:]:
ep = Episode(rel)
n = ep.n_frames(EGO_CAMS[0])
print(ep, "frames", n, "cams", len(ep.cam_ids()), "object mesh", ep.object_mesh is not None, "poses", None if ep.object_poses() is None else ep.object_poses().shape,
"success", ep.grasp_success())
for c in EGO_CAMS:
print(" cam", c, "moving" if ep.is_ego_moving(c) else "static", "K", ep.K(c)[0, 0].round(1), ep.K(c)[:2, 2].round(1), "cam_from_world f0 t", ep.cam_from_world(c, 0)[:3, 3].round(3))
if not ep.is_human:
q, names, info = ep.qpos_on_video_timeline(n)
print(" qpos", q.shape, "names", names[:7], "...", "info", {k: (np.round(v, 3).tolist() if isinstance(v, (float, list)) else v) for k, v in info.items()})
else:
print(" mano files", len(ep.mano_files()))
|