File size: 14,183 Bytes
5236ead |
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 |
{
"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
}
|