{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":293774821,"sourceType":"kernelVersion"}],"dockerImageVersionId":31259,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# **MASt3R to COLMAP ps1/ps2 Comparison**\n\nps1: called traditional/process1
\nps2: called process2
\n\nhttps://www.kaggle.com/code/stpeteishii/mast3r-to-colmap-pipeline\n\nhttps://www.kaggle.com/code/stpeteishii/mast3r-to-colmap-ps1-ps2-comparison","metadata":{}},{"cell_type":"markdown","source":"https://arxiv.org/abs/2406.09756","metadata":{}},{"cell_type":"markdown","source":"## **What is MASt3R?**\nMASt3R is a 3D image matching model built to find visual correspondences between photos and understand scenes in three dimensions. It fundamentally treats matching as a 3D geometry problem, unlike older methods that treat it as a 2D task. This makes it exceptionally robust for challenging real-world scenarios.","metadata":{}},{"cell_type":"markdown","source":"\n## **About this notebook**\n\nWhen performing Gaussian Splatting, the traditional approach is to feed the output of COLMAP directly into the Gaussian Splatting pipeline.\n\nMASt3R can replace the role that COLMAP has traditionally played. However, the output format of MASt3R differs from that of COLMAP, so it is necessary to convert MASt3R’s output into COLMAP format.\n\nIn this notebook, we consider two possible approaches for converting MASt3R output into COLMAP format.\n\nThe first approach is the one used to generate submission data with MASt3R in IMC2025. In this notebook, this approach is referred to as **process2**.\n\nThe second approach is referred to as **traditional** or **process1** in this notebook.\n\n* **Process2** directly merges and filters the 3D point clouds (pts3d) and returns them as the function output.\n* **Traditional / process1** does not return 3D point cloud data. Instead, it focuses on decomposing and organizing camera poses into rotations and translations.\n\nWe performed Gaussian Splatting using both approaches and observed a clear difference in the resulting 3DGS reconstructions. The results produced by the traditional/process1 approach were superior.\n\nBased on these observations, when performing Gaussian Splatting with MASt3R, we recommend using the traditional/process1 approach.\nFurthermore, for submissions to IMC2025 using MASt3R, adopting the traditional/process1 approach is also expected to yield better results.\n\n\n\n","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nfrom collections import namedtuple\nimport struct\nimport matplotlib.pyplot as plt\n\ndef quantify_pose_differences_from_bins(sparse_dir_trad, sparse_dir_proc2):\n \"\"\"\n Compare camera poses directly from COLMAP binary files.\n Calculates differences in position (meters) and rotation (degrees).\n \"\"\"\n \n def read_images_binary(path_to_model_file):\n \"\"\"\n Read COLMAP images.bin file\n \"\"\"\n Image = namedtuple(\n \"Image\", [\"id\", \"qvec\", \"tvec\", \"camera_id\", \"name\", \"xys\", \"point3D_ids\"]\n )\n \n images = {}\n with open(path_to_model_file, \"rb\") as fid:\n num_reg_images = struct.unpack(\" threshold) / len(errors_trad) * 100\n proc2_pct = np.sum(np.array(errors_proc2) > threshold) / len(errors_proc2) * 100\n print(f\" >{threshold:.1f} pixels: Trad={trad_pct:.2f}%, Proc2={proc2_pct:.2f}%\")\n \n # Distribution Shape (Skewness and Kurtosis)\n print(\"\\nDistribution Shape Analysis:\")\n trad_skew = stats.skew(errors_trad)\n proc2_skew = stats.skew(errors_proc2)\n trad_kurt = stats.kurtosis(errors_trad)\n proc2_kurt = stats.kurtosis(errors_proc2)\n \n print(f\" Skewness: Trad={trad_skew:.4f}, Proc2={proc2_skew:.4f}\")\n print(f\" Kurtosis: Trad={trad_kurt:.4f}, Proc2={proc2_kurt:.4f}\")\n \n # Kolmogorov-Smirnov Test (Statistical validation of differences)\n ks_stat, p_value = stats.ks_2samp(errors_trad, errors_proc2)\n print(f\"\\nKolmogorov-Smirnov Test (KS Test):\")\n print(f\" Statistic: {ks_stat:.4f}\")\n print(f\" p-value: {p_value:.2e}\")\n if p_value < 0.001:\n print(\" → Result: Distributions are statistically different (p < 0.001)\")\n \n # Jensen-Shannon Divergence (Similarity measure)\n hist_trad, bins = np.histogram(errors_trad, bins=50, range=(0, 1), density=True)\n hist_proc2, _ = np.histogram(errors_proc2, bins=bins, density=True)\n \n # Normalization for Divergence Calculation\n hist_trad = hist_trad / (hist_trad.sum() + 1e-10)\n hist_proc2 = hist_proc2 / (hist_proc2.sum() + 1e-10)\n \n js_dist = jensenshannon(hist_trad, hist_proc2)\n print(f\"\\nJensen-Shannon Distance: {js_dist:.4f}\")\n print(f\" (Scale: 0 = identical distributions, 1 = completely different)\")\n\n# Execute\nanalyze_error_distribution(errors_trad, errors_proc2)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def read_points3D_binary(path_to_model_file):\n \"\"\"\n Read COLMAP points3D.bin file.\n \n Returns:\n dict: point3D_id -> Point3D(id, xyz, rgb, error, image_ids, point2D_idxs)\n \"\"\"\n import struct\n import numpy as np\n from collections import namedtuple\n \n # Define Point3D namedtuple structure\n Point3D = namedtuple(\n \"Point3D\", \n [\"id\", \"xyz\", \"rgb\", \"error\", \"image_ids\", \"point2D_idxs\"]\n )\n \n points3D = {}\n \n with open(path_to_model_file, \"rb\") as fid:\n # Read total number of points\n num_points = struct.unpack(\" 0.5 pixels)\n high_error_points = [(p.xyz, p.error) for p in points.values() if p.error > 0.5]\n \n if not high_error_points:\n print(\"No high-error points (>0.5 pixels) detected.\")\n return\n\n xyz_high_error = np.array([p[0] for p in high_error_points])\n \n print(f\"High-error points (>0.5 pixels): {len(high_error_points)}\")\n print(f\"Percentage of noise: {len(high_error_points)/len(points)*100:.1f}%\")\n \n # [Automation Logic] Calculate the centroid of high-error points\n error_center = xyz_high_error.mean(axis=0)\n print(f\"\\nDetected High-error centroid: {error_center}\")\n print(f\"Global centroid (all points): {xyz_all.mean(axis=0)}\")\n \n # Count high-error points within a specific radius to check for spatial concentration\n # Note: 0.3 is a heuristic value; adjust based on your model's coordinate scale\n distances = np.linalg.norm(xyz_high_error - error_center, axis=1)\n nearby = np.sum(distances < 0.3) \n \n print(f\"\\nPoints concentrated near the error centroid (<0.3 units): {nearby}\")\n print(f\"Concentration rate: {nearby/len(high_error_points)*100:.1f}%\")\n \n # --- Visualization ---\n fig = plt.figure(figsize=(12, 8))\n ax = fig.add_subplot(111, projection='3d')\n \n # Plot all points (Faint blue for context)\n ax.scatter(xyz_all[::10, 0], xyz_all[::10, 1], xyz_all[::10, 2], \n s=1, alpha=0.05, c='blue', label='All points (subsampled)')\n \n # Plot high-error points (Red for visibility)\n ax.scatter(xyz_high_error[:, 0], xyz_high_error[:, 1], xyz_high_error[:, 2],\n s=5, alpha=0.2, c='red', label='High error (>0.5px)')\n \n # Highlight the detected error centroid (Yellow star)\n ax.scatter(*error_center, s=200, c='yellow', marker='*', \n edgecolors='black', linewidth=1, label='Detected Error Centroid')\n \n ax.set_title('Spatial Distribution of High-Error Points')\n ax.set_xlabel('X')\n ax.set_ylabel('Y')\n ax.set_zlabel('Z')\n ax.legend()\n plt.show()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"identify_problematic_points(sparse_dir_trad)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-25T07:56:20.499112Z","iopub.execute_input":"2026-01-25T07:56:20.499445Z","iopub.status.idle":"2026-01-25T07:56:39.483760Z","shell.execute_reply.started":"2026-01-25T07:56:20.499417Z","shell.execute_reply":"2026-01-25T07:56:39.482834Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"identify_problematic_points(sparse_dir_proc2)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-25T07:56:39.485498Z","iopub.execute_input":"2026-01-25T07:56:39.486198Z","iopub.status.idle":"2026-01-25T07:57:17.583330Z","shell.execute_reply.started":"2026-01-25T07:56:39.486161Z","shell.execute_reply":"2026-01-25T07:57:17.582161Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"3dgs via ps1(traditional/process1)\n","metadata":{}},{"cell_type":"markdown","source":"3dsgs via ps2(process2)\n","metadata":{}},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"","metadata":{}}]}