{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Notebook to Detect 3D Structures" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import json\n", "import trimesh\n", "import numpy as np" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "# Meshes for collision checking\n", "def _filter_small_segments(segments, min_length=1e-6):\n", " \"\"\"Filter out segments that are too short.\"\"\"\n", " valid_segments = []\n", " for segment in segments:\n", " start, end = segment\n", " length = np.linalg.norm(np.array(end) - np.array(start))\n", " if length >= min_length:\n", " valid_segments.append(segment)\n", " return valid_segments\n", "\n", "\n", "def _generate_mesh(segments, height=2.0, width=0.2, color=None):\n", " segments = np.array(segments, dtype=np.float64)\n", " starts, ends = segments[:, 0, :], segments[:, 1, :]\n", " directions = ends - starts\n", " lengths = np.linalg.norm(directions, axis=1, keepdims=True)\n", " unit_directions = directions / lengths\n", " \n", " # Create the base box mesh with the height along the z-axis\n", " base_box = trimesh.creation.box(extents=[1.0, width, height])\n", " base_box.apply_translation([0.5, 0, 0]) # Align box's origin to its start\n", " \n", " # Prepare rotation matrices around the z-axis\n", " z_axis = np.array([0, 0, 1]) # The desired vertical axis\n", " angles = np.arctan2(unit_directions[:, 1], unit_directions[:, 0]) # Rotation in the XY plane\n", "\n", " rectangles = []\n", " lengths = lengths.flatten()\n", "\n", " for i, (start, length, angle) in enumerate(zip(starts, lengths, angles)):\n", " # Copy the base box and scale to match segment length\n", " scaled_box = base_box.copy()\n", " scaled_box.apply_scale([length, 1.0, 1.0])\n", " \n", " # Apply rotation around the z-axis\n", " rotation_matrix = trimesh.transformations.rotation_matrix(angle, z_axis)\n", " scaled_box.apply_transform(rotation_matrix)\n", " \n", " # Translate the box to the segment's starting point\n", " scaled_box.apply_translation(start)\n", " if color is not None:\n", " scaled_box.visual.face_colors = color\n", " rectangles.append(scaled_box)\n", "\n", " # Concatenate all boxes into a single mesh\n", " mesh = trimesh.util.concatenate(rectangles)\n", " return mesh\n", "\n", "\n", "def _create_agent_box_mesh(position, heading, length, width, height, color=None):\n", " # Create box centered at origin\n", " box = trimesh.creation.box(extents=[length, width, height])\n", " \n", " # Rotate box to align with heading\n", " z_axis = np.array([0, 0, 1])\n", " rotation_matrix = trimesh.transformations.rotation_matrix(heading, z_axis)\n", " box.apply_transform(rotation_matrix)\n", " \n", " # Move box to position\n", " box.apply_translation(position)\n", " \n", " if color is not None:\n", " box.visual.face_colors = color\n", " \n", " return box" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "def check_3d_structures(scene_path, tolerance=0.1):\n", " \"\"\"Check for 3D structures using the same logic as process_waymo_files.py\"\"\"\n", " with open(scene_path, 'r') as f:\n", " scene = json.load(f)\n", "\n", " # Collect edge points like in the processing script\n", " edge_points = []\n", " edge_segments = []\n", " for road in scene['roads']:\n", " if road[\"type\"] == \"road_edge\":\n", " edge_vertices = [[r[\"x\"], r[\"y\"], r[\"z\"]] for r in road[\"geometry\"]]\n", " edge_points.extend(edge_vertices)\n", " edge_segments.extend([\n", " [edge_vertices[i], edge_vertices[i + 1]]\n", " for i in range(len(edge_vertices) - 1)\n", " ])\n", "\n", " # Check for 3D structures using same logic as processing script\n", " has_3d = False\n", " if len(edge_points) > 0:\n", " edge_points = np.array(edge_points)\n", " xy_points = edge_points[:, :2]\n", " \n", " # Process in chunks like in processing script\n", " chunk_size = 1000\n", " for i in range(0, len(xy_points), chunk_size):\n", " chunk = xy_points[i:i + chunk_size]\n", " # Calculate distances between current chunk and all points\n", " dists = np.linalg.norm(chunk[:, np.newaxis] - xy_points, axis=2)\n", " potential_pairs = np.where((dists < tolerance) & (dists > 0))\n", " \n", " # Check z-values for identified pairs\n", " for p1, p2 in zip(*potential_pairs):\n", " p1_idx = i + p1 # Adjust index for chunking\n", " if abs(edge_points[p1_idx, 2] - edge_points[p2, 2]) > tolerance:\n", " has_3d = True\n", " print(f\"Found 3D structure between points:\")\n", " print(f\"Point 1: {edge_points[p1_idx]}\")\n", " print(f\"Point 2: {edge_points[p2]}\")\n", " print(f\"Z difference: {abs(edge_points[p1_idx, 2] - edge_points[p2, 2])}\")\n", " break\n", " \n", " if has_3d:\n", " break\n", "\n", " # Create visualization identical to processing script\n", " edge_segments = _filter_small_segments(edge_segments)\n", " edge_mesh = _generate_mesh(edge_segments)\n", "\n", " # Add objects just like in processing script\n", " object_meshes = []\n", " trajectory_meshes = []\n", " for object in scene['objects']:\n", " if object['type'] not in ['vehicle', 'cyclist']:\n", " continue\n", "\n", " first_valid_idx = next((i for i, valid in enumerate(object[\"valid\"]) if valid), None)\n", " if first_valid_idx is not None:\n", " initial_pos = [\n", " object[\"position\"][first_valid_idx][\"x\"],\n", " object[\"position\"][first_valid_idx][\"y\"],\n", " object[\"position\"][first_valid_idx][\"z\"]\n", " ]\n", " initial_heading = object[\"heading\"][first_valid_idx]\n", " color = (180, 0, 0, 15) if object[\"mark_as_expert\"] else (0, 180, 0, 15)\n", " \n", " initial_box = _create_agent_box_mesh(\n", " initial_pos,\n", " initial_heading,\n", " object[\"length\"],\n", " object[\"width\"],\n", " object[\"height\"],\n", " color=color\n", " )\n", " object_meshes.append(initial_box)\n", "\n", " # Create trajectory visualization\n", " if False in object[\"valid\"]:\n", " trajectory_segments = []\n", " for i in range(len(object[\"position\"]) - 1):\n", " if object[\"valid\"][i] and object[\"valid\"][i + 1]:\n", " trajectory_segments.append([\n", " [object[\"position\"][i][\"x\"], object[\"position\"][i][\"y\"], object[\"position\"][i][\"z\"]],\n", " [object[\"position\"][i+1][\"x\"], object[\"position\"][i+1][\"y\"], object[\"position\"][i+1][\"z\"]]\n", " ])\n", " else:\n", " object_vertices = [[pos[\"x\"], pos[\"y\"], pos[\"z\"]] for pos in object[\"position\"]]\n", " trajectory_segments = [[object_vertices[i], object_vertices[i+1]] for i in range(len(object_vertices) - 1)]\n", " \n", " trajectory_segments = _filter_small_segments(trajectory_segments)\n", " if len(trajectory_segments) > 0:\n", " color = (180,0,0,15) if object[\"mark_as_expert\"] else (0,180,0,15)\n", " trajectory_mesh = _generate_mesh(trajectory_segments, color=color)\n", " trajectory_meshes.append(trajectory_mesh)\n", "\n", " # Create scene\n", " view = trimesh.Scene()\n", " view.add_geometry(edge_mesh, node_name=\"Road Edges\")\n", " for i, mesh in enumerate(trajectory_meshes):\n", " view.add_geometry(mesh, node_name=f\"Vehicle {i} Path\")\n", " for i, mesh in enumerate(object_meshes):\n", " view.add_geometry(mesh, node_name=f\"Vehicle {i} Initial Position\")\n", "\n", " print(f\"\\nHas 3D structures: {has_3d}\")\n", " return view, has_3d" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Has 3D structures: False\n" ] }, { "data": { "text/html": [ "
" ], "text/plain": [ "" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Example usage:\n", "scene_path = '../data/processed/examples/tfrecord-00000-of-01000_222.json'\n", "view, has_3d = check_3d_structures(scene_path, tolerance=0.2)\n", "view.show()" ] } ], "metadata": { "kernelspec": { "display_name": "json_gen", "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.10.12" } }, "nbformat": 4, "nbformat_minor": 2 }