{ "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", "
\n", "
Loading…
\n", " \n", "
\n", " \n", " \n", " \"\"\"\n", " ipy_display(HTML(html))" ], "metadata": { "execution": { "iopub.status.busy": "2026-04-06T17:49:34.420203Z", "iopub.execute_input": "2026-04-06T17:49:34.420438Z", "iopub.status.idle": "2026-04-06T17:49:34.436357Z", "shell.execute_reply.started": "2026-04-06T17:49:34.420417Z", "shell.execute_reply": "2026-04-06T17:49:34.435779Z" }, "papermill": { "duration": 0.009872, "end_time": "2026-03-26T12:56:07.140176", "exception": false, "start_time": "2026-03-26T12:56:07.130304", "status": "completed" }, "tags": [], "trusted": true, "id": "sZM_vDJHMlOd" }, "outputs": [], "execution_count": 12 }, { "cell_type": "code", "source": [ "!pip show numpy | grep Version:" ], "metadata": { "trusted": true, "execution": { "iopub.status.busy": "2026-04-06T17:49:34.437222Z", "iopub.execute_input": "2026-04-06T17:49:34.437774Z", "iopub.status.idle": "2026-04-06T17:49:36.524893Z", "shell.execute_reply.started": "2026-04-06T17:49:34.437752Z", "shell.execute_reply": "2026-04-06T17:49:36.52421Z" }, "id": "WvyH2N7iMlOe", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "8b8b7781-29cf-4460-daf7-d0f84c9c3670" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Version: 1.26.4\n" ] } ], "execution_count": 13 }, { "cell_type": "code", "source": [ "# ============================================================================\n", "# MAIN PIPELINE\n", "# ============================================================================\n", "\n", "# ---------- Path Settings ----------\n", "IMAGE_DIR = \"/content/drive/MyDrive/your_folder/fountain40\"\n", "OUTPUT_DIR = \"/content/output\"\n", "CACHE_DIR = os.path.join(OUTPUT_DIR, \"sfm_cache\")\n", "COLMAP_DIR = os.path.join(OUTPUT_DIR, \"colmap\")\n", "PLY_PATH = os.path.join(COLMAP_DIR, \"point_cloud.ply\")\n", "SQUARE_DIR = os.path.join(OUTPUT_DIR, \"processed_images\")\n", "\n", "os.makedirs(OUTPUT_DIR, exist_ok=True)" ], "metadata": { "execution": { "iopub.status.busy": "2026-04-06T17:49:36.527948Z", "iopub.execute_input": "2026-04-06T17:49:36.528175Z", "iopub.status.idle": "2026-04-06T17:49:36.533197Z", "shell.execute_reply.started": "2026-04-06T17:49:36.528152Z", "shell.execute_reply": "2026-04-06T17:49:36.532589Z" }, "papermill": { "duration": 274.479691, "end_time": "2026-03-26T13:00:41.621869", "exception": false, "start_time": "2026-03-26T12:56:07.142178", "status": "completed" }, "tags": [], "trusted": true, "id": "WX3MLZIcMlOe" }, "outputs": [], "execution_count": 14 }, { "cell_type": "code", "source": [ "# ---------- 0. Environment Setup ----------\n", "setup_base_environment()\n", "clear_memory()" ], "metadata": { "trusted": true, "_kg_hide-output": true, "execution": { "iopub.status.busy": "2026-04-06T17:49:36.534034Z", "iopub.execute_input": "2026-04-06T17:49:36.534309Z", "iopub.status.idle": "2026-04-06T17:50:09.924118Z", "shell.execute_reply.started": "2026-04-06T17:49:36.534278Z", "shell.execute_reply": "2026-04-06T17:50:09.923456Z" }, "id": "lcXem-fiMlOe", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "e094627e-ae44-4c17-8ff8-396d21e28d1f" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "\n", "============================================================\n", "Step 0-A: Base Environment Setup\n", "============================================================\n", " $ /usr/bin/python3 -m pip uninstall -y numpy\n", " $ /usr/bin/python3 -m pip install numpy==1.26.4\n", " $ /usr/bin/python3 -m pip install torch torchvision torchaudio\n", " $ /usr/bin/python3 -m pip install opencv-python pillow imageio imageio-ffmpeg plyfile tqdm scipy psutil roma trimesh matplotlib\n", " $ /usr/bin/python3 -m pip install transformers==4.40.0\n", " $ /usr/bin/python3 -m pip install pycolmap\n", "✓ Base environment ready\n" ] } ], "execution_count": 15 }, { "cell_type": "code", "source": [ "!pip show numpy | grep Version:" ], "metadata": { "trusted": true, "execution": { "iopub.status.busy": "2026-04-06T17:50:09.924978Z", "iopub.execute_input": "2026-04-06T17:50:09.925249Z", "iopub.status.idle": "2026-04-06T17:50:12.066269Z", "shell.execute_reply.started": "2026-04-06T17:50:09.925222Z", "shell.execute_reply": "2026-04-06T17:50:12.065517Z" }, "id": "RBQp_Ih6MlOe", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "698ded1a-82f5-4256-f2bc-a99aa166ae71" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Version: 2.4.4\n" ] } ], "execution_count": 16 }, { "cell_type": "code", "source": [ "setup_mast3r()" ], "metadata": { "trusted": true, "execution": { "iopub.status.busy": "2026-04-06T17:50:12.067628Z", "iopub.execute_input": "2026-04-06T17:50:12.067907Z", "iopub.status.idle": "2026-04-06T17:52:25.400382Z", "shell.execute_reply.started": "2026-04-06T17:50:12.06788Z", "shell.execute_reply": "2026-04-06T17:52:25.399751Z" }, "_kg_hide-output": true, "id": "WcuV-k58MlOe", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "713b4d7b-fbc1-44d1-eb5e-9d4b2f2c47dc" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "\n", "============================================================\n", "Step 0-B: MASt3R Setup\n", "============================================================\n", "⏱️ elapsed=03:00 ⏳ remain=236:59 | 🔥 CPU= 7.3% 💾 RAM= 4.0% | 🧠 GPU0= 0.0% 🎮 VRAM0= 0.8%\n", "Warning, cannot find cuda-compiled version of RoPE2D, using a slow pytorch version instead\n", " ✓ MASt3R import OK\n", "✓ MASt3R ready\n" ] } ], "execution_count": 17 }, { "cell_type": "code", "source": [ "# ASMK (Fallback to swin if setup fails)\n", "asmk_ok = setup_asmk()\n", "clear_memory()" ], "metadata": { "execution": { "iopub.status.busy": "2026-04-06T17:52:25.401238Z", "iopub.execute_input": "2026-04-06T17:52:25.401601Z", "iopub.status.idle": "2026-04-06T17:52:41.5606Z", "shell.execute_reply.started": "2026-04-06T17:52:25.401578Z", "shell.execute_reply": "2026-04-06T17:52:41.559803Z" }, "papermill": { "duration": 274.479691, "end_time": "2026-03-26T13:00:41.621869", "exception": false, "start_time": "2026-03-26T12:56:07.142178", "status": "completed" }, "tags": [], "trusted": true, "id": "AUuPsrrvMlOe", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "46c89fb0-07c2-4cd0-f775-fe92fbd71ade" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "\n", "============================================================\n", "Step 0-C: ASMK Setup (for retrieval pair selection)\n", "============================================================\n", " $ /usr/bin/python3 -m pip install cython\n", " ✓ ASMK import OK\n" ] } ], "execution_count": 18 }, { "cell_type": "code", "source": [ "!pip show numpy | grep Version:\n", "\n", "!pip uninstall numpy -y\n", "!pip install \"numpy==1.26.4\" \"scipy>=1.12\" --quiet\n", "\n", "!pip show numpy | grep Version:" ], "metadata": { "trusted": true, "execution": { "iopub.status.busy": "2026-04-06T17:52:41.561633Z", "iopub.execute_input": "2026-04-06T17:52:41.561965Z", "iopub.status.idle": "2026-04-06T17:52:52.421496Z", "shell.execute_reply.started": "2026-04-06T17:52:41.561919Z", "shell.execute_reply": "2026-04-06T17:52:52.420529Z" }, "id": "-q6AjUb2MlOe", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "9c0fdf01-b7e5-453e-cf2e-c667bdd7c194" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Version: 2.4.4\n", "Found existing installation: numpy 2.4.4\n", "Uninstalling numpy-2.4.4:\n", " Successfully uninstalled numpy-2.4.4\n", "\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", "sentence-transformers 5.3.0 requires transformers<6.0.0,>=4.41.0, but you have transformers 4.40.0 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[0mVersion: 1.26.4\n" ] } ], "execution_count": 19 }, { "cell_type": "code", "source": [ "# ---------- 1. Biplet Normalization ----------\n", "normalize_image_sizes_biplet(IMAGE_DIR, SQUARE_DIR, size=Config.SQUARE_SIZE)\n", "\n", "image_paths = sorted([\n", " os.path.join(SQUARE_DIR, f)\n", " for f in os.listdir(SQUARE_DIR)\n", " if f.lower().endswith(('.jpg', '.jpeg', '.png'))\n", "])\n", "print(f\"\\n📸 {len(image_paths)} images ready\")" ], "metadata": { "execution": { "iopub.status.busy": "2026-04-06T17:52:52.422971Z", "iopub.execute_input": "2026-04-06T17:52:52.423248Z", "iopub.status.idle": "2026-04-06T17:52:58.038813Z", "shell.execute_reply.started": "2026-04-06T17:52:52.42322Z", "shell.execute_reply": "2026-04-06T17:52:58.038003Z" }, "papermill": { "duration": 12.082868, "end_time": "2026-03-26T13:00:53.831242", "exception": true, "start_time": "2026-03-26T13:00:41.748374", "status": "failed" }, "tags": [], "trusted": true, "id": "CgJu6DrgMlOe", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "5ee64aab-07f4-45d6-8b38-39fe4b64751d" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "\n", "============================================================\n", "Step 1: Biplet-Square Normalization\n", "============================================================\n", " ✓ image_001.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_002.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_003.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_004.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_005.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_006.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_007.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_008.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_009.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_010.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_011.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_012.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_013.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_014.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_015.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_016.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_017.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_018.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_019.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_020.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_021.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_022.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_023.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_024.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_025.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_026.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_027.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_028.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_029.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_030.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_031.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_032.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_033.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_034.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_035.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_036.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_037.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_038.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_039.jpeg: (1440, 1920) → 2 crops\n", " ✓ image_040.jpeg: (1440, 1920) → 2 crops\n", " Total: 40 images → 80 crops\n", "\n", "📸 80 images ready\n" ] } ], "execution_count": 20 }, { "cell_type": "code", "source": [ "!pip show numpy | grep Version:" ], "metadata": { "trusted": true, "execution": { "iopub.status.busy": "2026-04-06T17:52:58.040056Z", "iopub.execute_input": "2026-04-06T17:52:58.040398Z", "iopub.status.idle": "2026-04-06T17:53:00.13663Z", "shell.execute_reply.started": "2026-04-06T17:52:58.040365Z", "shell.execute_reply": "2026-04-06T17:53:00.135711Z" }, "id": "wNVD6s0cMlOe", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "afedfff3-66a9-413e-cb2e-73d81e2b83d9" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Version: 1.26.4\n" ] } ], "execution_count": 21 }, { "cell_type": "code", "source": [ "# ---------- 2. MASt3R-SfM ----------\n", "model = load_mast3r_model()\n", "\n", "scene = run_mast3r_sfm(\n", " model,\n", " image_paths,\n", " cache_dir=CACHE_DIR,\n", " asmk_available=asmk_ok,\n", ")\n", "\n", "del model\n", "clear_memory()" ], "metadata": { "execution": { "iopub.status.busy": "2026-04-06T17:53:00.137978Z", "iopub.execute_input": "2026-04-06T17:53:00.1383Z", "iopub.status.idle": "2026-04-06T18:08:48.305441Z", "shell.execute_reply.started": "2026-04-06T17:53:00.138264Z", "shell.execute_reply": "2026-04-06T18:08:48.304688Z" }, "papermill": { "duration": 12.082868, "end_time": "2026-03-26T13:00:53.831242", "exception": true, "start_time": "2026-03-26T13:00:41.748374", "status": "failed" }, "tags": [], "trusted": true, "id": "EHyN5OqZMlOe", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "e4b0b168-2ae6-41d5-a97f-725ae00953f2" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "... loading model from /content/mast3r/checkpoints/MASt3R_ViTLarge_BaseDecoder_512_catmlpdpt_metric.pth\n", "instantiating : AsymmetricMASt3R(enc_depth=24, dec_depth=12, enc_embed_dim=1024, dec_embed_dim=768, enc_num_heads=16, dec_num_heads=12, pos_embed='RoPE100',img_size=(512, 512), head_type='catmlp+dpt', output_mode='pts3d+desc24', depth_mode=('exp', -inf, inf), conf_mode=('exp', 1, inf), patch_embed_cls='PatchEmbedDust3R', two_confs=True, desc_conf_mode=('exp', 0, inf), landscape_only=False)\n", "\n", " ✓ MASt3R loaded on cuda\n", "\n", "============================================================\n", "Step 2: MASt3R-SfM (sparse_global_alignment)\n", "============================================================\n" ] }, { "output_type": "stream", "name": "stderr", "text": [ "/content/mast3r/dust3r/dust3r/cloud_opt/base_opt.py:275: FutureWarning: `torch.cuda.amp.autocast(args...)` is deprecated. Please use `torch.amp.autocast('cuda', args...)` instead.\n", " @torch.cuda.amp.autocast(enabled=False)\n" ] }, { "output_type": "stream", "name": "stdout", "text": [ " Loading 80 images at size=512…\n", " Loaded 80 images\n", " scene_graph = 'retrieval-10-15'\n", " [WARN] sim_mat construction failed (No module named 'faiss') → falling back to 'logwin-5'\n", " ✓ make_pairs: 800 pairs selected\n", " Running sparse_global_alignment…\n", " Memory before alignment:\n", " GPU - Allocated: 2.58 GB, Reserved: 2.68 GB\n", " CPU - Usage: 8.3%\n" ] }, { "output_type": "stream", "name": "stderr", "text": [ "\r 0%| | 0/800 [00:00> final loss = 0.13503803312778473\n" ] }, { "output_type": "stream", "name": "stderr", "text": [ " 97%|█████████▋| 290/300 [01:54<00:03, 2.53it/s, lr=0.0000, loss=0.573]" ] }, { "output_type": "stream", "name": "stdout", "text": [ "⏱️ elapsed=15:00 ⏳ remain=224:59 | 🔥 CPU= 11.0% 💾 RAM= 8.7% | 🧠 GPU0= 25.0% 🎮 VRAM0= 24.5%\n" ] }, { "output_type": "stream", "name": "stderr", "text": [ "100%|██████████| 300/300 [01:58<00:00, 2.53it/s, lr=0.0000, loss=0.568]\n" ] }, { "output_type": "stream", "name": "stdout", "text": [ ">> final loss = 0.5675967931747437\n", "Final focals = [527.1656 542.53357 524.326 541.3448 517.9595 546.69037 515.5983\n", " 551.5943 514.54095 555.28784 513.928 556.96246 511.2091 556.24615\n", " 510.22964 554.66754 508.0994 556.95636 508.20773 554.1811 510.2956\n", " 552.1906 514.2344 548.94104 513.96497 549.1159 513.6511 553.3412\n", " 512.40155 555.99207 508.48114 560.3865 509.8687 559.085 509.86774\n", " 557.7523 512.30994 557.3793 507.42514 560.2667 507.77997 563.32434\n", " 509.42593 563.9998 516.51715 563.178 521.0214 562.3778 520.2069\n", " 567.1606 521.47626 564.6666 522.8941 562.8961 522.62036 560.45996\n", " 520.80084 561.34174 518.98224 562.2094 519.7321 562.429 519.5602\n", " 560.76685 516.54425 564.60767 516.94464 563.5815 519.1268 563.6148\n", " 519.5324 564.416 520.44116 568.58813 523.83795 569.6674 528.67975\n", " 568.74 531.5526 565.7716 ]\n", " ✓ sparse_global_alignment done\n", " Memory after alignment:\n", " GPU - Allocated: 2.67 GB, Reserved: 5.26 GB\n", " CPU - Usage: 8.7%\n" ] } ], "execution_count": 22 }, { "cell_type": "code", "source": [ "# ---------- 3. COLMAP Conversion ----------\n", "convert_scene_to_colmap(\n", " scene,\n", " output_dir=COLMAP_DIR,\n", " processed_image_paths=image_paths,\n", " verbose=True,\n", ")" ], "metadata": { "papermill": { "duration": 12.082868, "end_time": "2026-03-26T13:00:53.831242", "exception": true, "start_time": "2026-03-26T13:00:41.748374", "status": "failed" }, "tags": [], "trusted": true, "execution": { "iopub.status.busy": "2026-04-06T18:08:48.306539Z", "iopub.execute_input": "2026-04-06T18:08:48.307162Z", "iopub.status.idle": "2026-04-06T18:09:27.185975Z", "shell.execute_reply.started": "2026-04-06T18:08:48.307136Z", "shell.execute_reply": "2026-04-06T18:09:27.18532Z" }, "id": "IZGowCelMlOe", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "36f311a7-9c53-4597-f03f-c345c46b748e" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "\n", "============================================================\n", "Step 3: Converting to COLMAP format\n", "============================================================\n", " Output: /content/output/colmap\n", "\n", " Extracting scene data…\n", " Views: 80\n", " Extracting 3D points…\n", " [WARN] Could not parse masks, using all-True\n", " [DEBUG] pts_vn3 shape=(80, 196608, 3)\n", " [DEBUG] masks_vn shape=(80, 196608)\n", " ✓ Points: 5,000,000\n", " Summary: 80 cams, 80 imgs, 5,000,000 pts\n", " Saved 80 depth maps → /content/output/colmap/depth\n", " ✓ cameras.bin (80 cameras)\n", " ✓ images.bin (80 images)\n", " ✓ points3D.bin (5000000 points)\n", "✓ COLMAP conversion complete\n" ] }, { "output_type": "execute_result", "data": { "text/plain": [ "PosixPath('/content/output/colmap')" ] }, "metadata": {}, "execution_count": 23 } ], "execution_count": 23 }, { "cell_type": "code", "source": [ "!pip show numpy | grep Version:" ], "metadata": { "trusted": true, "execution": { "iopub.status.busy": "2026-04-06T18:09:27.187348Z", "iopub.execute_input": "2026-04-06T18:09:27.187593Z", "iopub.status.idle": "2026-04-06T18:09:29.428734Z", "shell.execute_reply.started": "2026-04-06T18:09:27.187571Z", "shell.execute_reply": "2026-04-06T18:09:29.427944Z" }, "id": "ta-iXVWqMlOe", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "9aefb16f-5c64-47b8-ed5a-bbf699f97ada" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Version: 1.26.4\n" ] } ], "execution_count": 24 }, { "cell_type": "code", "source": [ "# ---------- 4. PLY Output ----------\n", "sparse_dir = os.path.join(COLMAP_DIR, \"sparse\", \"0\")\n", "n = convert_colmap_to_ply(sparse_dir, PLY_PATH)\n", "\n", "# ---------- 5. Viewer ----------\n", "#if n > 0:\n", "# display_ply_viewer(PLY_PATH)\n", "\n", "print(\"\\n🎉 Pipeline complete!\")\n", "print(f\" PLY : {PLY_PATH}\")\n", "print(f\" COLMAP: {COLMAP_DIR}\")" ], "metadata": { "papermill": { "duration": null, "end_time": null, "exception": null, "start_time": null, "status": "pending" }, "tags": [], "trusted": true, "execution": { "iopub.status.busy": "2026-04-06T18:09:29.430054Z", "iopub.execute_input": "2026-04-06T18:09:29.430304Z", "iopub.status.idle": "2026-04-06T18:10:07.796696Z", "shell.execute_reply.started": "2026-04-06T18:09:29.430279Z", "shell.execute_reply": "2026-04-06T18:10:07.795818Z" }, "id": "8umJBHXbMlOe", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "5ccfd0be-75e9-48a9-fa1f-c831873fbaa0" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "\n", "============================================================\n", "Step 4: COLMAP bin → PLY\n", "============================================================\n", " Cameras: 80\n", " Images: 80\n", " Points: 5000000\n", " X: [-36.452, 7.695]\n", " Y: [-31.787, 10.960]\n", " Z: [-20.766, 17.420]\n", " ✓ PLY saved → /content/output/colmap/point_cloud.ply\n", "\n", "🎉 Pipeline complete!\n", " PLY : /content/output/colmap/point_cloud.ply\n", " COLMAP: /content/output/colmap\n" ] } ], "execution_count": 25 }, { "cell_type": "code", "source": [ "logger.stop()" ], "metadata": { "papermill": { "duration": null, "end_time": null, "exception": null, "start_time": null, "status": "pending" }, "tags": [], "trusted": true, "execution": { "iopub.status.busy": "2026-04-06T18:10:07.797817Z", "iopub.execute_input": "2026-04-06T18:10:07.798233Z", "iopub.status.idle": "2026-04-06T18:10:07.801876Z", "shell.execute_reply.started": "2026-04-06T18:10:07.798198Z", "shell.execute_reply": "2026-04-06T18:10:07.801161Z" }, "id": "j88mY_ZNMlOe" }, "outputs": [], "execution_count": 26 } ] }