{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "dc974867-4bae-468f-b203-f9e5534271b8", "metadata": {}, "outputs": [], "source": [ "# pip install jupyter lerobot matplotlib scipy\n", "import cv2\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "from scipy.spatial.transform import Rotation as Rt\n", "from lerobot.datasets.lerobot_dataset import LeRobotDataset" ] }, { "cell_type": "code", "execution_count": 2, "id": "0a3317e1-47fe-44de-a6b2-3d6af804eb07", "metadata": {}, "outputs": [], "source": [ "# helper for printing sample features\n", "def extract_feature_info(feature):\n", " if feature is None:\n", " return {\"dtype\": None, \"shape\": None, \"names\": None}\n", "\n", " get = feature.get if isinstance(feature, dict) else getattr\n", "\n", " dtype = get(\"dtype\", None) if isinstance(feature, dict) else getattr(feature, \"dtype\", None)\n", " shape = get(\"shape\", None) if isinstance(feature, dict) else getattr(feature, \"shape\", None)\n", " names = get(\"names\", None) if isinstance(feature, dict) else getattr(feature, \"names\", None)\n", "\n", " if isinstance(names, dict) and \"motors\" in names:\n", " names = names[\"motors\"]\n", "\n", " return {\"dtype\": dtype, \"shape\": shape, \"names\": names}\n", "\n", "def feature_info_to_string(info: dict) -> str:\n", " dtype = info.get(\"dtype\")\n", " shape = info.get(\"shape\")\n", " names = info.get(\"names\")\n", "\n", " lines = []\n", " lines.append(f\"dtype: {dtype}\")\n", " lines.append(f\"shape: {shape}\")\n", "\n", " if names is None:\n", " pass\n", " elif isinstance(names, list):\n", " preview = \", \".join(map(str, names[:10]))\n", " suffix = f\" ... (+{len(names)-10})\" if len(names) > 10 else \"\"\n", " lines.append(f\"names: [{preview}]{suffix}\")\n", " elif isinstance(names, dict):\n", " parts = []\n", " for k, v in names.items():\n", " if isinstance(v, list):\n", " pv = \", \".join(map(str, v[:6]))\n", " suf = f\" ... (+{len(v)-6})\" if len(v) > 6 else \"\"\n", " parts.append(f\"{k}=[{pv}]{suf}\")\n", " else:\n", " parts.append(f\"{k}={v}\")\n", " lines.append(\"names: {\" + \", \".join(parts) + \"}\")\n", " else:\n", " lines.append(f\"names: {names}\")\n", "\n", " return \"\\n\".join(lines)\n", "\n", "# changes eef coordinate system to x:right, y:down, z:forward, this is only a matter of preference\n", "ROTATE_EEF = np.array([[np.cos(np.deg2rad(90)), np.sin(np.deg2rad(90)), 0.0],[-np.sin(np.deg2rad(90)), np.cos(np.deg2rad(90)), 0.0],[0.0, 0.0, 1.0]])\n", "# helper for drawing eef frame into camera view\n", "def draw_axes(img, cam_pose, ee_pose, K, L=.08, t=3, zoff=0.):\n", " img = img.copy()\n", " fx, cx, fy, cy = K\n", " K33 = np.array([[fx,0,cx],[0,fy,cy],[0,0,1.]], float)\n", "\n", " Rc = Rt.from_quat([cam_pose[4],cam_pose[5],cam_pose[6],cam_pose[3]]).as_matrix()\n", " tc = np.asarray(cam_pose[:3], float)\n", "\n", " Re = Rt.from_quat([ee_pose[4],ee_pose[5],ee_pose[6],ee_pose[3]]).as_matrix() @ ROTATE_EEF\n", " te = np.asarray(ee_pose[:3], float) + zoff*Re[:,2]\n", "\n", " Pw = np.vstack([te, te+L*Re[:,0], te+L*Re[:,1], te+L*Re[:,2]]).T\n", " Pc = Rc.T @ (Pw - tc[:,None])\n", " z = Pc[2]\n", " if np.any(z <= 1e-6): return img\n", " uvw = K33 @ (Pc / z)\n", " p0,px,py,pz = [tuple(np.rint(uvw[:2,i]).astype(int)) for i in range(4)]\n", "\n", " h,w = img.shape[:2]\n", " if 0<=p0[0]" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# pick a random sample and visualize it\n", "sample_idx = np.random.randint(len(dataset))\n", "sample = dataset[sample_idx]\n", "# retrieve the episode uuid from the metadata\n", "episode_uuid = dataset.meta.episodes[sample[\"episode_index\"].item()][\"uuid\"]\n", "desc = f\"{episode_uuid}\"\n", "# retrieve the eef pose\n", "eef_pose = sample[\"observation.cartesian_position\"]\n", "\n", "\n", "cams = [(\"observation.images.left_external\", \"left\"), (\"observation.images.wrist\", \"wrist\"), (\"observation.images.right_external\", \"right\"),]\n", "fig, ax = plt.subplots(1, 3, figsize=(3*1280*0.004, 720*0.004))\n", "fig.suptitle(desc)\n", "plt.subplots_adjust(left=0, right=1, bottom=0, top=0.86, wspace=0.0)\n", "for a, (cam_key, title) in zip(ax, cams):\n", " s = cam_key.split(\".\")[-1]\n", " intr = sample[f\"{s}_camera_intrinsics\"]\n", " extr = sample[f\"{s}_camera_to_robot_extrinsics\"]\n", " img = sample[cam_key].permute(1, 2, 0).numpy()\n", " im = draw_axes(img, extr, eef_pose, intr, zoff=0.18)\n", " a.imshow(im)\n", " a.set_title(title, pad=2)\n", " a.axis(\"off\")\n", "plt.show()" ] }, { "cell_type": "code", "execution_count": 6, "id": "940e2c7e-23c7-4c00-b193-081d80a89348", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "episode 5166 - 'IPRL+2fe9715d+2023-08-21-23h-32m-15s'\n", "start_global_idx: 1315912, end_global_idx: 1316046, length: 134 | 134\n" ] } ], "source": [ "# its also possible to interact with an entire episode\n", "episode_idx = np.random.randint(dataset.meta.total_episodes)\n", "episode_info = dataset.meta.episodes[episode_idx]\n", "episode_len = episode_info[\"length\"]\n", "# uuid references the episode in the raw dataset\n", "episode_uuid = episode_info[\"uuid\"]\n", "start_global_idx = episode_info[\"dataset_from_index\"]\n", "end_global_idx = episode_info[\"dataset_to_index\"]\n", "print(f\"episode {episode_idx} - '{episode_uuid}'\\nstart_global_idx: {start_global_idx}, end_global_idx: {end_global_idx}, length: {episode_len} | {end_global_idx-start_global_idx}\")\n", "# global indices in the dataset\n", "episode_global_idx = np.arange(start_global_idx, end_global_idx)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.3" } }, "nbformat": 4, "nbformat_minor": 5 }