{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Jupyter environment detected. Enabling Open3D WebVisualizer.\n", "[Open3D INFO] WebRTC GUI backend enabled.\n", "[Open3D INFO] WebRTCWindowSystem: HTTP handshake server disabled.\n", "Reading point cloud from car_source.ply\n", "Removing duplicate points (epsilon = 0.001)\n", "Performing voxel downsampling with voxel size 0.05\n", "\n", "Point cloud statistics:\n", "Original points: 2016000\n", "Points after duplicate removal: 619908\n", "Final points after downsampling: 619908\n", "Duplicate removal reduction: 69.25%\n", "Total reduction: 69.25%\n", "Reading point cloud from car_target.ply\n", "Removing duplicate points (epsilon = 0.001)\n", "Performing voxel downsampling with voxel size 0.05\n", "\n", "Point cloud statistics:\n", "Original points: 2016000\n", "Points after duplicate removal: 873663\n", "Final points after downsampling: 873663\n", "Duplicate removal reduction: 56.66%\n", "Total reduction: 56.66%\n" ] } ], "source": [ "import open3d as o3d\n", "import numpy as np\n", "\n", "def write_ply(points, output_path):\n", " \"\"\"\n", " Write points and parameters to a PLY file\n", " \n", " Parameters:\n", " points: numpy array of shape (N, 3) containing point coordinates\n", " output_path: path to save the PLY file\n", " \"\"\"\n", " with open(output_path, 'w') as f:\n", " # Write header\n", " f.write(\"ply\\n\")\n", " f.write(\"format ascii 1.0\\n\")\n", " \n", " # Write vertex element\n", " f.write(f\"element vertex {len(points)}\\n\")\n", " f.write(\"property float x\\n\")\n", " f.write(\"property float y\\n\")\n", " f.write(\"property float z\\n\")\n", " \n", " # Write camera element\n", " f.write(\"element camera 1\\n\")\n", " f.write(\"property float view_px\\n\")\n", " f.write(\"property float view_py\\n\")\n", " f.write(\"property float view_pz\\n\")\n", " f.write(\"property float x_axisx\\n\")\n", " f.write(\"property float x_axisy\\n\")\n", " f.write(\"property float x_axisz\\n\")\n", " f.write(\"property float y_axisx\\n\")\n", " f.write(\"property float y_axisy\\n\")\n", " f.write(\"property float y_axisz\\n\")\n", " f.write(\"property float z_axisx\\n\")\n", " f.write(\"property float z_axisy\\n\")\n", " f.write(\"property float z_axisz\\n\")\n", " \n", " # Write phoxi frame parameters\n", " f.write(\"element phoxi_frame_params 1\\n\")\n", " f.write(\"property uint32 frame_width\\n\")\n", " f.write(\"property uint32 frame_height\\n\")\n", " f.write(\"property uint32 frame_index\\n\")\n", " f.write(\"property float frame_start_time\\n\")\n", " f.write(\"property float frame_duration\\n\")\n", " f.write(\"property float frame_computation_duration\\n\")\n", " f.write(\"property float frame_transfer_duration\\n\")\n", " f.write(\"property int32 total_scan_count\\n\")\n", " \n", " # Write camera matrix\n", " f.write(\"element camera_matrix 1\\n\")\n", " for i in range(9):\n", " f.write(f\"property float cm{i}\\n\")\n", " \n", " # Write distortion matrix\n", " f.write(\"element distortion_matrix 1\\n\")\n", " for i in range(14):\n", " f.write(f\"property float dm{i}\\n\")\n", " \n", " # Write camera resolution\n", " f.write(\"element camera_resolution 1\\n\")\n", " f.write(\"property float width\\n\")\n", " f.write(\"property float height\\n\")\n", " \n", " # Write frame binning\n", " f.write(\"element frame_binning 1\\n\")\n", " f.write(\"property float horizontal\\n\")\n", " f.write(\"property float vertical\\n\")\n", " \n", " # End header\n", " f.write(\"end_header\\n\")\n", " \n", " # Write vertex data\n", " for point in points:\n", " f.write(f\"{point[0]} {point[1]} {point[2]}\\n\")\n", "\n", " return True\n", " \n", "def random_rotation_matrix():\n", " \"\"\"\n", " Generate a random 3x3 rotation matrix (SO(3) matrix).\n", " \n", " Uses the method described by James Arvo in \"Fast Random Rotation Matrices\" (1992):\n", " 1. Generate a random unit vector for rotation axis\n", " 2. Generate a random angle\n", " 3. Create rotation matrix using Rodriguez rotation formula\n", " \n", " Returns:\n", " numpy.ndarray: A 3x3 random rotation matrix\n", " \"\"\"\n", " # Generate random angle between 0 and 2π\n", " theta = np.random.uniform(0, 2 * np.pi)\n", " \n", " # Generate random unit vector for rotation axis\n", " phi = np.random.uniform(0, 2 * np.pi)\n", " cos_theta = np.random.uniform(-1, 1)\n", " sin_theta = np.sqrt(1 - cos_theta**2)\n", " \n", " axis = np.array([\n", " sin_theta * np.cos(phi),\n", " sin_theta * np.sin(phi),\n", " cos_theta\n", " ])\n", " \n", " # Normalize to ensure it's a unit vector\n", " axis = axis / np.linalg.norm(axis)\n", " \n", " # Create the cross-product matrix K\n", " K = np.array([\n", " [0, -axis[2], axis[1]],\n", " [axis[2], 0, -axis[0]],\n", " [-axis[1], axis[0], 0]\n", " ])\n", " \n", " # Rodriguez rotation formula: R = I + sin(θ)K + (1-cos(θ))K²\n", " R = (np.eye(3) + \n", " np.sin(theta) * K + \n", " (1 - np.cos(theta)) * np.dot(K, K))\n", " \n", " return R\n", "\n", "def remove_duplicates(pcd, eps=0.001):\n", " \"\"\"\n", " Remove duplicate points from point cloud within epsilon distance\n", " \n", " Parameters:\n", " pcd: open3d.geometry.PointCloud\n", " eps: float, maximum distance between points to be considered duplicates\n", " \n", " Returns:\n", " open3d.geometry.PointCloud: Point cloud with duplicates removed\n", " \"\"\"\n", " # Convert to numpy array for processing\n", " points = np.asarray(pcd.points)\n", " colors = np.asarray(pcd.colors) if pcd.has_colors() else None\n", " \n", " # Use voxel downsampling with very small voxel size to remove duplicates\n", " temp_pcd = o3d.geometry.PointCloud()\n", " temp_pcd.points = o3d.utility.Vector3dVector(points)\n", " if colors is not None:\n", " temp_pcd.colors = o3d.utility.Vector3dVector(colors)\n", " \n", " # Use voxel downsampling with epsilon size to remove points within eps distance\n", " deduped_pcd = temp_pcd.voxel_down_sample(voxel_size=eps)\n", " \n", " return deduped_pcd\n", "\n", "def downsample_ply(input_path, output_path, method='voxel', voxel_size=0.05, \n", " every_k_points=5, remove_duplicates_eps=0.001, perturb = False):\n", " \"\"\"\n", " Remove duplicates and downsample a PLY file using different methods.\n", " \n", " Parameters:\n", " input_path (str): Path to input PLY file\n", " output_path (str): Path to save downsampled PLY file\n", " method (str): Downsampling method ('voxel', 'uniform', or 'random')\n", " voxel_size (float): Size of voxel for voxel downsampling\n", " every_k_points (int): Keep every kth point for uniform downsampling\n", " remove_duplicates_eps (float): Maximum distance between points to be considered duplicates\n", " \n", " Returns:\n", " bool: True if successful, False otherwise\n", " \"\"\"\n", " try:\n", " # Read point cloud\n", " print(f\"Reading point cloud from {input_path}\")\n", " pcd = o3d.io.read_point_cloud(input_path)\n", " original_points = len(np.asarray(pcd.points))\n", " \n", " # Remove duplicates first\n", " print(f\"Removing duplicate points (epsilon = {remove_duplicates_eps})\")\n", " pcd = remove_duplicates(pcd, eps=remove_duplicates_eps)\n", " after_dedup_points = len(np.asarray(pcd.points))\n", " \n", " # Perform downsampling based on selected method\n", " if method == 'voxel':\n", " print(f\"Performing voxel downsampling with voxel size {voxel_size}\")\n", " downsampled_pcd = pcd.voxel_down_sample(voxel_size=voxel_size)\n", " \n", " elif method == 'uniform':\n", " print(f\"Performing uniform downsampling, keeping every {every_k_points}th point\")\n", " downsampled_pcd = pcd.uniform_down_sample(every_k_points=every_k_points)\n", " \n", " elif method == 'random':\n", " points = np.asarray(pcd.points)\n", " colors = np.asarray(pcd.colors) if pcd.has_colors() else None\n", " indices = np.random.choice(\n", " points.shape[0], \n", " size=points.shape[0] // every_k_points, \n", " replace=False\n", " )\n", " downsampled_pcd = o3d.geometry.PointCloud()\n", " downsampled_pcd.points = o3d.utility.Vector3dVector(points[indices])\n", " if colors is not None:\n", " downsampled_pcd.colors = o3d.utility.Vector3dVector(colors[indices])\n", " \n", " else:\n", " raise ValueError(f\"Unknown downsampling method: {method}\")\n", " \n", " point_cloud = np.asarray(downsampled_pcd.points)\n", " if perturb:\n", " R_perturb = random_rotation_matrix()\n", " t_perturb = np.random.rand(3) * 0.01\n", " point_cloud = np.dot(R_perturb, point_cloud.T).T + t_perturb.T\n", "\n", " # Save downsampled point cloud\n", " success = write_ply(point_cloud, output_path)\n", " \n", " if not success:\n", " raise Exception(\"Failed to write point cloud\")\n", " \n", " # Print statistics\n", " final_points = len(np.asarray(downsampled_pcd.points))\n", " dedup_reduction = (1 - after_dedup_points/original_points) * 100\n", " total_reduction = (1 - final_points/original_points) * 100\n", " \n", " print(\"\\nPoint cloud statistics:\")\n", " print(f\"Original points: {original_points}\")\n", " print(f\"Points after duplicate removal: {after_dedup_points}\")\n", " print(f\"Final points after downsampling: {final_points}\")\n", " print(f\"Duplicate removal reduction: {dedup_reduction:.2f}%\")\n", " print(f\"Total reduction: {total_reduction:.2f}%\")\n", " \n", " return True\n", " \n", " except Exception as e:\n", " print(f\"Error during processing: {str(e)}\")\n", " return False\n", "\n", "mode = 'downsample' # 'downsample', 'voxel', 'uniform'\n", "\n", "if mode == 'downsample':\n", " # Voxel downsampling\n", " downsample_ply(\n", " \"car_source.ply\",\n", " \"car_source_downsample.ply\",\n", " method='voxel',\n", " voxel_size=0.05,\n", " remove_duplicates_eps=0.001,\n", " perturb = True\n", " )\n", " downsample_ply(\n", " \"car_target.ply\",\n", " \"car_target_downsample.ply\",\n", " method='voxel',\n", " voxel_size=0.05,\n", " remove_duplicates_eps=0.001\n", " )\n", "\n", "if mode == 'voxel': \n", " # Uniform downsampling\n", " downsample_ply(\n", " \"car_source.ply\",\n", " \"car_source_downsample.ply\",\n", " method='uniform',\n", " every_k_points=5,\n", " remove_duplicates_eps=0.001\n", " )\n", " downsample_ply(\n", " \"car_target.ply\",\n", " \"car_target_downsample.ply\",\n", " method='uniform',\n", " every_k_points=5,\n", " remove_duplicates_eps=0.001\n", " )\n", "\n", "if mode == 'uniform': \n", " # Random downsampling\n", " downsample_ply(\n", " \"car_source.ply\",\n", " \"car_source_downsample.ply\",\n", " method='random',\n", " every_k_points=5,\n", " remove_duplicates_eps=0.001\n", " )\n", " downsample_ply(\n", " \"car_target.ply\",\n", " \"car_target_downsample.ply\",\n", " method='random',\n", " every_k_points=5,\n", " remove_duplicates_eps=0.001\n", " )" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "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 }