#!/usr/bin/env python3 """Render the three RGB views, exact uint16 depth, and both tactile surfaces.""" from __future__ import annotations import argparse from pathlib import Path import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np RGB_KEYS = ( ("observation.images.cam_front", "Front RGB"), ("observation.images.cam_side", "Side RGB"), ("observation.images.cam_fisheye", "Fisheye RGB"), ) def lerobot_dataset_class(): try: from lerobot.datasets.lerobot_dataset import LeRobotDataset except ModuleNotFoundError: from lerobot.common.datasets.lerobot_dataset import LeRobotDataset return LeRobotDataset def to_numpy(value: object) -> np.ndarray: if hasattr(value, "detach"): value = value.detach().cpu().numpy() return np.asarray(value) def rgb_hwc(value: object) -> np.ndarray: image = to_numpy(value) if image.ndim != 3: raise ValueError(f"expected RGB rank 3, got {image.shape}") if image.shape[0] in (1, 3, 4) and image.shape[-1] not in (1, 3, 4): image = np.moveaxis(image, 0, -1) if image.shape[-1] == 4: image = image[..., :3] if np.issubdtype(image.dtype, np.integer): image = image.astype(np.float32) / 255.0 return np.clip(image, 0.0, 1.0) def exact_depth_uint16(value: object) -> np.ndarray: depth = np.ascontiguousarray(np.squeeze(to_numpy(value))) if depth.ndim != 2: raise ValueError(f"expected depth HW/HW1/1HW, got {depth.shape}") if depth.dtype == np.int16: return depth.view(np.uint16) if depth.dtype == np.uint16: return depth if np.issubdtype(depth.dtype, np.floating) and float(np.nanmax(depth)) <= 1.0: raise TypeError( "depth was normalized to [0,1]; exact millimetres are unavailable from " "this loader version. Read the PNG bytes from data/*.parquet instead." ) return depth.astype(np.uint16, copy=False) def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--repo-id", default="Tachintech/TacRich-Manip") parser.add_argument("--revision", default="main") parser.add_argument("--root", type=Path, help="Optional existing local dataset root") parser.add_argument("--episode-index", type=int, default=0) parser.add_argument("--frame-index", type=int, help="Episode-local frame; default is the midpoint") parser.add_argument("--video-backend", default="pyav") parser.add_argument("--depth-max-mm", type=float, default=2000.0) parser.add_argument("--tactile-vmax", type=float, help="Shared tactile upper limit; default uses current-frame max") parser.add_argument("--output", type=Path, default=Path("episode_preview.png")) return parser.parse_args() def main() -> None: args = parse_args() dataset = lerobot_dataset_class()( repo_id=args.repo_id, root=args.root, revision=args.revision, episodes=[args.episode_index], video_backend=args.video_backend, ) frame_index = len(dataset) // 2 if args.frame_index is None else args.frame_index if not 0 <= frame_index < len(dataset): raise IndexError(f"frame {frame_index} outside [0, {len(dataset) - 1}]") if args.depth_max_mm <= 0: raise ValueError("--depth-max-mm must be positive") sample = dataset[frame_index] depth = exact_depth_uint16(sample["observation.depth.cam_front"]) tactile = to_numpy(sample["observation.tactile"]).astype(np.float32) if tactile.shape[0] != 2: raise ValueError(f"expected tactile [2,H,W], got {tactile.shape}") tactile_vmax = args.tactile_vmax if tactile_vmax is None: tactile_vmax = max(float(np.nanmax(tactile)), 1.0e-6) figure, axes = plt.subplots(2, 3, figsize=(16, 9), constrained_layout=True) for axis, (key, title) in zip(axes[0], RGB_KEYS, strict=True): axis.imshow(rgb_hwc(sample[key]), interpolation="nearest") axis.set_title(title) axis.axis("off") depth_artist = axes[1, 0].imshow( depth, cmap="cividis", vmin=0.0, vmax=args.depth_max_mm, interpolation="nearest" ) axes[1, 0].set_title("Front depth (lossless uint16)") axes[1, 0].axis("off") figure.colorbar(depth_artist, ax=axes[1, 0], label="millimetres", fraction=0.046) tactile_artists = [] for axis, values, title in zip( axes[1, 1:], tactile, ("Left tactile", "Right tactile"), strict=True ): tactile_artists.append(axis.imshow( values, cmap="magma", vmin=0.0, vmax=tactile_vmax, interpolation="nearest", aspect="auto" )) axis.set_title(title) axis.set_xlabel("sensor column") axis.set_ylabel("sensor row") figure.colorbar( tactile_artists[-1], ax=list(axes[1, 1:]), label="calibrated response", fraction=0.023 ) state_tip = to_numpy(sample["observation.state_gripper"]) action_tip = to_numpy(sample["action_gripper"]) relative_time = float(to_numpy(sample["timestamp"]).reshape(-1)[0]) figure.suptitle( f"multiple tasks | episode {args.episode_index} | frame {frame_index} | " f"t={relative_time:.3f}s\n" f"tip xyz={np.array2string(state_tip[:3], precision=4)} m | " f"target xyz={np.array2string(action_tip[:3], precision=4)} m" ) args.output.parent.mkdir(parents=True, exist_ok=True) figure.savefig(args.output, dpi=140, facecolor="white") plt.close(figure) print(args.output.resolve()) if __name__ == "__main__": main()