{ "metadata": { "kernelspec": { "display_name": "Python 3", "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.12" }, "kaggle": { "accelerator": "none", "dataSources": [ { "sourceType": "datasetVersion", "sourceId": 15538872, "datasetId": 1429416, "databundleVersionId": 16467233 } ], "dockerImageVersionId": 31260, "isInternetEnabled": true, "language": "python", "sourceType": "notebook", "isGpuEnabled": false }, "papermill": { "default_parameters": {}, "duration": 297.567631, "end_time": "2026-03-26T13:00:56.861265", "environment_variables": {}, "exception": true, "input_path": "__notebook__.ipynb", "output_path": "__notebook__.ipynb", "parameters": {}, "start_time": "2026-03-26T12:55:59.293634", "version": "2.6.0" }, "colab": { "provenance": [], "machine_shape": "hm", "gpuType": "L4" }, "accelerator": "GPU" }, "nbformat_minor": 0, "nbformat": 4, "cells": [ { "source": [ "from google.colab import drive\n", "drive.mount('/content/drive')\n" ], "metadata": { "id": "G8HLekEKMlOW", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "f301cbf6-4389-4b71-937c-3a331a92183b" }, "cell_type": "code", "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Mounted at /content/drive\n" ] } ], "execution_count": 1 }, { "cell_type": "markdown", "source": [ "# **3D Reconstruction with MASt3R-SfM**" ], "metadata": { "papermill": { "duration": 0.001826, "end_time": "2026-03-26T12:56:02.330517", "exception": false, "start_time": "2026-03-26T12:56:02.328691", "status": "completed" }, "tags": [], "id": "IFhi2v_hMlOZ" } }, { "cell_type": "markdown", "source": [ "### **w/biplet**" ], "metadata": { "id": "bzVezppvTTVe" } }, { "cell_type": "code", "source": [ "!pip uninstall numpy -y\n", "!pip install \"numpy==1.26.4\" \"scipy>=1.12\" --quiet\n", "break" ], "metadata": { "trusted": true, "id": "rxX5nRu4MlOa", "colab": { "base_uri": "https://localhost:8080/", "height": 431 }, "outputId": "a6b3ce41-2165-41df-f3c7-1955616d3b25" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Found existing installation: numpy 2.0.2\n", "Uninstalling numpy-2.0.2:\n", " Successfully uninstalled numpy-2.0.2\n", "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m61.0/61.0 kB\u001b[0m \u001b[31m6.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m18.0/18.0 MB\u001b[0m \u001b[31m123.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", "\u001b[?25h\u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n", "shap 0.51.0 requires numpy>=2, but you have numpy 1.26.4 which is incompatible.\n", "opencv-python 4.13.0.92 requires numpy>=2; python_version >= \"3.9\", but you have numpy 1.26.4 which is incompatible.\n", "rasterio 1.5.0 requires numpy>=2, but you have numpy 1.26.4 which is incompatible.\n", "jax 0.7.2 requires numpy>=2.0, but you have numpy 1.26.4 which is incompatible.\n", "pytensor 2.38.2 requires numpy>=2.0, but you have numpy 1.26.4 which is incompatible.\n", "cupy-cuda12x 14.0.1 requires numpy<2.6,>=2.0, but you have numpy 1.26.4 which is incompatible.\n", "opencv-python-headless 4.13.0.92 requires numpy>=2; python_version >= \"3.9\", but you have numpy 1.26.4 which is incompatible.\n", "xarray-einstats 0.10.0 requires numpy>=2.0, but you have numpy 1.26.4 which is incompatible.\n", "opencv-contrib-python 4.13.0.92 requires numpy>=2; python_version >= \"3.9\", but you have numpy 1.26.4 which is incompatible.\n", "tobler 0.13.0 requires numpy>=2.0, but you have numpy 1.26.4 which is incompatible.\n", "jaxlib 0.7.2 requires numpy>=2.0, but you have numpy 1.26.4 which is incompatible.\u001b[0m\u001b[31m\n", "\u001b[0m" ] }, { "output_type": "error", "ename": "SyntaxError", "evalue": "'break' outside loop (1398352102.py, line 3)", "traceback": [ "\u001b[0;36m File \u001b[0;32m\"/tmp/ipykernel_10964/1398352102.py\"\u001b[0;36m, line \u001b[0;32m3\u001b[0m\n\u001b[0;31m break\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m 'break' outside loop\n" ] } ], "execution_count": 2 }, { "cell_type": "markdown", "source": [ "---" ], "metadata": { "id": "rE9GmNNcMlOb" } }, { "cell_type": "code", "source": [ "# restart, run after" ], "metadata": { "trusted": true, "execution": { "iopub.status.busy": "2026-04-06T17:49:20.119493Z", "iopub.execute_input": "2026-04-06T17:49:20.119783Z", "iopub.status.idle": "2026-04-06T17:49:20.124291Z", "shell.execute_reply.started": "2026-04-06T17:49:20.119757Z", "shell.execute_reply": "2026-04-06T17:49:20.123517Z" }, "id": "LjWh_q2jMlOb" }, "outputs": [], "execution_count": 1 }, { "cell_type": "code", "source": [], "metadata": { "id": "vSrsSqRpUGWz" }, "execution_count": 1, "outputs": [] }, { "cell_type": "code", "source": [ "!pip show numpy | grep Version:" ], "metadata": { "trusted": true, "execution": { "iopub.status.busy": "2026-04-06T17:49:20.125646Z", "iopub.execute_input": "2026-04-06T17:49:20.126379Z", "iopub.status.idle": "2026-04-06T17:49:22.32856Z", "shell.execute_reply.started": "2026-04-06T17:49:20.126347Z", "shell.execute_reply": "2026-04-06T17:49:22.327891Z" }, "id": "YlKV_7vgMlOb", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "ac624797-b3e6-4bec-bc61-ec4faedaf3c4" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Version: 1.26.4\n" ] } ], "execution_count": 2 }, { "cell_type": "code", "source": [ "!pip install gputil\n", "import psutil\n", "import time\n", "import threading\n", "import os\n", "import numpy as np\n", "\n", "class MultiResourceLogger:\n", " def __init__(self, interval=60.0, time_limit=None):\n", " self.interval = interval\n", " self.time_limit = time_limit\n", " self.stop_flag = False\n", " self.start_time = time.time()\n", "\n", " self.thread = threading.Thread(target=self._log_loop, daemon=True)\n", "\n", " if self.time_limit is not None:\n", " self.timeout_thread = threading.Thread(\n", " target=self._timeout_loop, daemon=True\n", " )\n", "\n", " def _get_gpu_usage(self):\n", " try:\n", " import GPUtil\n", " gpus = GPUtil.getGPUs()\n", " stats = []\n", " for i, gpu in enumerate(gpus):\n", " stats.append(\n", " (i, gpu.load * 100, gpu.memoryUtil * 100)\n", " )\n", " return stats\n", " except:\n", " return []\n", "\n", " def _timeout_loop(self):\n", " while True:\n", " elapsed = time.time() - self.start_time\n", " if elapsed > self.time_limit:\n", " print(\"\\n⏰ TIME LIMIT REACHED\")\n", " print(\"💣 Force stopping entire notebook...\")\n", " os._exit(0)\n", " time.sleep(1)\n", "\n", " def _format_time(self, t):\n", " if t is None:\n", " return \"∞\"\n", " m = int(t // 60)\n", " s = int(t % 60)\n", " return f\"{m:02d}:{s:02d}\"\n", "\n", " def _log_loop(self):\n", " psutil.cpu_percent(None)\n", "\n", " while not self.stop_flag:\n", " elapsed = time.time() - self.start_time\n", " remain = None\n", " if self.time_limit is not None:\n", " remain = self.time_limit - elapsed\n", "\n", " cpu = psutil.cpu_percent(None)\n", " mem = psutil.virtual_memory().percent\n", " gpu_stats = self._get_gpu_usage()\n", "\n", " msg = (\n", " f\"⏱️ elapsed={self._format_time(elapsed)} \"\n", " f\"⏳ remain={self._format_time(remain)} | \"\n", " f\"🔥 CPU={cpu:5.1f}% \"\n", " f\"💾 RAM={mem:5.1f}%\"\n", " )\n", "\n", " for idx, gpu, vram in gpu_stats:\n", " msg += f\" | 🧠 GPU{idx}={gpu:5.1f}% 🎮 VRAM{idx}={vram:5.1f}%\"\n", "\n", " print(msg)\n", "\n", " time.sleep(self.interval)\n", "\n", " def start(self):\n", " self.thread.start()\n", " if self.time_limit is not None:\n", " self.timeout_thread.start()\n", "\n", " def stop(self):\n", " self.stop_flag = True\n", "\n", "\n", "\n", "logger = MultiResourceLogger(\n", " interval=60*3,\n", " time_limit=60*240\n", ")\n", "\n", "logger.start()\n", "#logger.stop()" ], "metadata": { "trusted": true, "execution": { "iopub.status.busy": "2026-04-06T17:49:22.329626Z", "iopub.execute_input": "2026-04-06T17:49:22.329849Z", "iopub.status.idle": "2026-04-06T17:49:27.764878Z", "shell.execute_reply.started": "2026-04-06T17:49:22.329824Z", "shell.execute_reply": "2026-04-06T17:49:27.763955Z" }, "id": "YtsBCdK_MlOb", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "6b41e6cd-0a61-4bdc-c603-95a59db853df" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Collecting gputil\n", " Downloading GPUtil-1.4.0.tar.gz (5.5 kB)\n", " Preparing metadata (setup.py) ... \u001b[?25l\u001b[?25hdone\n", "Building wheels for collected packages: gputil\n", " Building wheel for gputil (setup.py) ... \u001b[?25l\u001b[?25hdone\n", " Created wheel for gputil: filename=GPUtil-1.4.0-py3-none-any.whl size=7392 sha256=a560d51f35cfce46b8a8fdb123279f19b1c8320bca4c1ccf0126954103913000\n", " Stored in directory: /root/.cache/pip/wheels/92/a8/b7/d8a067c31a74de9ca252bbe53dea5f896faabd25d55f541037\n", "Successfully built gputil\n", "Installing collected packages: gputil\n", "Successfully installed gputil-1.4.0\n" ] } ], "execution_count": 3 }, { "cell_type": "code", "source": [ "# =============================================================================\n", "# 3D Reconstruction with MASt3R-SfM (sparse_global_alignment)\n", "# Based on: https://github.com/naver/mast3r\n", "# Replaces DUSt3R global_aligner with MASt3R-SfM sparse_global_alignment\n", "# =============================================================================\n", "\n", "import os\n", "import sys\n", "import gc\n", "import numpy as np\n", "import torch\n", "import torch.nn.functional as F\n", "from pathlib import Path\n", "import subprocess\n", "from PIL import Image\n", "import struct\n", "import base64\n", "\n", "\n", "# ============================================================================\n", "# Config\n", "# ============================================================================\n", "\n", "class Config:\n", " MAST3R_MODEL = \"/content/mast3r/checkpoints/MASt3R_ViTLarge_BaseDecoder_512_catmlpdpt_metric.pth\"\n", " RETRIEVAL_MODEL = (\n", " \"/content/mast3r/checkpoints/\"\n", " \"MASt3R_ViTLarge_BaseDecoder_512_catmlpdpt_metric_retrieval_trainingfree.pth\"\n", " )\n", "\n", " MAST3R_IMAGE_SIZE = 512 #512 # 512 recommended for SfM (prioritize accuracy)\n", " SCENE_GRAPH = 'retrieval-10-15' #'retrieval-10-15' # 'retrieval' | 'swin-5' | 'complete'\n", " LR1 = 0.07 # Coarse LR\n", " NITER1 = 300 # Coarse iterations ###\n", " LR2 = 0.01 # Fine LR\n", " NITER2 = 300 # Fine iterations ###\n", " OPT_DEPTH = True # Also optimize depth maps\n", " SHARED_INTRINSICS = False # Different intrinsic parameters per camera\n", "\n", " MIN_CONF_THR = 1.5 # Confidence threshold for 3D points ###\n", "\n", " SQUARE_SIZE = 1024 # Size after Biplet normalization\n", "\n", " DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n", "\n", "\n", "# ============================================================================\n", "# Memory Utilities\n", "# ============================================================================\n", "\n", "def clear_memory():\n", " gc.collect()\n", " if torch.cuda.is_available():\n", " torch.cuda.empty_cache()\n", " torch.cuda.synchronize()\n", "\n", "\n", "def get_memory_info():\n", " if torch.cuda.is_available():\n", " alloc = torch.cuda.memory_allocated() / 1024**3\n", " reserv = torch.cuda.memory_reserved() / 1024**3\n", " print(f\" GPU - Allocated: {alloc:.2f} GB, Reserved: {reserv:.2f} GB\")\n", " import psutil\n", " cpu = psutil.virtual_memory().percent\n", " print(f\" CPU - Usage: {cpu:.1f}%\")\n", "\n", "\n", "# ============================================================================\n", "# Environment Setup\n", "# ============================================================================\n", "\n", "def run_cmd(cmd, check=True):\n", " print(f\" $ {' '.join(cmd)}\")\n", " r = subprocess.run(cmd, text=True, check=False)\n", " if check and r.returncode != 0:\n", " print(f\" [WARN] exit code {r.returncode}\")\n", " return r\n", "\n", "\n", "def setup_base_environment():\n", " print(\"\\n\" + \"=\"*60)\n", " print(\"Step 0-A: Base Environment Setup\")\n", " print(\"=\"*60)\n", "\n", " run_cmd([sys.executable, \"-m\", \"pip\", \"uninstall\", \"-y\", \"numpy\"])\n", " run_cmd([sys.executable, \"-m\", \"pip\", \"install\", \"numpy==1.26.4\"])\n", " run_cmd([sys.executable, \"-m\", \"pip\", \"install\",\n", " \"torch\", \"torchvision\", \"torchaudio\"])\n", " run_cmd([sys.executable, \"-m\", \"pip\", \"install\",\n", " \"opencv-python\", \"pillow\", \"imageio\", \"imageio-ffmpeg\",\n", " \"plyfile\", \"tqdm\", \"scipy\", \"psutil\", \"roma\", \"trimesh\", \"matplotlib\"])\n", " run_cmd([sys.executable, \"-m\", \"pip\", \"install\", \"transformers==4.40.0\"])\n", " run_cmd([sys.executable, \"-m\", \"pip\", \"install\", \"pycolmap\"])\n", " print(\"✓ Base environment ready\")\n", "\n", "\n", "def setup_mast3r():\n", " print(\"\\n\" + \"=\"*60)\n", " print(\"Step 0-B: MASt3R Setup\")\n", " print(\"=\"*60)\n", "\n", " os.chdir('/content')\n", " if os.path.exists('mast3r'):\n", " os.system('rm -rf mast3r')\n", "\n", " os.system('git clone --recursive https://github.com/naver/mast3r')\n", " os.chdir('/content/mast3r')\n", " os.system('pip install -e dust3r/')\n", " os.system('pip install -r requirements.txt')\n", "\n", " os.makedirs('checkpoints', exist_ok=True)\n", "\n", " # MASt3R Main Checkpoint\n", " os.system(\n", " 'wget -nc -P checkpoints/ '\n", " 'https://download.europe.naverlabs.com/ComputerVision/MASt3R/'\n", " 'MASt3R_ViTLarge_BaseDecoder_512_catmlpdpt_metric.pth'\n", " )\n", "\n", " # Retrieval Checkpoint (for MASt3R-SfM)\n", " os.system(\n", " 'wget -nc -P checkpoints/ '\n", " 'https://download.europe.naverlabs.com/ComputerVision/MASt3R/'\n", " 'MASt3R_ViTLarge_BaseDecoder_512_catmlpdpt_metric_retrieval_trainingfree.pth'\n", " )\n", " os.system(\n", " 'wget -nc -P checkpoints/ '\n", " 'https://download.europe.naverlabs.com/ComputerVision/MASt3R/'\n", " 'MASt3R_ViTLarge_BaseDecoder_512_catmlpdpt_metric_retrieval_codebook.pkl'\n", " )\n", "\n", " sys.path.insert(0, '/content/mast3r')\n", " sys.path.insert(0, '/content/mast3r/dust3r')\n", "\n", " try:\n", " from mast3r.model import AsymmetricMASt3R\n", " print(\" ✓ MASt3R import OK\")\n", " except Exception as e:\n", " print(f\" ✗ MASt3R import failed: {e}\")\n", " raise\n", " print(\"✓ MASt3R ready\")\n", "\n", "\n", "def setup_asmk():\n", " \"\"\"\n", " ASMK: Required for MASt3R-SfM retrieval pair selection.\n", " Can be skipped if using scene_graph='swin-*'.\n", " \"\"\"\n", " print(\"\\n\" + \"=\"*60)\n", " print(\"Step 0-C: ASMK Setup (for retrieval pair selection)\")\n", " print(\"=\"*60)\n", "\n", " os.chdir('/content')\n", " run_cmd([sys.executable, \"-m\", \"pip\", \"install\", \"cython\"])\n", "\n", " if not os.path.exists('asmk'):\n", " os.system('git clone https://github.com/jenicek/asmk')\n", "\n", " os.chdir('/content/asmk/cython')\n", " r = os.system('cythonize *.pyx')\n", " if r != 0:\n", " print(\" [WARN] cythonize failed — switching to swin graph\")\n", " os.chdir('/content')\n", " return False\n", "\n", " os.chdir('/content/asmk')\n", " os.system('pip install .')\n", " os.chdir('/content')\n", "\n", " try:\n", " import asmk\n", " print(\" ✓ ASMK import OK\")\n", " return True\n", " except Exception as e:\n", " print(f\" [WARN] ASMK not importable: {e}\")\n", " return False" ], "metadata": { "execution": { "iopub.status.busy": "2026-04-06T17:49:27.76611Z", "iopub.execute_input": "2026-04-06T17:49:27.766315Z", "iopub.status.idle": "2026-04-06T17:49:32.016967Z", "shell.execute_reply.started": "2026-04-06T17:49:27.766292Z", "shell.execute_reply": "2026-04-06T17:49:32.01614Z" }, "papermill": { "duration": 4.734022, "end_time": "2026-03-26T12:56:07.070258", "exception": false, "start_time": "2026-03-26T12:56:02.336236", "status": "completed" }, "tags": [], "trusted": true, "id": "3iBUlgpsMlOc", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "721a1d15-9dd7-489e-b41c-48811ac2ef20" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "⏱️ elapsed=00:00 ⏳ remain=239:59 | 🔥 CPU= 0.0% 💾 RAM= 3.3% | 🧠 GPU0= 0.0% 🎮 VRAM0= 0.0%\n" ] } ], "execution_count": 4 }, { "cell_type": "code", "source": [ "!pip show numpy | grep Version:" ], "metadata": { "trusted": true, "execution": { "iopub.status.busy": "2026-04-06T17:49:32.018877Z", "iopub.execute_input": "2026-04-06T17:49:32.019295Z", "iopub.status.idle": "2026-04-06T17:49:34.084649Z", "shell.execute_reply.started": "2026-04-06T17:49:32.01927Z", "shell.execute_reply": "2026-04-06T17:49:34.083987Z" }, "id": "BIOZt3qJMlOc", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "19b7bed7-1c60-49a5-d208-381427d63a45" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Version: 1.26.4\n" ] } ], "execution_count": 5 }, { "cell_type": "code", "source": [ "# ============================================================================\n", "# Step 1: Biplet-Square Normalization\n", "# ============================================================================\n", "\n", "def generate_two_crops(img, size):\n", " if isinstance(size, (tuple, list)):\n", " size = size[0]\n", " width, height = img.size\n", " crops = {}\n", " if width >= height:\n", " crops['left'] = img.crop((0, 0, height, height)).resize((size, size), Image.LANCZOS)\n", " crops['right'] = img.crop((width-height,0, width, height)).resize((size, size), Image.LANCZOS)\n", " else:\n", " crops['top'] = img.crop((0, 0, width, width )).resize((size, size), Image.LANCZOS)\n", " crops['bottom'] = img.crop((0, height-width, width, height )).resize((size, size), Image.LANCZOS)\n", " return crops\n", "\n", "\n", "def normalize_image_sizes_biplet(input_dir, output_dir, size=512):\n", " print(\"\\n\" + \"=\"*60)\n", " print(\"Step 1: Biplet-Square Normalization\")\n", " print(\"=\"*60)\n", " os.makedirs(output_dir, exist_ok=True)\n", " count = 0\n", " for fname in sorted(os.listdir(input_dir)):\n", " if not fname.lower().endswith(('.jpg', '.jpeg', '.png')):\n", " continue\n", " img = Image.open(os.path.join(input_dir, fname))\n", " crops = generate_two_crops(img, size)\n", " base, ext = os.path.splitext(fname)\n", " for mode, crop in crops.items():\n", " crop.save(os.path.join(output_dir, f\"{base}_{mode}{ext}\"), quality=95)\n", " print(f\" ✓ {fname}: {img.size} → 2 crops\")\n", " count += 1\n", " print(f\" Total: {count} images → {count*2} crops\")\n", " return count" ], "metadata": { "execution": { "iopub.status.busy": "2026-04-06T17:49:34.085756Z", "iopub.execute_input": "2026-04-06T17:49:34.086081Z", "iopub.status.idle": "2026-04-06T17:49:34.100391Z", "shell.execute_reply.started": "2026-04-06T17:49:34.086046Z", "shell.execute_reply": "2026-04-06T17:49:34.099586Z" }, "papermill": { "duration": 0.013469, "end_time": "2026-03-26T12:56:07.085932", "exception": false, "start_time": "2026-03-26T12:56:07.072463", "status": "completed" }, "tags": [], "trusted": true, "id": "B0rFsg0vMlOc" }, "outputs": [], "execution_count": 6 }, { "cell_type": "code", "source": [ "# ============================================================================\n", "# Step 2: MASt3R-SfM (sparse_global_alignment)\n", "# ============================================================================\n", "\n", "def load_mast3r_model():\n", " from mast3r.model import AsymmetricMASt3R\n", " model = AsymmetricMASt3R.from_pretrained(Config.MAST3R_MODEL).to(Config.DEVICE)\n", " model.eval()\n", " print(f\" ✓ MASt3R loaded on {Config.DEVICE}\")\n", " return model" ], "metadata": { "execution": { "iopub.status.busy": "2026-04-06T17:49:34.101477Z", "iopub.execute_input": "2026-04-06T17:49:34.101998Z", "iopub.status.idle": "2026-04-06T17:49:34.28427Z", "shell.execute_reply.started": "2026-04-06T17:49:34.101969Z", "shell.execute_reply": "2026-04-06T17:49:34.2832Z" }, "papermill": { "duration": 0.039919, "end_time": "2026-03-26T12:56:07.127924", "exception": false, "start_time": "2026-03-26T12:56:07.088005", "status": "completed" }, "tags": [], "trusted": true, "id": "uL0rE-HeMlOd" }, "outputs": [], "execution_count": 7 }, { "cell_type": "code", "source": [ "def run_mast3r_sfm(model, image_paths, cache_dir, asmk_available=True):\n", " \"\"\"\n", " MASt3R-SfM Core Pipeline:\n", " make_pairs → sparse_global_alignment\n", " Completely replaces the old method (inference + global_aligner).\n", " \"\"\"\n", " print(\"\\n\" + \"=\"*60)\n", " print(\"Step 2: MASt3R-SfM (sparse_global_alignment)\")\n", " print(\"=\"*60)\n", " from mast3r.cloud_opt.sparse_ga import sparse_global_alignment\n", " from mast3r.image_pairs import make_pairs\n", " from dust3r.utils.image import load_images\n", "\n", " os.makedirs(cache_dir, exist_ok=True)\n", "\n", " # -- 2-A: Load Images --\n", " print(f\" Loading {len(image_paths)} images at size={Config.MAST3R_IMAGE_SIZE}…\")\n", " imgs = load_images(image_paths, size=Config.MAST3R_IMAGE_SIZE, verbose=False)\n", " print(f\" Loaded {len(imgs)} images\")\n", "\n", " # -- 2-B: Pair Selection --\n", " # 'retrieval-Na-k' : ASMK retrieval (requires sim_mat)\n", " # 'logwin-5' : Log window — good for unordered images ← default fallback\n", " # 'swin-5' : Sliding window — good for sequential images\n", " # 'complete' : All pairs (small scenes only)\n", " scene_graph = Config.SCENE_GRAPH\n", "\n", " # retrieval mode requires ASMK + sim_mat; fall back if unavailable\n", " if scene_graph.startswith('retrieval') and not asmk_available:\n", " print(f\" [WARN] ASMK not available → falling back to scene_graph='logwin-5'\")\n", " scene_graph = 'logwin-5'\n", "\n", " print(f\" scene_graph = '{scene_graph}'\")\n", "\n", " # -- 2-C: Build sim_mat for retrieval mode --\n", " sim_mat = None\n", " if scene_graph.startswith('retrieval'):\n", " try:\n", " from mast3r.retrieval.processor import Retriever\n", " retriever = Retriever(model, device=Config.DEVICE)\n", " sim_mat = retriever.get_similarity_matrix(imgs)\n", " print(f\" ✓ sim_mat built: shape={sim_mat.shape}\")\n", " except Exception as e:\n", " print(f\" [WARN] sim_mat construction failed ({e}) → falling back to 'logwin-5'\")\n", " scene_graph = 'logwin-5'\n", " sim_mat = None\n", "\n", " # -- 2-D: Make Pairs --\n", " pairs = make_pairs(\n", " imgs,\n", " scene_graph=scene_graph,\n", " prefilter=None,\n", " symmetrize=True,\n", " sim_mat=sim_mat, # None is safe for non-retrieval graphs\n", " )\n", " print(f\" ✓ make_pairs: {len(pairs)} pairs selected\")\n", "\n", " # -- 2-E: sparse_global_alignment --\n", " print(\" Running sparse_global_alignment…\")\n", " print(\" Memory before alignment:\")\n", " get_memory_info()\n", "\n", " scene = sparse_global_alignment(\n", " image_paths,\n", " pairs,\n", " cache_dir,\n", " model,\n", " lr1=Config.LR1,\n", " niter1=Config.NITER1,\n", " lr2=Config.LR2,\n", " niter2=Config.NITER2,\n", " device=Config.DEVICE,\n", " opt_depth=Config.OPT_DEPTH,\n", " shared_intrinsics=Config.SHARED_INTRINSICS,\n", " matching_conf_thr=3.0,\n", " )\n", "\n", " print(\" ✓ sparse_global_alignment done\")\n", " print(\" Memory after alignment:\")\n", " get_memory_info()\n", " return scene" ], "metadata": { "trusted": true, "execution": { "iopub.status.busy": "2026-04-06T17:49:34.285711Z", "iopub.execute_input": "2026-04-06T17:49:34.286086Z", "iopub.status.idle": "2026-04-06T17:49:34.363298Z", "shell.execute_reply.started": "2026-04-06T17:49:34.286048Z", "shell.execute_reply": "2026-04-06T17:49:34.362738Z" }, "id": "REV-5F9JMlOd" }, "outputs": [], "execution_count": 8 }, { "cell_type": "code", "source": [ "# ============================================================================\n", "# Step 3: COLMAP Conversion Utility\n", "# ============================================================================\n", "\n", "def write_next_bytes(fid, data, fmt):\n", " if isinstance(data, (list, tuple, np.ndarray)):\n", " fid.write(struct.pack(\"<\" + fmt, *data))\n", " else:\n", " fid.write(struct.pack(\"<\" + fmt, data))\n", "\n", "\n", "def matrix_to_qvec_tvec(matrix):\n", " from scipy.spatial.transform import Rotation\n", " R = matrix[:3, :3]\n", " t = matrix[:3, 3]\n", " q = Rotation.from_matrix(R).as_quat() # [x,y,z,w]\n", " qvec = np.array([q[3], q[0], q[1], q[2]])\n", " return qvec, t\n", "\n", "\n", "def write_cameras_binary(cameras, path):\n", " with open(path, \"wb\") as f:\n", " write_next_bytes(f, len(cameras), \"Q\")\n", " for cam_id, cam in cameras.items():\n", " write_next_bytes(f, cam_id, \"I\")\n", " write_next_bytes(f, 1, \"I\") # PINHOLE\n", " write_next_bytes(f, cam['width'], \"Q\")\n", " write_next_bytes(f, cam['height'], \"Q\")\n", " for p in cam['params']:\n", " write_next_bytes(f, float(p), \"d\")\n", "\n", "\n", "def write_images_binary(images, path):\n", " with open(path, \"wb\") as f:\n", " write_next_bytes(f, len(images), \"Q\")\n", " for img_id, img in images.items():\n", " write_next_bytes(f, img_id, \"I\")\n", " write_next_bytes(f, img['qvec'], \"dddd\")\n", " write_next_bytes(f, img['tvec'], \"ddd\")\n", " write_next_bytes(f, img['camera_id'],\"I\")\n", " for ch in img['name']:\n", " write_next_bytes(f, ch.encode(\"utf-8\"), \"c\")\n", " write_next_bytes(f, b\"\\x00\", \"c\")\n", " write_next_bytes(f, 0, \"Q\") # no 2D points\n", "\n", "\n", "def write_points3d_binary(points3D, path):\n", " with open(path, \"wb\") as f:\n", " write_next_bytes(f, len(points3D), \"Q\")\n", " for pid, pt in enumerate(points3D):\n", " write_next_bytes(f, pid, \"Q\")\n", " write_next_bytes(f, pt['xyz'], \"ddd\")\n", " write_next_bytes(f, pt['rgb'], \"BBB\")\n", " write_next_bytes(f, pt['error'], \"d\")\n", " write_next_bytes(f, 0, \"Q\") # empty track" ], "metadata": { "execution": { "iopub.status.busy": "2026-04-06T17:49:34.36426Z", "iopub.execute_input": "2026-04-06T17:49:34.364569Z", "iopub.status.idle": "2026-04-06T17:49:34.379605Z", "shell.execute_reply.started": "2026-04-06T17:49:34.364548Z", "shell.execute_reply": "2026-04-06T17:49:34.378966Z" }, "papermill": { "duration": 0.039919, "end_time": "2026-03-26T12:56:07.127924", "exception": false, "start_time": "2026-03-26T12:56:07.088005", "status": "completed" }, "tags": [], "trusted": true, "id": "35gWY1vIMlOd" }, "outputs": [], "execution_count": 9 }, { "cell_type": "code", "source": [ "# ============================================================================\n", "# Step 3: Extract scene → COLMAP ----------- fix 2026/03/28 20:00\n", "# ============================================================================\n", "\n", "def extract_scene_data(scene, verbose=True):\n", " cameras = {}\n", " images_data = {}\n", " points3D = []\n", "\n", " if verbose:\n", " print(\"\\n Extracting scene data…\")\n", "\n", " num_views = scene.n_imgs\n", " if verbose:\n", " print(f\" Views: {num_views}\")\n", "\n", " # ---- Camera + Pose ----\n", " focals = scene.get_focals().detach().cpu().numpy()\n", " pps = scene.get_principal_points().detach().cpu().numpy()\n", " poses = scene.get_im_poses().detach().cpu().numpy()\n", "\n", " for idx in range(num_views):\n", " img = scene.imgs[idx]\n", " h, w = img.shape[:2]\n", " fx = fy = float(focals[idx])\n", " cx, cy = float(pps[idx][0]), float(pps[idx][1])\n", " cameras[idx] = {\n", " 'model': 'PINHOLE', 'width': w, 'height': h,\n", " 'params': [fx, fy, cx, cy],\n", " }\n", " p = poses[idx]\n", " qvec, tvec = (matrix_to_qvec_tvec(np.linalg.inv(p))\n", " if abs(np.linalg.det(p)) > 1e-10\n", " else (np.array([1., 0., 0., 0.]), np.zeros(3)))\n", " images_data[idx + 1] = {\n", " 'qvec': qvec, 'tvec': tvec,\n", " 'camera_id': idx,\n", " 'name': f'image_{idx:04d}.jpg',\n", " 'xys': np.array([]), 'point3D_ids': np.array([]),\n", " }\n", "\n", " # ---- 3D Point Cloud ----\n", " def to_numpy(x):\n", " if hasattr(x, 'detach'):\n", " return x.detach().cpu().numpy()\n", " elif isinstance(x, list):\n", " if x and hasattr(x[0], 'detach'):\n", " return torch.stack(x).detach().cpu().numpy()\n", " return np.array(x)\n", " return np.asarray(x)\n", "\n", " def unwrap_pts(raw, V):\n", " \"\"\"→ (V, N, 3) の numpy配列に正規化\"\"\"\n", " if isinstance(raw, (list, tuple)):\n", " if len(raw) == V:\n", " # per-view リスト\n", " return np.stack([to_numpy(r).reshape(-1, 3) for r in raw])\n", " else:\n", " arr = to_numpy(raw[0])\n", " else:\n", " arr = to_numpy(raw)\n", " if arr.ndim == 4: # (V, H, W, 3)\n", " arr = arr.reshape(V, -1, 3)\n", " elif arr.ndim == 3 and arr.shape[-1] == 3:\n", " if arr.shape[0] != V: # (N, ?, 3) → reshape\n", " arr = arr.reshape(V, -1, 3)\n", " return arr # (V, N, 3)\n", "\n", " def unwrap_masks(raw, V, N):\n", " \"\"\"→ (V, N) の bool numpy配列に正規化\"\"\"\n", " # per-view リスト\n", " if isinstance(raw, (list, tuple)) and len(raw) == V:\n", " try:\n", " arrs = [to_numpy(m).reshape(-1).astype(bool) for m in raw]\n", " if all(len(a) == N for a in arrs):\n", " return np.stack(arrs)\n", " except Exception:\n", " pass\n", "\n", " # 1要素リスト (stacked)\n", " if isinstance(raw, (list, tuple)) and len(raw) == 1:\n", " try:\n", " arr = to_numpy(raw[0]).astype(bool).reshape(V, -1)\n", " if arr.shape[1] == N:\n", " return arr\n", " except Exception:\n", " pass\n", "\n", " # Tensor直接\n", " if hasattr(raw, 'detach'):\n", " try:\n", " arr = raw.detach().cpu().numpy().astype(bool)\n", " if arr.shape == (V, N):\n", " return arr\n", " return arr.reshape(V, N)\n", " except Exception:\n", " pass\n", "\n", " # object配列 (shape=()) → .item() で中身を取り出す\n", " arr = np.asarray(raw)\n", " if arr.dtype == object:\n", " try:\n", " inner = arr.item() # Python list や tuple が出てくる想定\n", " return unwrap_masks(inner, V, N)\n", " except Exception:\n", " pass\n", "\n", " if verbose:\n", " print(f\" [WARN] Could not parse masks, using all-True\")\n", " return np.ones((V, N), dtype=bool)\n", "\n", " if verbose:\n", " print(\" Extracting 3D points…\")\n", "\n", " try:\n", " pts3d_raw = scene.get_dense_pts3d(clean_depth=False)\n", " masks_raw = scene.get_masks()\n", "\n", " pts_vn3 = unwrap_pts(pts3d_raw, num_views) # (V, N, 3)\n", " N = pts_vn3.shape[1]\n", " masks_vn = unwrap_masks(masks_raw, num_views, N) # (V, N)\n", "\n", " if verbose:\n", " print(f\" [DEBUG] pts_vn3 shape={pts_vn3.shape}\")\n", " print(f\" [DEBUG] masks_vn shape={masks_vn.shape}\")\n", "\n", " all_pts, all_cols = [], []\n", "\n", " for idx in range(num_views):\n", " pts_flat = pts_vn3[idx] # (N, 3)\n", " mask_flat = masks_vn[idx] # (N,) bool\n", "\n", " valid_pts = pts_flat[mask_flat]\n", " if len(valid_pts) == 0:\n", " continue\n", "\n", " # 色\n", " img = to_numpy(scene.imgs[idx])\n", " if img.ndim == 3 and img.shape[0] in (1, 3, 4):\n", " img = np.transpose(img, (1, 2, 0))\n", " img_flat = img.reshape(-1, 3)\n", "\n", " if len(img_flat) == N:\n", " valid_col = img_flat[mask_flat]\n", " else:\n", " # サイズ不一致の場合は有効点数分を切り出す\n", " valid_col = img_flat[:len(valid_pts)]\n", "\n", " if valid_col.size == 0:\n", " valid_col = np.zeros((len(valid_pts), 3), dtype=np.uint8)\n", " elif valid_col.max() <= 1.0:\n", " valid_col = (valid_col * 255).clip(0, 255).astype(np.uint8)\n", " else:\n", " valid_col = valid_col.clip(0, 255).astype(np.uint8)\n", "\n", " all_pts.append(valid_pts)\n", " all_cols.append(valid_col)\n", "\n", " if all_pts:\n", " pts_all = np.vstack(all_pts)\n", " cols_all = np.vstack(all_cols)\n", "\n", " valid = np.all(np.isfinite(pts_all), axis=1)\n", " pts_all, cols_all = pts_all[valid], cols_all[valid]\n", "\n", " MAX_PTS = 5_000_000\n", " if len(pts_all) > MAX_PTS:\n", " idx_s = np.random.choice(len(pts_all), MAX_PTS, replace=False)\n", " pts_all, cols_all = pts_all[idx_s], cols_all[idx_s]\n", "\n", " points3D = [\n", " {'xyz': pt, 'rgb': col, 'error': 0.0,\n", " 'image_ids': np.array([]), 'point2D_idxs': np.array([])}\n", " for pt, col in zip(pts_all, cols_all)\n", " ]\n", " if verbose:\n", " print(f\" ✓ Points: {len(points3D):,}\")\n", " else:\n", " if verbose:\n", " print(\" [WARN] all_pts is empty — no valid masked points\")\n", "\n", " except Exception as e:\n", " import traceback\n", " if verbose:\n", " print(f\" [ERROR] 3D point extraction failed: {e}\")\n", " traceback.print_exc()\n", "\n", " if verbose:\n", " print(f\" Summary: {len(cameras)} cams, {len(images_data)} imgs, {len(points3D):,} pts\")\n", "\n", " return cameras, images_data, points3D" ], "metadata": { "trusted": true, "execution": { "iopub.status.busy": "2026-04-06T17:49:34.380564Z", "iopub.execute_input": "2026-04-06T17:49:34.380787Z", "iopub.status.idle": "2026-04-06T17:49:34.403327Z", "shell.execute_reply.started": "2026-04-06T17:49:34.380768Z", "shell.execute_reply": "2026-04-06T17:49:34.402685Z" }, "id": "jvuZQ7HiMlOd" }, "outputs": [], "execution_count": 10 }, { "cell_type": "code", "source": [], "metadata": { "trusted": true, "id": "sUcx-aMAMlOd" }, "outputs": [], "execution_count": 10 }, { "cell_type": "code", "source": [ "def save_images(scene, images_dir, processed_image_paths=None):\n", " images_dir = Path(images_dir)\n", " images_dir.mkdir(parents=True, exist_ok=True)\n", " num_views = len(scene.imgs) if hasattr(scene, 'imgs') else len(scene.views)\n", " imgs_src = scene.imgs if hasattr(scene, 'imgs') else scene.views\n", "\n", " import shutil\n", " if processed_image_paths:\n", " for idx, src in enumerate(processed_image_paths[:num_views]):\n", " shutil.copy2(src, images_dir / f'image_{idx:04d}.jpg')\n", " else:\n", " for idx in range(num_views):\n", " img = imgs_src[idx]\n", " if isinstance(img, torch.Tensor):\n", " img = img.detach().cpu().numpy()\n", " if img.ndim == 3 and img.shape[0] in (1, 3, 4):\n", " img = np.transpose(img, (1, 2, 0))\n", " if img.max() <= 1.0:\n", " img = (img * 255).astype(np.uint8)\n", " if img.ndim == 2:\n", " img = np.stack([img]*3, axis=-1)\n", " Image.fromarray(img).save(images_dir / f'image_{idx:04d}.jpg')\n", "\n", "\n", "def save_depth_maps(scene, depth_dir):\n", " depth_dir = Path(depth_dir)\n", " depth_dir.mkdir(parents=True, exist_ok=True)\n", " try:\n", " depthmaps = scene.get_depthmaps()\n", " if depthmaps is None:\n", " return\n", " for idx, d in enumerate(depthmaps):\n", " if isinstance(d, torch.Tensor):\n", " d = d.detach().cpu().numpy()\n", " np.save(depth_dir / f'depth_{idx:04d}.npy', d)\n", " print(f\" Saved {len(depthmaps)} depth maps → {depth_dir}\")\n", " except Exception as e:\n", " print(f\" [WARN] depth maps: {e}\")\n", "\n", "\n", "def convert_scene_to_colmap(scene, output_dir, processed_image_paths=None, verbose=True):\n", " output_dir = Path(output_dir)\n", " sparse_dir = output_dir / \"sparse\" / \"0\"\n", " images_dir = output_dir / \"images\"\n", " depth_dir = output_dir / \"depth\"\n", " sparse_dir.mkdir(parents=True, exist_ok=True)\n", "\n", " if verbose:\n", " print(\"\\n\" + \"=\"*60)\n", " print(\"Step 3: Converting to COLMAP format\")\n", " print(\"=\"*60)\n", " print(f\" Output: {output_dir}\")\n", "\n", " cameras, images_data, points3D = extract_scene_data(scene, verbose=verbose)\n", "\n", " save_images(scene, images_dir, processed_image_paths)\n", " save_depth_maps(scene, depth_dir)\n", "\n", " write_cameras_binary(cameras, sparse_dir / \"cameras.bin\")\n", " write_images_binary(images_data, sparse_dir / \"images.bin\")\n", " write_points3d_binary(points3D, sparse_dir / \"points3D.bin\")\n", "\n", " if verbose:\n", " print(f\" ✓ cameras.bin ({len(cameras)} cameras)\")\n", " print(f\" ✓ images.bin ({len(images_data)} images)\")\n", " print(f\" ✓ points3D.bin ({len(points3D)} points)\")\n", " print(\"✓ COLMAP conversion complete\")\n", "\n", " return output_dir\n", "\n", "\n", "# ============================================================================\n", "# Step 4: PLY Conversion\n", "# ============================================================================\n", "\n", "def convert_colmap_to_ply(sparse_dir, ply_path):\n", " import pycolmap\n", " from plyfile import PlyData, PlyElement\n", "\n", " print(\"\\n\" + \"=\"*60)\n", " print(\"Step 4: COLMAP bin → PLY\")\n", " print(\"=\"*60)\n", "\n", " recon = pycolmap.Reconstruction(str(sparse_dir))\n", " print(f\" Cameras: {len(recon.cameras)}\")\n", " print(f\" Images: {len(recon.images)}\")\n", " print(f\" Points: {len(recon.points3D)}\")\n", "\n", " if len(recon.points3D) == 0:\n", " print(\" [WARN] No 3D points found\")\n", " return 0\n", "\n", " pts = np.array([p.xyz for p in recon.points3D.values()])\n", " cols = np.array([p.color for p in recon.points3D.values()])\n", "\n", " print(f\" X: [{pts[:,0].min():.3f}, {pts[:,0].max():.3f}]\")\n", " print(f\" Y: [{pts[:,1].min():.3f}, {pts[:,1].max():.3f}]\")\n", " print(f\" Z: [{pts[:,2].min():.3f}, {pts[:,2].max():.3f}]\")\n", "\n", " verts = np.array(\n", " [(p[0], p[1], p[2], c[0], c[1], c[2]) for p, c in zip(pts, cols)],\n", " dtype=[('x','f4'),('y','f4'),('z','f4'),\n", " ('red','u1'),('green','u1'),('blue','u1')]\n", " )\n", " PlyData([PlyElement.describe(verts, 'vertex')]).write(ply_path)\n", " print(f\" ✓ PLY saved → {ply_path}\")\n", " return len(pts)" ], "metadata": { "execution": { "iopub.status.busy": "2026-04-06T17:49:34.404201Z", "iopub.execute_input": "2026-04-06T17:49:34.404464Z", "iopub.status.idle": "2026-04-06T17:49:34.419441Z", "shell.execute_reply.started": "2026-04-06T17:49:34.404444Z", "shell.execute_reply": "2026-04-06T17:49:34.418818Z" }, "papermill": { "duration": 0.039919, "end_time": "2026-03-26T12:56:07.127924", "exception": false, "start_time": "2026-03-26T12:56:07.088005", "status": "completed" }, "tags": [], "trusted": true, "id": "AK3jlVkLMlOd" }, "outputs": [], "execution_count": 11 }, { "cell_type": "code", "source": [ "# ============================================================================\n", "# Step 5: PLY Viewer (for Kaggle Notebook)\n", "# ============================================================================\n", "\n", "def display_ply_viewer(ply_file_path):\n", " from IPython.display import HTML, display as ipy_display\n", "\n", " with open(ply_file_path, 'rb') as f:\n", " ply_b64 = base64.b64encode(f.read()).decode('utf-8')\n", "\n", " html = f\"\"\"\n", "