{ "metadata": { "kernelspec": { "name": "python3", "display_name": "Python 3", "language": "python" }, "language_info": { "name": "python", "version": "3.12.12", "mimetype": "text/x-python", "codemirror_mode": { "name": "ipython", "version": 3 }, "pygments_lexer": "ipython3", "nbconvert_exporter": "python", "file_extension": ".py" }, "colab": { "provenance": [], "gpuType": "T4" }, "accelerator": "GPU", "kaggle": { "accelerator": "nvidiaTeslaT4", "dataSources": [ { "sourceId": 14571475, "sourceType": "datasetVersion", "datasetId": 1429416 } ], "dockerImageVersionId": 31260, "isInternetEnabled": true, "language": "python", "sourceType": "notebook", "isGpuEnabled": true } }, "nbformat_minor": 0, "nbformat": 4, "cells": [ { "cell_type": "markdown", "source": [ "# **biplet-asmk-mast3r-ps2-gs-kg-32-colab**\n", "\n" ], "metadata": { "id": "qDQLX3PArmh8" } }, { "cell_type": "markdown", "source": [ "https://huggingface.co/datasets/stpete2/ipynb/blob/main/biplet-asmk-mast3r-ps2-gs-kg-32.ipynb" ], "metadata": { "id": "Yhla_oBUjLmD" } }, { "cell_type": "code", "source": [ "#これを元にcolab化 2025/01/22 16:00" ], "metadata": { "id": "UyF0gaG8jOXu" }, "execution_count": 1, "outputs": [] }, { "cell_type": "markdown", "source": [ "v.32 全面見直し" ], "metadata": { "id": "uNZNREeejLmD" } }, { "cell_type": "code", "source": [], "metadata": { "trusted": true, "id": "yH63Q7yCjLmE" }, "outputs": [], "execution_count": 1 }, { "cell_type": "code", "source": [ "# =====================================================================\n", "# CELL 1: Install Dependencies\n", "# =====================================================================\n", "!pip install roma einops timm huggingface_hub\n", "!pip install opencv-python pillow tqdm pyaml cython plyfile\n", "!pip install pycolmap trimesh\n", "!pip uninstall -y numpy scipy\n", "!pip install numpy==1.26.4 scipy==1.11.4\n", "break" ], "metadata": { "trusted": true, "id": "h5Exo6FBjLmE", "colab": { "base_uri": "https://localhost:8080/", "height": 1000 }, "outputId": "bcd49f5d-064f-44d3-d902-378fa44d3363" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Collecting roma\n", " Downloading roma-1.5.4-py3-none-any.whl.metadata (5.5 kB)\n", "Requirement already satisfied: einops in /usr/local/lib/python3.12/dist-packages (0.8.1)\n", "Requirement already satisfied: timm in /usr/local/lib/python3.12/dist-packages (1.0.24)\n", "Requirement already satisfied: huggingface_hub in /usr/local/lib/python3.12/dist-packages (0.36.0)\n", "Requirement already satisfied: torch in /usr/local/lib/python3.12/dist-packages (from timm) (2.9.0+cu126)\n", "Requirement already satisfied: torchvision in /usr/local/lib/python3.12/dist-packages (from timm) (0.24.0+cu126)\n", "Requirement already satisfied: pyyaml in /usr/local/lib/python3.12/dist-packages (from timm) (6.0.3)\n", "Requirement already satisfied: safetensors in /usr/local/lib/python3.12/dist-packages (from timm) (0.7.0)\n", "Requirement already satisfied: filelock in /usr/local/lib/python3.12/dist-packages (from huggingface_hub) (3.20.3)\n", "Requirement already satisfied: fsspec>=2023.5.0 in /usr/local/lib/python3.12/dist-packages (from huggingface_hub) (2025.3.0)\n", "Requirement already satisfied: packaging>=20.9 in /usr/local/lib/python3.12/dist-packages (from huggingface_hub) (25.0)\n", "Requirement already satisfied: requests in /usr/local/lib/python3.12/dist-packages (from huggingface_hub) (2.32.4)\n", "Requirement already satisfied: tqdm>=4.42.1 in /usr/local/lib/python3.12/dist-packages (from huggingface_hub) (4.67.1)\n", "Requirement already satisfied: typing-extensions>=3.7.4.3 in /usr/local/lib/python3.12/dist-packages (from huggingface_hub) (4.15.0)\n", "Requirement already satisfied: hf-xet<2.0.0,>=1.1.3 in /usr/local/lib/python3.12/dist-packages (from huggingface_hub) (1.2.0)\n", "Requirement already satisfied: charset_normalizer<4,>=2 in /usr/local/lib/python3.12/dist-packages (from requests->huggingface_hub) (3.4.4)\n", "Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.12/dist-packages (from requests->huggingface_hub) (3.11)\n", "Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.12/dist-packages (from requests->huggingface_hub) (2.5.0)\n", "Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.12/dist-packages (from requests->huggingface_hub) (2026.1.4)\n", "Requirement already satisfied: setuptools in /usr/local/lib/python3.12/dist-packages (from torch->timm) (75.2.0)\n", "Requirement already satisfied: sympy>=1.13.3 in /usr/local/lib/python3.12/dist-packages (from torch->timm) (1.14.0)\n", "Requirement already satisfied: networkx>=2.5.1 in /usr/local/lib/python3.12/dist-packages (from torch->timm) (3.6.1)\n", "Requirement already satisfied: jinja2 in /usr/local/lib/python3.12/dist-packages (from torch->timm) (3.1.6)\n", "Requirement already satisfied: nvidia-cuda-nvrtc-cu12==12.6.77 in /usr/local/lib/python3.12/dist-packages (from torch->timm) (12.6.77)\n", "Requirement already satisfied: nvidia-cuda-runtime-cu12==12.6.77 in /usr/local/lib/python3.12/dist-packages (from torch->timm) (12.6.77)\n", "Requirement already satisfied: nvidia-cuda-cupti-cu12==12.6.80 in /usr/local/lib/python3.12/dist-packages (from torch->timm) (12.6.80)\n", "Requirement already satisfied: nvidia-cudnn-cu12==9.10.2.21 in /usr/local/lib/python3.12/dist-packages (from torch->timm) (9.10.2.21)\n", "Requirement already satisfied: nvidia-cublas-cu12==12.6.4.1 in /usr/local/lib/python3.12/dist-packages (from torch->timm) (12.6.4.1)\n", "Requirement already satisfied: nvidia-cufft-cu12==11.3.0.4 in /usr/local/lib/python3.12/dist-packages (from torch->timm) (11.3.0.4)\n", "Requirement already satisfied: nvidia-curand-cu12==10.3.7.77 in /usr/local/lib/python3.12/dist-packages (from torch->timm) (10.3.7.77)\n", "Requirement already satisfied: nvidia-cusolver-cu12==11.7.1.2 in /usr/local/lib/python3.12/dist-packages (from torch->timm) (11.7.1.2)\n", "Requirement already satisfied: nvidia-cusparse-cu12==12.5.4.2 in /usr/local/lib/python3.12/dist-packages (from torch->timm) (12.5.4.2)\n", "Requirement already satisfied: nvidia-cusparselt-cu12==0.7.1 in /usr/local/lib/python3.12/dist-packages (from torch->timm) (0.7.1)\n", "Requirement already satisfied: nvidia-nccl-cu12==2.27.5 in /usr/local/lib/python3.12/dist-packages (from torch->timm) (2.27.5)\n", "Requirement already satisfied: nvidia-nvshmem-cu12==3.3.20 in /usr/local/lib/python3.12/dist-packages (from torch->timm) (3.3.20)\n", "Requirement already satisfied: nvidia-nvtx-cu12==12.6.77 in /usr/local/lib/python3.12/dist-packages (from torch->timm) (12.6.77)\n", "Requirement already satisfied: nvidia-nvjitlink-cu12==12.6.85 in /usr/local/lib/python3.12/dist-packages (from torch->timm) (12.6.85)\n", "Requirement already satisfied: nvidia-cufile-cu12==1.11.1.6 in /usr/local/lib/python3.12/dist-packages (from torch->timm) (1.11.1.6)\n", "Requirement already satisfied: triton==3.5.0 in /usr/local/lib/python3.12/dist-packages (from torch->timm) (3.5.0)\n", "Requirement already satisfied: numpy in /usr/local/lib/python3.12/dist-packages (from torchvision->timm) (2.0.2)\n", "Requirement already satisfied: pillow!=8.3.*,>=5.3.0 in /usr/local/lib/python3.12/dist-packages (from torchvision->timm) (11.3.0)\n", "Requirement already satisfied: mpmath<1.4,>=1.1.0 in /usr/local/lib/python3.12/dist-packages (from sympy>=1.13.3->torch->timm) (1.3.0)\n", "Requirement already satisfied: MarkupSafe>=2.0 in /usr/local/lib/python3.12/dist-packages (from jinja2->torch->timm) (3.0.3)\n", "Downloading roma-1.5.4-py3-none-any.whl (25 kB)\n", "Installing collected packages: roma\n", "Successfully installed roma-1.5.4\n", "Requirement already satisfied: opencv-python in /usr/local/lib/python3.12/dist-packages (4.12.0.88)\n", "Requirement already satisfied: pillow in /usr/local/lib/python3.12/dist-packages (11.3.0)\n", "Requirement already satisfied: tqdm in /usr/local/lib/python3.12/dist-packages (4.67.1)\n", "Collecting pyaml\n", " Downloading pyaml-25.7.0-py3-none-any.whl.metadata (12 kB)\n", "Requirement already satisfied: cython in /usr/local/lib/python3.12/dist-packages (3.0.12)\n", "Collecting plyfile\n", " Downloading plyfile-1.1.3-py3-none-any.whl.metadata (43 kB)\n", "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m43.3/43.3 kB\u001b[0m \u001b[31m3.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", "\u001b[?25hRequirement already satisfied: numpy<2.3.0,>=2 in /usr/local/lib/python3.12/dist-packages (from opencv-python) (2.0.2)\n", "Requirement already satisfied: PyYAML in /usr/local/lib/python3.12/dist-packages (from pyaml) (6.0.3)\n", "Downloading pyaml-25.7.0-py3-none-any.whl (26 kB)\n", "Downloading plyfile-1.1.3-py3-none-any.whl (36 kB)\n", "Installing collected packages: pyaml, plyfile\n", "Successfully installed plyfile-1.1.3 pyaml-25.7.0\n", "Collecting pycolmap\n", " Downloading pycolmap-3.13.0-cp312-cp312-manylinux_2_28_x86_64.whl.metadata (10 kB)\n", "Collecting trimesh\n", " Downloading trimesh-4.11.1-py3-none-any.whl.metadata (13 kB)\n", "Requirement already satisfied: numpy in /usr/local/lib/python3.12/dist-packages (from pycolmap) (2.0.2)\n", "Downloading pycolmap-3.13.0-cp312-cp312-manylinux_2_28_x86_64.whl (20.3 MB)\n", "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m20.3/20.3 MB\u001b[0m \u001b[31m116.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", "\u001b[?25hDownloading trimesh-4.11.1-py3-none-any.whl (740 kB)\n", "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m740.4/740.4 kB\u001b[0m \u001b[31m62.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", "\u001b[?25hInstalling collected packages: trimesh, pycolmap\n", "Successfully installed pycolmap-3.13.0 trimesh-4.11.1\n", "Found existing installation: numpy 2.0.2\n", "Uninstalling numpy-2.0.2:\n", " Successfully uninstalled numpy-2.0.2\n", "Found existing installation: scipy 1.16.3\n", "Uninstalling scipy-1.16.3:\n", " Successfully uninstalled scipy-1.16.3\n", "Collecting numpy==1.26.4\n", " Downloading numpy-1.26.4-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (61 kB)\n", "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m61.0/61.0 kB\u001b[0m \u001b[31m4.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", "\u001b[?25hCollecting scipy==1.11.4\n", " Downloading scipy-1.11.4-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (60 kB)\n", "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m60.4/60.4 kB\u001b[0m \u001b[31m6.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", "\u001b[?25hDownloading numpy-1.26.4-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (18.0 MB)\n", "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m18.0/18.0 MB\u001b[0m \u001b[31m129.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", "\u001b[?25hDownloading scipy-1.11.4-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (35.8 MB)\n", "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m35.8/35.8 MB\u001b[0m \u001b[31m19.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", "\u001b[?25hInstalling collected packages: numpy, scipy\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.50.0 requires numpy>=2, but you have numpy 1.26.4 which is incompatible.\n", "libpysal 4.14.1 requires scipy>=1.12.0, but you have scipy 1.11.4 which is incompatible.\n", "opencv-contrib-python 4.12.0.88 requires numpy<2.3.0,>=2; python_version >= \"3.9\", but you have numpy 1.26.4 which is incompatible.\n", "inequality 1.1.2 requires scipy>=1.12, but you have scipy 1.11.4 which is incompatible.\n", "spopt 0.7.0 requires scipy>=1.12.0, but you have scipy 1.11.4 which is incompatible.\n", "jaxlib 0.7.2 requires numpy>=2.0, but you have numpy 1.26.4 which is incompatible.\n", "jaxlib 0.7.2 requires scipy>=1.13, but you have scipy 1.11.4 which is incompatible.\n", "pytensor 2.36.3 requires numpy>=2.0, but you have numpy 1.26.4 which is incompatible.\n", "opencv-python 4.12.0.88 requires numpy<2.3.0,>=2; python_version >= \"3.9\", but you have numpy 1.26.4 which is incompatible.\n", "giddy 2.3.8 requires scipy>=1.12, but you have scipy 1.11.4 which is incompatible.\n", "tobler 0.13.0 requires numpy>=2.0, but you have numpy 1.26.4 which is incompatible.\n", "tobler 0.13.0 requires scipy>=1.13, but you have scipy 1.11.4 which is incompatible.\n", "esda 2.8.1 requires scipy>=1.12, but you have scipy 1.11.4 which is incompatible.\n", "tsfresh 0.21.1 requires scipy>=1.14.0; python_version >= \"3.10\", but you have scipy 1.11.4 which is incompatible.\n", "access 1.1.10.post3 requires scipy>=1.14.1, but you have scipy 1.11.4 which is incompatible.\n", "jax 0.7.2 requires numpy>=2.0, but you have numpy 1.26.4 which is incompatible.\n", "jax 0.7.2 requires scipy>=1.13, but you have scipy 1.11.4 which is incompatible.\n", "opencv-python-headless 4.12.0.88 requires numpy<2.3.0,>=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", "mapclassify 2.10.0 requires scipy>=1.12, but you have scipy 1.11.4 which is incompatible.\u001b[0m\u001b[31m\n", "\u001b[0mSuccessfully installed numpy-1.26.4 scipy-1.11.4\n" ] }, { "output_type": "display_data", "data": { "application/vnd.colab-display-data+json": { "pip_warning": { "packages": [ "numpy" ] }, "id": "d6aae877fb5e40cab59820f769d9203c" } }, "metadata": {} }, { "output_type": "error", "ename": "SyntaxError", "evalue": "'break' outside loop (ipython-input-2884072918.py, line 9)", "traceback": [ "\u001b[0;36m File \u001b[0;32m\"/tmp/ipython-input-2884072918.py\"\u001b[0;36m, line \u001b[0;32m9\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": "code", "source": [ "# =====================================================================\n", "# CELL 2: Restart Kernel (Run this after Cell 1)\n", "# =====================================================================\n", "# Restart kernel, then run from this cell\n", "\n", "from google.colab import drive\n", "drive.mount('/content/drive')\n", "\n", "# =====================================================================\n", "# CELL 3: Verify NumPy Version\n", "# =====================================================================\n", "import numpy as np\n", "print(f\"✓ np: {np.__version__} - {np.__file__}\")\n", "!pip show numpy | grep Version\n", "\n", "# =====================================================================\n", "# CELL 4: Verify Roma Installation\n", "# =====================================================================\n", "try:\n", " import roma\n", " print(\"✓ roma is installed\")\n", "except ModuleNotFoundError:\n", " print(\"⚠️ roma not found, installing...\")\n", " !pip install roma\n", " import roma\n", " print(\"✓ roma installed\")" ], "metadata": { "trusted": true, "id": "XgxGC30cjLmF", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "cf85e49c-71bd-4cbb-cec5-12561aa47d65" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Mounted at /content/drive\n", "✓ np: 1.26.4 - /usr/local/lib/python3.12/dist-packages/numpy/__init__.py\n", "Version: 1.26.4\n", "Version 3.1, 31 March 2009\n", " Version 3, 29 June 2007\n", " 5. Conveying Modified Source Versions.\n", " 14. Revised Versions of this License.\n", "✓ roma is installed\n" ] } ], "execution_count": 1 }, { "cell_type": "code", "source": [ "# =====================================================================\n", "# CELL 5: Clone Repositories\n", "# =====================================================================\n", "import os\n", "import sys\n", "\n", "# MASt3Rをクローン\n", "if not os.path.exists('/content/mast3r'):\n", " print(\"Cloning MASt3R repository...\")\n", " !git clone --recursive https://github.com/naver/mast3r.git /content/mast3r\n", " print(\"✓ MASt3R cloned\")\n", "else:\n", " print(\"✓ MASt3R already exists\")\n", "\n", "# DUSt3Rをクローン(MASt3R内に必要)\n", "if not os.path.exists('/content/mast3r/dust3r'):\n", " print(\"Cloning DUSt3R repository...\")\n", " !git clone --recursive https://github.com/naver/dust3r.git /content/mast3r/dust3r\n", " print(\"✓ DUSt3R cloned\")\n", "else:\n", " print(\"✓ DUSt3R already exists\")\n", "\n", "# ASMKをクローン\n", "if not os.path.exists('/content/asmk'):\n", " print(\"Cloning ASMK repository...\")\n", " !git clone https://github.com/jenicek/asmk.git /content/asmk\n", " print(\"✓ ASMK cloned\")\n", "else:\n", " print(\"✓ ASMK already exists\")\n", "\n", "# パスを追加\n", "sys.path.insert(0, '/content/mast3r')\n", "sys.path.insert(0, '/content/mast3r/dust3r')\n", "sys.path.insert(0, '/content/asmk')\n", "\n", "# 確認\n", "try:\n", " from dust3r.model import AsymmetricCroCo3DStereo\n", " print(\"✓ dust3r.model imported successfully\")\n", "except ImportError as e:\n", " print(f\"✗ Import error: {e}\")\n", "\n", "# croco(MASt3Rの依存関係)もクローン\n", "if not os.path.exists('/content/mast3r/croco'):\n", " print(\"Cloning CroCo repository...\")\n", " !git clone --recursive https://github.com/naver/croco.git /content/mast3r/croco\n", " print(\"✓ CroCo cloned\")\n", "\n", "# CroCo v2の依存関係\n", "if not os.path.exists('/content/mast3r/croco/models/curope'):\n", " print(\"Cloning CuRoPe...\")\n", " !git clone --recursive https://github.com/naver/curope.git /content/mast3r/croco/models/curope\n", " print(\"✓ CuRoPe cloned\")\n", "\n", "# =====================================================================\n", "# CELL 6: Clone and Build Gaussian Splatting\n", "# =====================================================================\n", "print(\"\\n\" + \"=\"*70)\n", "print(\"STEP 2: Clone Gaussian Splatting\")\n", "print(\"=\"*70)\n", "WORK_DIR = \"/content/gaussian-splatting\"\n", "\n", "import subprocess\n", "if not os.path.exists(WORK_DIR):\n", " subprocess.run([\n", " \"git\", \"clone\", \"--recursive\",\n", " \"https://github.com/graphdeco-inria/gaussian-splatting.git\",\n", " WORK_DIR\n", " ], capture_output=True)\n", " print(\"✓ Cloned\")\n", "else:\n", " print(\"✓ Already exists\")\n", "\n", "# インストールが必要なディレクトリ\n", "submodules = [\n", " \"/content/gaussian-splatting/submodules/diff-gaussian-rasterization\",\n", " \"/content/gaussian-splatting/submodules/simple-knn\"\n", "]\n", "\n", "for path in submodules:\n", " print(f\"Installing {path}...\")\n", " subprocess.run([\"pip\", \"install\", path], check=True)\n", "\n", "print(\"✓ Custom CUDA modules installed.\")\n", "\n", "# =====================================================================\n", "# CELL 7: Verify NumPy Again\n", "# =====================================================================\n", "import numpy as np\n", "print(f\"✓ np: {np.__version__} - {np.__file__}\")\n", "!pip show numpy | grep Version" ], "metadata": { "trusted": true, "id": "EF_Z8VDLjLmF", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "c469f2a0-6b5d-4f11-e0bb-3f8c6237b9d6" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Cloning MASt3R repository...\n", "Cloning into '/content/mast3r'...\n", "remote: Enumerating objects: 269, done.\u001b[K\n", "remote: Counting objects: 100% (170/170), done.\u001b[K\n", "remote: Compressing objects: 100% (61/61), done.\u001b[K\n", "remote: Total 269 (delta 115), reused 109 (delta 109), pack-reused 99 (from 1)\u001b[K\n", "Receiving objects: 100% (269/269), 3.59 MiB | 9.19 MiB/s, done.\n", "Resolving deltas: 100% (151/151), done.\n", "Submodule 'dust3r' (https://github.com/naver/dust3r) registered for path 'dust3r'\n", "Cloning into '/content/mast3r/dust3r'...\n", "remote: Enumerating objects: 611, done. \n", "remote: Total 611 (delta 0), reused 0 (delta 0), pack-reused 611 (from 1) \n", "Receiving objects: 100% (611/611), 756.60 KiB | 2.80 MiB/s, done.\n", "Resolving deltas: 100% (355/355), done.\n", "Submodule path 'dust3r': checked out '3cc8c88c413bb9e34c41db0e0eef99c2ee010b12'\n", "Submodule 'croco' (https://github.com/naver/croco) registered for path 'dust3r/croco'\n", "Cloning into '/content/mast3r/dust3r/croco'...\n", "remote: Enumerating objects: 198, done. \n", "remote: Counting objects: 100% (87/87), done. \n", "remote: Compressing objects: 100% (54/54), done. \n", "remote: Total 198 (delta 54), reused 33 (delta 33), pack-reused 111 (from 1) \n", "Receiving objects: 100% (198/198), 403.93 KiB | 1.92 MiB/s, done.\n", "Resolving deltas: 100% (94/94), done.\n", "Submodule path 'dust3r/croco': checked out 'd7de0705845239092414480bd829228723bf20de'\n", "✓ MASt3R cloned\n", "✓ DUSt3R already exists\n", "Cloning ASMK repository...\n", "Cloning into '/content/asmk'...\n", "remote: Enumerating objects: 138, done.\u001b[K\n", "remote: Counting objects: 100% (138/138), done.\u001b[K\n", "remote: Compressing objects: 100% (75/75), done.\u001b[K\n", "remote: Total 138 (delta 78), reused 117 (delta 59), pack-reused 0 (from 0)\u001b[K\n", "Receiving objects: 100% (138/138), 152.04 KiB | 1.07 MiB/s, done.\n", "Resolving deltas: 100% (78/78), done.\n", "✓ ASMK cloned\n", "Warning, cannot find cuda-compiled version of RoPE2D, using a slow pytorch version instead\n", "✓ dust3r.model imported successfully\n", "Cloning CroCo repository...\n", "Cloning into '/content/mast3r/croco'...\n", "remote: Enumerating objects: 198, done.\u001b[K\n", "remote: Counting objects: 100% (87/87), done.\u001b[K\n", "remote: Compressing objects: 100% (54/54), done.\u001b[K\n", "remote: Total 198 (delta 54), reused 33 (delta 33), pack-reused 111 (from 1)\u001b[K\n", "Receiving objects: 100% (198/198), 403.93 KiB | 2.16 MiB/s, done.\n", "Resolving deltas: 100% (94/94), done.\n", "✓ CroCo cloned\n", "\n", "======================================================================\n", "STEP 2: Clone Gaussian Splatting\n", "======================================================================\n", "✓ Cloned\n", "Installing /content/gaussian-splatting/submodules/diff-gaussian-rasterization...\n", "Installing /content/gaussian-splatting/submodules/simple-knn...\n", "✓ Custom CUDA modules installed.\n", "✓ np: 1.26.4 - /usr/local/lib/python3.12/dist-packages/numpy/__init__.py\n", "Version: 1.26.4\n", "Version 3.1, 31 March 2009\n", " Version 3, 29 June 2007\n", " 5. Conveying Modified Source Versions.\n", " 14. Revised Versions of this License.\n" ] } ], "execution_count": 2 }, { "cell_type": "code", "source": [ "# =====================================================================\n", "# CELL 8: Import Core Libraries and Configure Memory\n", "# =====================================================================\n", "import os\n", "import sys\n", "import gc\n", "import torch\n", "import numpy as np\n", "from pathlib import Path\n", "from tqdm import tqdm\n", "import torch.nn.functional as F\n", "import shutil\n", "from PIL import Image\n", "\n", "# MEMORY MANAGEMENT\n", "os.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'expandable_segments:True'\n", "\n", "def clear_memory():\n", " \"\"\"メモリクリア関数\"\"\"\n", " gc.collect()\n", " if torch.cuda.is_available():\n", " torch.cuda.empty_cache()\n", " torch.cuda.synchronize()\n", "\n", "# CONFIGURATION\n", "class Config:\n", " DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n", " MAST3R_WEIGHTS = \"naver/MASt3R_ViTLarge_BaseDecoder_512_catmlpdpt_metric\"\n", " DUST3R_WEIGHTS = \"naver/DUSt3R_ViTLarge_BaseDecoder_512_dpt\"\n", " RETRIEVAL_TOPK = 10\n", " IMAGE_SIZE = 224\n", "\n", "# =====================================================================\n", "# CELL 9: Image Preprocessing Functions\n", "# =====================================================================\n", "def normalize_image_sizes_biplet(input_dir, output_dir=None, size=1024):\n", " \"\"\"\n", " Generates two square crops (Left & Right or Top & Bottom)\n", " from each image in a directory.\n", " \"\"\"\n", " if output_dir is None:\n", " output_dir = input_dir + \"_biplet\"\n", "\n", " os.makedirs(output_dir, exist_ok=True)\n", "\n", " print(f\"\\n=== Generating Biplet Crops ({size}x{size}) ===\")\n", "\n", " converted_count = 0\n", " size_stats = {}\n", "\n", " for img_file in tqdm(sorted(os.listdir(input_dir)), desc=\"Creating biplets\"):\n", " if not img_file.lower().endswith(('.jpg', '.jpeg', '.png')):\n", " continue\n", "\n", " input_path = os.path.join(input_dir, img_file)\n", "\n", " try:\n", " img = Image.open(input_path)\n", " original_size = img.size\n", "\n", " size_key = f\"{original_size[0]}x{original_size[1]}\"\n", " size_stats[size_key] = size_stats.get(size_key, 0) + 1\n", "\n", " # Generate 2 crops\n", " crops = generate_two_crops(img, size)\n", "\n", " base_name, ext = os.path.splitext(img_file)\n", " for mode, cropped_img in crops.items():\n", " output_path = os.path.join(output_dir, f\"{base_name}_{mode}{ext}\")\n", " cropped_img.save(output_path, quality=95)\n", "\n", " converted_count += 1\n", "\n", " except Exception as e:\n", " print(f\" ✗ Error processing {img_file}: {e}\")\n", "\n", " print(f\"\\n✓ Biplet generation complete:\")\n", " print(f\" Source images: {converted_count}\")\n", " print(f\" Biplet crops generated: {converted_count * 2}\")\n", " print(f\" Original size distribution: {size_stats}\")\n", "\n", " return output_dir\n", "\n", "\n", "def generate_two_crops(img, size):\n", " \"\"\"\n", " Crops the image into a square and returns 2 variations\n", " \"\"\"\n", " width, height = img.size\n", " crop_size = min(width, height)\n", " crops = {}\n", "\n", " if width > height:\n", " # Landscape → Left & Right\n", " positions = {\n", " 'left': 0,\n", " 'right': width - crop_size\n", " }\n", " for mode, x_offset in positions.items():\n", " box = (x_offset, 0, x_offset + crop_size, crop_size)\n", " crops[mode] = img.crop(box).resize(\n", " (size, size),\n", " Image.Resampling.LANCZOS\n", " )\n", " else:\n", " # Portrait or Square → Top & Bottom\n", " positions = {\n", " 'top': 0,\n", " 'bottom': height - crop_size\n", " }\n", " for mode, y_offset in positions.items():\n", " box = (0, y_offset, crop_size, y_offset + crop_size)\n", " crops[mode] = img.crop(box).resize(\n", " (size, size),\n", " Image.Resampling.LANCZOS\n", " )\n", "\n", " return crops\n", "\n", "# =====================================================================\n", "# CELL 10: Image Loading Function\n", "# =====================================================================\n", "def load_images_from_directory(image_dir, max_images=200):\n", " \"\"\"ディレクトリから画像をロード\"\"\"\n", " print(f\"\\nLoading images from: {image_dir}\")\n", "\n", " valid_extensions = {'.jpg', '.jpeg', '.png', '.bmp'}\n", " image_paths = []\n", "\n", " for ext in valid_extensions:\n", " image_paths.extend(sorted(Path(image_dir).glob(f'*{ext}')))\n", " image_paths.extend(sorted(Path(image_dir).glob(f'*{ext.upper()}')))\n", "\n", " image_paths = sorted(set(str(p) for p in image_paths))\n", "\n", " if len(image_paths) > max_images:\n", " print(f\"⚠️ Limiting from {len(image_paths)} to {max_images} images\")\n", " image_paths = image_paths[:max_images]\n", "\n", " print(f\"✓ Found {len(image_paths)} images\")\n", " return image_paths" ], "metadata": { "trusted": true, "id": "_rFAsFGDjLmF" }, "outputs": [], "execution_count": 3 }, { "cell_type": "code", "source": [ "# =====================================================================\n", "# CELL 11: MASt3R Model Loading\n", "# =====================================================================\n", "def load_mast3r_model(device):\n", " \"\"\"MASt3Rモデルをロード\"\"\"\n", " print(\"\\n=== Loading MASt3R Model ===\")\n", "\n", " if '/content/mast3r' not in sys.path:\n", " sys.path.insert(0, '/content/mast3r')\n", " if '/content/mast3r/dust3r' not in sys.path:\n", " sys.path.insert(0, '/content/mast3r/dust3r')\n", "\n", " from dust3r.model import AsymmetricCroCo3DStereo\n", "\n", " try:\n", " print(f\"Attempting to load: {Config.MAST3R_WEIGHTS}\")\n", " model = AsymmetricCroCo3DStereo.from_pretrained(Config.MAST3R_WEIGHTS).to(device)\n", " print(\"✓ Loaded MASt3R model\")\n", " except Exception as e:\n", " print(f\"⚠️ Failed to load MASt3R: {e}\")\n", " print(f\"Trying DUSt3R instead: {Config.DUST3R_WEIGHTS}\")\n", " model = AsymmetricCroCo3DStereo.from_pretrained(Config.DUST3R_WEIGHTS).to(device)\n", " print(\"✓ Loaded DUSt3R model as fallback\")\n", "\n", " model.eval()\n", " print(f\"✓ Model loaded on {device}\")\n", " return model\n", "\n", "# =====================================================================\n", "# CELL 12: Feature Extraction (FIXED)\n", "# =====================================================================\n", "def extract_mast3r_features(model, image_paths, device, batch_size=1):\n", " \"\"\"MASt3Rモデルを使用して特徴量を抽出(修正版)\"\"\"\n", " print(\"\\n=== Extracting MASt3R Features ===\")\n", " from dust3r.utils.image import load_images\n", " from dust3r.inference import inference\n", "\n", " all_features = []\n", "\n", " for i in tqdm(range(len(image_paths)), desc=\"Features\"):\n", " img_path = image_paths[i]\n", "\n", " # 同じ画像を2回ロード(ペアとして)\n", " images = load_images([img_path, img_path], size=Config.IMAGE_SIZE)\n", " pairs = [(images[0], images[1])]\n", "\n", " with torch.no_grad():\n", " output = inference(pairs, model, device, batch_size=1)\n", "\n", " try:\n", " # outputから特徴量を抽出(修正版)\n", " if isinstance(output, dict):\n", " if 'pred1' in output:\n", " pred1 = output['pred1']\n", " if isinstance(pred1, dict):\n", " # 'desc'または'conf'を優先的に使用\n", " if 'desc' in pred1:\n", " desc = pred1['desc']\n", " elif 'conf' in pred1:\n", " desc = pred1['conf']\n", " elif 'pts3d' in pred1:\n", " desc = pred1['pts3d']\n", " else:\n", " desc = list(pred1.values())[0]\n", " else:\n", " desc = pred1\n", " elif 'view1' in output:\n", " view1 = output['view1']\n", " if isinstance(view1, dict):\n", " desc = view1.get('desc', view1.get('conf', view1.get('pts3d', list(view1.values())[0])))\n", " else:\n", " desc = view1\n", " else:\n", " desc = list(output.values())[0]\n", " elif isinstance(output, tuple) and len(output) == 2:\n", " view1, view2 = output\n", " if isinstance(view1, dict):\n", " desc = view1.get('desc', view1.get('conf', view1.get('pts3d', list(view1.values())[0])))\n", " else:\n", " desc = view1\n", " elif isinstance(output, list):\n", " item = output[0]\n", " if isinstance(item, dict):\n", " desc = item.get('desc', item.get('conf', item.get('pts3d', list(item.values())[0])))\n", " else:\n", " desc = item\n", " else:\n", " desc = output\n", "\n", " # テンソルをCPUに移動して保存\n", " if isinstance(desc, torch.Tensor):\n", " desc = desc.detach().cpu()\n", "\n", " # 4次元の場合はbatch次元を削除\n", " if desc.dim() == 4:\n", " desc = desc.squeeze(0)\n", "\n", " # 特徴量の次元が小さすぎる場合(RGB画像など)は平均プーリング\n", " if desc.shape[-1] < 16:\n", " # [H, W, 3] -> [H, W, 64] に拡張\n", " desc = desc.unsqueeze(-1).repeat(1, 1, 1, 64 // desc.shape[-1]).reshape(desc.shape[0], desc.shape[1], -1)\n", "\n", " all_features.append(desc)\n", "\n", " except Exception as e:\n", " print(f\"⚠️ Error extracting features for image {i}: {e}\")\n", " # デフォルト特徴量\n", " all_features.append(torch.zeros((Config.IMAGE_SIZE, Config.IMAGE_SIZE, 64)))\n", "\n", " # メモリクリア\n", " del output, images, pairs\n", " if i % 10 == 0:\n", " torch.cuda.empty_cache()\n", "\n", " print(f\"✓ Extracted features for {len(all_features)} images\")\n", " if all_features:\n", " first_feat = all_features[0]\n", " if isinstance(first_feat, torch.Tensor):\n", " print(f\" Feature shape: {first_feat.shape}\")\n", "\n", " return all_features\n", "\n", "# =====================================================================\n", "# CELL 13: ASMK Similarity Computation (FIXED)\n", "# =====================================================================\n", "def compute_asmk_similarity(features, codebook=None):\n", " \"\"\"ASMKを使用して類似度行列を計算(修正版)\"\"\"\n", " print(\"\\n=== Computing ASMK Similarity ===\")\n", "\n", " n_images = len(features)\n", " similarity_matrix = np.zeros((n_images, n_images), dtype=np.float32)\n", "\n", " # 各特徴量をグローバル記述子に変換\n", " global_features = []\n", "\n", " for feat in features:\n", " if isinstance(feat, dict):\n", " for key in ['desc', 'conf', 'pts3d']:\n", " if key in feat:\n", " feat = feat[key]\n", " break\n", "\n", " if isinstance(feat, torch.Tensor):\n", " feat = feat.cpu().numpy()\n", "\n", " if isinstance(feat, np.ndarray):\n", " if feat.ndim == 3: # [H, W, C]\n", " feat_flat = feat.reshape(-1, feat.shape[-1])\n", " elif feat.ndim == 2: # [N, C]\n", " feat_flat = feat\n", " else:\n", " feat_flat = feat.reshape(-1, max(feat.shape))\n", "\n", " global_desc = np.mean(feat_flat, axis=0)\n", " global_features.append(global_desc)\n", " else:\n", " # ダミー特徴量\n", " global_features.append(np.zeros(64))\n", "\n", " global_features = np.stack(global_features)\n", " feature_dim = global_features.shape[1]\n", "\n", " print(f\"Global features shape: {global_features.shape}\")\n", "\n", " # コサイン類似度を使用\n", " global_features_norm = global_features / (np.linalg.norm(global_features, axis=1, keepdims=True) + 1e-8)\n", " similarity_matrix = global_features_norm @ global_features_norm.T\n", "\n", " np.fill_diagonal(similarity_matrix, -1)\n", "\n", " print(f\"Similarity matrix shape: {similarity_matrix.shape}\")\n", " print(f\"Similarity range: [{similarity_matrix.min():.3f}, {similarity_matrix.max():.3f}]\")\n", "\n", " return similarity_matrix\n", "\n", "\n", "def build_pairs_from_similarity(similarity_matrix, top_k=10):\n", " \"\"\"類似度行列からペアを構築\"\"\"\n", " n_images = similarity_matrix.shape[0]\n", " pairs = []\n", "\n", " for i in range(n_images):\n", " similarities = similarity_matrix[i]\n", " top_indices = np.argsort(similarities)[::-1][:top_k]\n", "\n", " for j in top_indices:\n", " if j > i:\n", " pairs.append((i, j))\n", "\n", " pairs = list(set(pairs))\n", " print(f\"✓ Built {len(pairs)} unique pairs\")\n", "\n", " return pairs\n", "\n", "\n", "def get_image_pairs_asmk(image_paths, max_pairs=100):\n", " \"\"\"ASMKを使用して画像ペアを取得\"\"\"\n", " print(\"\\n=== Getting Image Pairs with ASMK ===\")\n", "\n", " device = Config.DEVICE\n", " model = load_mast3r_model(device)\n", " features = extract_mast3r_features(model, image_paths, device)\n", " similarity_matrix = compute_asmk_similarity(features)\n", " pairs = build_pairs_from_similarity(similarity_matrix, Config.RETRIEVAL_TOPK)\n", "\n", " # モデルを解放\n", " del model\n", " clear_memory()\n", "\n", " if len(pairs) > max_pairs:\n", " pairs = pairs[:max_pairs]\n", " print(f\"Limited to {max_pairs} pairs\")\n", "\n", " return pairs" ], "metadata": { "trusted": true, "id": "qo0mGj_5jLmG" }, "outputs": [], "execution_count": 4 }, { "cell_type": "code", "source": [ "# =====================================================================\n", "# CELL 14: MASt3R Reconstruction\n", "# =====================================================================\n", "def run_mast3r_pairs(model, image_paths, pairs, device, batch_size=1):\n", " \"\"\"MASt3Rでペア画像を処理(メモリ最適化版)\"\"\"\n", " print(\"\\n=== Running MASt3R Reconstruction ===\")\n", " from dust3r.inference import inference\n", " from dust3r.cloud_opt import global_aligner, GlobalAlignerMode\n", " from dust3r.utils.image import load_images\n", "\n", " # ペアを制限\n", " max_pairs_for_memory = 50\n", " if len(pairs) > max_pairs_for_memory:\n", " print(f\"⚠️ Limiting pairs from {len(pairs)} to {max_pairs_for_memory} for memory\")\n", " pairs = pairs[:max_pairs_for_memory]\n", "\n", " # ペアから画像インデックスを取得\n", " pair_indices = []\n", " for i, j in pairs:\n", " pair_indices.extend([i, j])\n", " unique_indices = sorted(set(pair_indices))\n", "\n", " selected_paths = [image_paths[i] for i in unique_indices]\n", " print(f\"Selected {len(selected_paths)} unique images from {len(pairs)} pairs\")\n", "\n", " # 画像をロード\n", " images = load_images(selected_paths, size=Config.IMAGE_SIZE)\n", " clear_memory()\n", "\n", " # インデックスマッピング\n", " index_map = {old_idx: new_idx for new_idx, old_idx in enumerate(unique_indices)}\n", "\n", " # ペア画像リストを作成\n", " image_pairs = []\n", " for i, j in pairs:\n", " new_i = index_map[i]\n", " new_j = index_map[j]\n", " image_pairs.append((images[new_i], images[new_j]))\n", "\n", " print(f\"Created {len(image_pairs)} image pairs\")\n", " clear_memory()\n", "\n", " # 推論を実行\n", " print(f\"Running inference on {len(image_pairs)} pairs...\")\n", " with torch.no_grad():\n", " output = inference(image_pairs, model, device, batch_size=batch_size)\n", "\n", " print(f\"✓ Processed {len(output)} predictions\")\n", " clear_memory()\n", "\n", " # Global alignment\n", " scene = global_aligner(\n", " dust3r_output=output,\n", " device=device,\n", " mode=GlobalAlignerMode.PointCloudOptimizer,\n", " verbose=True\n", " )\n", "\n", " clear_memory()\n", "\n", " print(\"Running global alignment...\")\n", " try:\n", " loss = scene.compute_global_alignment(\n", " init=\"mst\",\n", " niter=50,\n", " schedule='cosine',\n", " lr=0.01\n", " )\n", " print(f\"✓ Alignment complete (loss: {loss:.6f})\")\n", " except RuntimeError as e:\n", " if \"out of memory\" in str(e).lower():\n", " print(\"⚠️ OOM during alignment, trying with fewer iterations...\")\n", " clear_memory()\n", " loss = scene.compute_global_alignment(\n", " init=\"mst\",\n", " niter=20,\n", " schedule='cosine',\n", " lr=0.01\n", " )\n", " print(f\"✓ Alignment complete with reduced iterations (loss: {loss:.6f})\")\n", " else:\n", " raise\n", "\n", " clear_memory()\n", " return scene, images\n", "\n" ], "metadata": { "trusted": true, "id": "bCXpdw83jLmG" }, "outputs": [], "execution_count": 14 }, { "cell_type": "code", "source": [ "\n", "# =====================================================================\n", "# CELL 15: Camera Parameter Extraction\n", "# =====================================================================\n", "\n", "def extract_camera_params_process2(scene, image_paths, conf_threshold=1.5):\n", " \"\"\"sceneからカメラパラメータと3D点を抽出\"\"\"\n", " print(\"\\n=== Extracting Camera Parameters ===\")\n", "\n", " cameras_dict = {}\n", " all_pts3d = []\n", " all_confidence = []\n", "\n", " try:\n", " if hasattr(scene, 'get_im_poses'):\n", " poses = scene.get_im_poses()\n", " elif hasattr(scene, 'im_poses'):\n", " poses = scene.im_poses\n", " else:\n", " poses = None\n", "\n", " if hasattr(scene, 'get_focals'):\n", " focals = scene.get_focals()\n", " elif hasattr(scene, 'im_focals'):\n", " focals = scene.im_focals\n", " else:\n", " focals = None\n", "\n", " if hasattr(scene, 'get_principal_points'):\n", " pps = scene.get_principal_points()\n", " elif hasattr(scene, 'im_pp'):\n", " pps = scene.im_pp\n", " else:\n", " pps = None\n", " except Exception as e:\n", " print(f\"⚠️ Error getting camera parameters: {e}\")\n", " poses = None\n", " focals = None\n", " pps = None\n", "\n", " n_images = min(len(poses) if poses is not None else len(image_paths), len(image_paths))\n", "\n", " for idx in range(n_images):\n", " img_name = os.path.basename(image_paths[idx])\n", "\n", " try:\n", " # Poseを取得\n", " if poses is not None and idx < len(poses):\n", " pose = poses[idx]\n", " if isinstance(pose, torch.Tensor):\n", " pose = pose.detach().cpu().numpy()\n", " if not isinstance(pose, np.ndarray) or pose.shape != (4, 4):\n", " pose = np.eye(4)\n", " else:\n", " pose = np.eye(4)\n", "\n", " # Focalを取得\n", " if focals is not None and idx < len(focals):\n", " focal = focals[idx]\n", " if isinstance(focal, torch.Tensor):\n", " focal = focal.detach().cpu().item()\n", " else:\n", " focal = float(focal)\n", " else:\n", " focal = 1000.0\n", "\n", " # Principal pointを取得\n", " if pps is not None and idx < len(pps):\n", " pp = pps[idx]\n", " if isinstance(pp, torch.Tensor):\n", " pp = pp.detach().cpu().numpy()\n", " else:\n", " pp = np.array([112.0, 112.0])\n", "\n", " # カメラパラメータを保存\n", " cameras_dict[img_name] = {\n", " 'focal': focal,\n", " 'pp': pp,\n", " 'pose': pose,\n", " 'width': Config.IMAGE_SIZE * 4,\n", " 'height': Config.IMAGE_SIZE * 4\n", " }\n", "\n", " # 3D点を取得\n", " if hasattr(scene, 'im_pts3d') and idx < len(scene.im_pts3d):\n", " pts3d_img = scene.im_pts3d[idx]\n", " elif hasattr(scene, 'get_pts3d'):\n", " pts3d_all = scene.get_pts3d()\n", " if idx < len(pts3d_all):\n", " pts3d_img = pts3d_all[idx]\n", " else:\n", " pts3d_img = None\n", " else:\n", " pts3d_img = None\n", "\n", " # Confidenceを取得\n", " if hasattr(scene, 'im_conf') and idx < len(scene.im_conf):\n", " conf_img = scene.im_conf[idx]\n", " elif hasattr(scene, 'get_conf'):\n", " conf_all = scene.get_conf()\n", " if idx < len(conf_all):\n", " conf_img = conf_all[idx]\n", " else:\n", " conf_img = None\n", " else:\n", " conf_img = None\n", "\n", " # 3D点とconfidenceを処理\n", " if pts3d_img is not None:\n", " if isinstance(pts3d_img, torch.Tensor):\n", " pts3d_img = pts3d_img.detach().cpu().numpy()\n", "\n", " if pts3d_img.ndim == 3:\n", " pts3d_flat = pts3d_img.reshape(-1, 3)\n", " else:\n", " pts3d_flat = pts3d_img\n", "\n", " all_pts3d.append(pts3d_flat)\n", "\n", " # confidenceを処理\n", " if conf_img is not None:\n", " if isinstance(conf_img, list):\n", " conf_img = np.array(conf_img)\n", " elif isinstance(conf_img, torch.Tensor):\n", " conf_img = conf_img.detach().cpu().numpy()\n", "\n", " if conf_img.ndim > 1:\n", " conf_flat = conf_img.reshape(-1)\n", " else:\n", " conf_flat = conf_img\n", "\n", " if len(conf_flat) != len(pts3d_flat):\n", " conf_flat = np.ones(len(pts3d_flat))\n", "\n", " all_confidence.append(conf_flat)\n", " else:\n", " all_confidence.append(np.ones(len(pts3d_flat)))\n", "\n", " except Exception as e:\n", " print(f\"⚠️ Error processing image {idx} ({img_name}): {e}\")\n", " cameras_dict[img_name] = {\n", " 'focal': 1000.0,\n", " 'pp': np.array([112.0, 112.0]),\n", " 'pose': np.eye(4),\n", " 'width': Config.IMAGE_SIZE * 4,\n", " 'height': Config.IMAGE_SIZE * 4\n", " }\n", " continue\n", "\n", " # 全3D点を結合\n", " if all_pts3d:\n", " pts3d = np.vstack(all_pts3d)\n", " confidence = np.concatenate(all_confidence)\n", " else:\n", " pts3d = np.zeros((0, 3))\n", " confidence = np.zeros(0)\n", "\n", " print(f\"✓ Extracted camera parameters for {len(cameras_dict)} images\")\n", " print(f\"✓ Total 3D points: {len(pts3d)}\")\n", "\n", " # Confidenceでフィルタリング\n", " if len(confidence) > 0:\n", " valid_mask = confidence > conf_threshold\n", " pts3d = pts3d[valid_mask]\n", " confidence = confidence[valid_mask]\n", " print(f\"✓ After confidence filtering (>{conf_threshold}): {len(pts3d)} points\")\n", "\n", "\n", "\n", "\n", " # ========== ここに追加 ==========\n", "\n", " print(f\"\\n信頼度統計:\")\n", " print(f\" 最小: {np.min(all_confidence):.6f}\")\n", " print(f\" 平均: {np.mean(all_confidence):.6f}\")\n", " print(f\" 最大: {np.max(all_confidence):.6f}\")\n", " print(f\" 中央値: {np.median(all_confidence):.6f}\")\n", "\n", " print(\"\\n=== カメラポーズ診断 ===\")\n", " for i, (img_name, cam) in enumerate(list(cameras_dict.items())[:3]):\n", " print(f\"\\nCamera {i+1}: {img_name}\")\n", "\n", " # poseから回転と並進を抽出\n", " pose = cam['pose'] # 4x4行列\n", " R = pose[:3, :3] # 回転\n", " t = pose[:3, 3] # 並進\n", "\n", " # 回転行列の検証\n", " det_R = np.linalg.det(R)\n", " print(f\" 回転行列の行列式: {det_R:.6f} (正常値: 1.0)\")\n", " if abs(det_R - 1.0) > 0.01:\n", " print(f\" ⚠️ 回転行列が異常です!\")\n", "\n", " # 直交性の検証\n", " ortho_error = np.linalg.norm(R @ R.T - np.eye(3))\n", " print(f\" 直交性エラー: {ortho_error:.6e} (正常値: <1e-6)\")\n", " if ortho_error > 1e-4:\n", " print(f\" ⚠️ 回転行列が直交行列ではありません!\")\n", "\n", " # 並進ベクトルのノルム\n", " t_norm = np.linalg.norm(t)\n", " print(f\" 並進ベクトルのノルム: {t_norm:.6f}\")\n", "\n", " # カメラ位置(world座標系)\n", " camera_position = -R.T @ t\n", " print(f\" カメラ位置 (world): [{camera_position[0]:.3f}, {camera_position[1]:.3f}, {camera_position[2]:.3f}]\")\n", "\n", " # 焦点距離\n", " focal = cam['focal']\n", " print(f\" 焦点距離: {focal:.2f}\")\n", " print(f\" 画像サイズ: {cam['width']}x{cam['height']}\")\n", "\n", " # FOV計算\n", " fov_deg = 2 * np.arctan(cam['width'] / (2 * focal)) * 180 / np.pi\n", " print(f\" 視野角 (FOV): {fov_deg:.1f}°\")\n", "\n", " # カメラ間の距離統計\n", " print(\"\\n=== カメラ配置統計 ===\")\n", " positions = []\n", " for cam in cameras_dict.values():\n", " pose = cam['pose']\n", " R = pose[:3, :3]\n", " t = pose[:3, 3]\n", " pos = -R.T @ t\n", " positions.append(pos)\n", "\n", " positions = np.array(positions)\n", " center = np.mean(positions, axis=0)\n", " distances = np.linalg.norm(positions - center, axis=1)\n", "\n", " print(f\" カメラ数: {len(positions)}\")\n", " print(f\" 中心位置: [{center[0]:.3f}, {center[1]:.3f}, {center[2]:.3f}]\")\n", " print(f\" 中心からの平均距離: {np.mean(distances):.3f}\")\n", " print(f\" 距離の標準偏差: {np.std(distances):.3f}\")\n", " print(f\" 最小距離: {np.min(distances):.3f}\")\n", " print(f\" 最大距離: {np.max(distances):.3f}\")\n", "\n", " if np.std(distances) < 0.1:\n", " print(\" ⚠️ WARNING: すべてのカメラがほぼ同じ位置にあります!\")\n", "\n", " if np.mean(distances) < 0.01:\n", " print(\" ⚠️ WARNING: カメラが原点に集中しています!\")\n", "\n", " # ========== 修正版スケール補正 ==========\n", " print(\"\\n=== スケール補正 ===\")\n", "\n", " # 現在のカメラ位置を取得\n", " positions = []\n", " for cam in cameras_dict.values():\n", " pose = cam['pose']\n", " R = pose[:3, :3]\n", " t = pose[:3, 3]\n", " pos = -R.T @ t\n", " positions.append(pos)\n", "\n", " positions = np.array(positions)\n", "\n", " # 平均距離を計算\n", " center = np.mean(positions, axis=0)\n", " avg_distance = np.mean(np.linalg.norm(positions - center, axis=1))\n", "\n", " # 目標スケール(平均距離を1.0メートルに)\n", " target_scale = 1.0\n", " scale_factor = target_scale / (avg_distance + 1e-8)\n", "\n", " print(f\" 現在の平均距離: {avg_distance:.3f}\")\n", " print(f\" スケール係数: {scale_factor:.2f}x\")\n", "\n", " # カメラポーズにスケールを適用\n", " for cam in cameras_dict.values():\n", " pose = cam['pose']\n", " pose[:3, 3] *= scale_factor # 並進部分のみスケール\n", "\n", " # 3D点にスケールを適用(修正版)\n", " all_pts3d_array = np.vstack(all_pts3d) # リストをまず結合\n", " all_pts3d_scaled = all_pts3d_array * scale_factor # スケール適用\n", "\n", " print(f\" ✓ スケール補正完了\")\n", " print(f\" 3D点数: {len(all_pts3d_scaled):,}\")\n", "\n", " # 補正後の統計を表示\n", " positions_scaled = []\n", " for cam in cameras_dict.values():\n", " pose = cam['pose']\n", " R = pose[:3, :3]\n", " t = pose[:3, 3]\n", " pos = -R.T @ t\n", " positions_scaled.append(pos)\n", "\n", " positions_scaled = np.array(positions_scaled)\n", " center_scaled = np.mean(positions_scaled, axis=0)\n", " avg_distance_scaled = np.mean(np.linalg.norm(positions_scaled - center_scaled, axis=1))\n", "\n", " print(f\" 補正後の平均距離: {avg_distance_scaled:.3f}\")\n", " # ========== ここまで ==========\n", "\n", " # ========== ここまで追加 ==========\n", "\n", " return cameras_dict, all_pts3d_scaled, all_confidence" ], "metadata": { "id": "a5veq5co-E7_" }, "execution_count": 16, "outputs": [] }, { "cell_type": "code", "source": [ "# =====================================================================\n", "# CELL 16: COLMAP Export Functions\n", "# =====================================================================\n", "import struct\n", "from scipy.spatial.transform import Rotation as R\n", "\n", "def write_colmap_sparse(cameras_dict, pts3d, confidence, image_paths, output_dir):\n", " \"\"\"COLMAP sparse形式をバイナリファイルで出力\"\"\"\n", " os.makedirs(output_dir, exist_ok=True)\n", "\n", " if not cameras_dict:\n", " raise ValueError(\"cameras_dict is empty\")\n", "\n", " first_key = list(cameras_dict.keys())[0]\n", " first_cam = cameras_dict[first_key]\n", "\n", " w = int(first_cam.get('width', 1920))\n", " h = int(first_cam.get('height', 1080))\n", " focal = float(first_cam.get('focal', max(w, h) * 1.2))\n", " cx = w / 2.0\n", " cy = h / 2.0\n", "\n", " # cameras.bin\n", " cameras_file = os.path.join(output_dir, 'cameras.bin')\n", " with open(cameras_file, 'wb') as f:\n", " f.write(struct.pack('Q', 1))\n", " camera_id = 1\n", " model_id = 1 # PINHOLE\n", " f.write(struct.pack('i', camera_id))\n", " f.write(struct.pack('i', model_id))\n", " f.write(struct.pack('Q', w))\n", " f.write(struct.pack('Q', h))\n", " f.write(struct.pack('d', focal))\n", " f.write(struct.pack('d', focal))\n", " f.write(struct.pack('d', cx))\n", " f.write(struct.pack('d', cy))\n", "\n", " print(f\"✓ Written cameras.bin\")\n", "\n", " # images.bin\n", " images_file = os.path.join(output_dir, 'images.bin')\n", " with open(images_file, 'wb') as f:\n", " f.write(struct.pack('Q', len(image_paths)))\n", "\n", " for i, img_path in enumerate(image_paths):\n", " img_name = os.path.basename(img_path)\n", "\n", " cam_info = cameras_dict.get(img_name)\n", " if cam_info is None:\n", " pose = np.eye(4)\n", " else:\n", " pose = cam_info['pose']\n", "\n", " try:\n", " w2c = np.linalg.inv(pose)\n", " except np.linalg.LinAlgError:\n", " w2c = np.eye(4)\n", "\n", " rot_mat = w2c[:3, :3]\n", " tvec = w2c[:3, 3]\n", " quat = R.from_matrix(rot_mat).as_quat()\n", " qw, qx, qy, qz = quat[3], quat[0], quat[1], quat[2]\n", "\n", " image_id = i + 1\n", " f.write(struct.pack('i', image_id))\n", " f.write(struct.pack('d', qw))\n", " f.write(struct.pack('d', qx))\n", " f.write(struct.pack('d', qy))\n", " f.write(struct.pack('d', qz))\n", " f.write(struct.pack('d', tvec[0]))\n", " f.write(struct.pack('d', tvec[1]))\n", " f.write(struct.pack('d', tvec[2]))\n", " f.write(struct.pack('i', 1))\n", " img_name_bytes = img_name.encode('utf-8') + b'\\x00'\n", " f.write(img_name_bytes)\n", " f.write(struct.pack('Q', 0))\n", "\n", " print(f\"✓ Written images.bin ({len(image_paths)} images)\")\n", "\n", " # points3D.bin\n", " points_file = os.path.join(output_dir, 'points3D.bin')\n", " with open(points_file, 'wb') as f:\n", " f.write(struct.pack('Q', len(pts3d)))\n", "\n", " for point_id, point in enumerate(pts3d, start=1):\n", " f.write(struct.pack('Q', point_id))\n", " f.write(struct.pack('d', point[0]))\n", " f.write(struct.pack('d', point[1]))\n", " f.write(struct.pack('d', point[2]))\n", " f.write(struct.pack('B', 255))\n", " f.write(struct.pack('B', 255))\n", " f.write(struct.pack('B', 255))\n", " f.write(struct.pack('d', 0.0))\n", " f.write(struct.pack('Q', 0))\n", "\n", " print(f\"✓ Written points3D.bin ({len(pts3d)} points)\")\n", "\n", " # テキスト形式も出力\n", " write_text_versions(cameras_dict, pts3d, image_paths, output_dir, w, h, focal, cx, cy)\n", "\n", " print(f\"\\n✓ COLMAP sparse reconstruction saved\")\n", " return output_dir\n", "\n", "\n", "def write_text_versions(cameras_dict, pts3d, image_paths, output_dir, w, h, focal, cx, cy):\n", " \"\"\"テキスト形式を出力\"\"\"\n", "\n", " # cameras.txt\n", " with open(os.path.join(output_dir, 'cameras.txt'), 'w') as file:\n", " file.write(\"# Camera list with one line of data per camera:\\n\")\n", " file.write(\"# CAMERA_ID, MODEL, WIDTH, HEIGHT, PARAMS[]\\n\")\n", " file.write(f\"1 PINHOLE {w} {h} {focal} {focal} {cx} {cy}\\n\")\n", "\n", " # images.txt\n", " with open(os.path.join(output_dir, 'images.txt'), 'w') as file:\n", " file.write(\"# Image list with two lines of data per image:\\n\")\n", " file.write(\"# IMAGE_ID, QW, QX, QY, QZ, TX, TY, TZ, CAMERA_ID, NAME\\n\")\n", " file.write(\"# POINTS2D[] as (X, Y, POINT3D_ID)\\n\")\n", "\n", " for i, img_path in enumerate(image_paths):\n", " img_name = os.path.basename(img_path)\n", " cam_info = cameras_dict.get(img_name)\n", "\n", " if cam_info is None:\n", " pose = np.eye(4)\n", " else:\n", " pose = cam_info['pose']\n", "\n", " try:\n", " w2c = np.linalg.inv(pose)\n", " except np.linalg.LinAlgError:\n", " w2c = np.eye(4)\n", "\n", " rot_mat = w2c[:3, :3]\n", " tvec = w2c[:3, 3]\n", " quat = R.from_matrix(rot_mat).as_quat()\n", " qw, qx, qy, qz = quat[3], quat[0], quat[1], quat[2]\n", "\n", " image_id = i + 1\n", " file.write(f\"{image_id} {qw} {qx} {qy} {qz} {tvec[0]} {tvec[1]} {tvec[2]} 1 {img_name}\\n\")\n", " file.write(\"\\n\")\n", "\n", " # points3D.txt\n", " with open(os.path.join(output_dir, 'points3D.txt'), 'w') as file:\n", " file.write(\"# 3D point list with one line of data per point:\\n\")\n", " file.write(\"# POINT3D_ID, X, Y, Z, R, G, B, ERROR, TRACK[]\\n\")\n", "\n", " for point_id, point in enumerate(pts3d, start=1):\n", " file.write(f\"{point_id} {point[0]} {point[1]} {point[2]} 255 255 255 0.0\\n\")\n", "\n", "# =====================================================================\n", "# CELL 17: Gaussian Splatting Runner\n", "# =====================================================================\n", "def run_gaussian_splatting(source_dir, output_dir, iterations=30000):\n", " \"\"\"Gaussian Splattingを実行\"\"\"\n", " print(\"\\n=== Running Gaussian Splatting ===\")\n", "\n", " os.makedirs(output_dir, exist_ok=True)\n", "\n", " cmd = [\n", " \"python\", \"/content/gaussian-splatting/train.py\",\n", " \"-s\", source_dir,\n", " \"-m\", output_dir,\n", " \"--iterations\", str(iterations),\n", " \"--eval\"\n", " ]\n", "\n", " print(f\"Command: {' '.join(cmd)}\")\n", " print(f\" Source: {source_dir}\")\n", " print(f\" Output: {output_dir}\")\n", "\n", " result = subprocess.run(cmd, capture_output=False, text=True)\n", "\n", " if result.returncode == 0:\n", " print(f\"\\n✓ Gaussian Splatting complete\")\n", "\n", " point_cloud_dir = os.path.join(output_dir, \"point_cloud\")\n", " if os.path.exists(point_cloud_dir):\n", " print(f\"\\n✓ Point cloud directory found: {point_cloud_dir}\")\n", "\n", " for item in sorted(os.listdir(point_cloud_dir)):\n", " item_path = os.path.join(point_cloud_dir, item)\n", " if os.path.isdir(item_path) and item.startswith(\"iteration_\"):\n", " ply_file = os.path.join(item_path, \"point_cloud.ply\")\n", " if os.path.exists(ply_file):\n", " file_size = os.path.getsize(ply_file) / (1024 * 1024)\n", " print(f\" ✓ {item}/point_cloud.ply ({file_size:.2f} MB)\")\n", " else:\n", " print(f\"\\n✗ Gaussian Splatting failed with return code {result.returncode}\")\n", "\n", " return output_dir" ], "metadata": { "trusted": true, "id": "1yyRoxHKjLmH" }, "outputs": [], "execution_count": 6 }, { "cell_type": "code", "source": [ "# =====================================================================\n", "# CELL 18: Main Pipeline\n", "# =====================================================================\n", "def main_pipeline(image_dir, output_dir, square_size=1024, iterations=30000,\n", " max_images=200, max_pairs=100, max_points=500000,\n", " conf_threshold=1.5, preprocess_mode='none'):\n", " \"\"\"メインパイプライン(修正版)\"\"\"\n", "\n", " # STEP 0: Image Preprocessing\n", " if preprocess_mode == 'biplet':\n", " print(\"=\"*70)\n", " print(\"STEP 0: Image Preprocessing (Biplet Crops)\")\n", " print(\"=\"*70)\n", "\n", " temp_biplet_dir = os.path.join(output_dir, \"temp_biplet\")\n", " biplet_dir = normalize_image_sizes_biplet(image_dir, temp_biplet_dir, size=square_size)\n", "\n", " images_dir = os.path.join(output_dir, \"images\")\n", " os.makedirs(images_dir, exist_ok=True)\n", "\n", " biplet_suffixes = ['_left', '_right', '_top', '_bottom']\n", " copied_count = 0\n", "\n", " for img_file in os.listdir(temp_biplet_dir):\n", " if any(suffix in img_file for suffix in biplet_suffixes):\n", " src = os.path.join(temp_biplet_dir, img_file)\n", " dst = os.path.join(images_dir, img_file)\n", " shutil.copy2(src, dst)\n", " copied_count += 1\n", "\n", " print(f\"✓ Copied {copied_count} biplet images to {images_dir}\")\n", "\n", " original_images_dir = os.path.join(output_dir, \"original_images\")\n", " os.makedirs(original_images_dir, exist_ok=True)\n", "\n", " original_count = 0\n", " valid_extensions = ('.jpg', '.jpeg', '.png', '.bmp')\n", " for img_file in os.listdir(image_dir):\n", " if img_file.lower().endswith(valid_extensions):\n", " src = os.path.join(image_dir, img_file)\n", " dst = os.path.join(original_images_dir, img_file)\n", " shutil.copy2(src, dst)\n", " original_count += 1\n", "\n", " print(f\"✓ Saved {original_count} original images to {original_images_dir}\")\n", " shutil.rmtree(temp_biplet_dir)\n", " image_dir = images_dir\n", " clear_memory()\n", " else:\n", " images_dir = os.path.join(output_dir, \"images\")\n", " if not os.path.exists(images_dir):\n", " print(\"=\"*70)\n", " print(\"STEP 0: Copying images to output directory\")\n", " print(\"=\"*70)\n", " shutil.copytree(image_dir, images_dir)\n", " print(f\"✓ Copied images to {images_dir}\")\n", " image_dir = images_dir\n", "\n", " # STEP 1: Loading Images\n", " print(\"\\n\" + \"=\"*70)\n", " print(\"STEP 1: Loading and Preparing Images\")\n", " print(\"=\"*70)\n", "\n", " image_paths = load_images_from_directory(image_dir, max_images=max_images)\n", " print(f\"Loaded {len(image_paths)} images\")\n", " clear_memory()\n", "\n", " # STEP 2: Image Pair Selection\n", " print(\"\\n\" + \"=\"*70)\n", " print(\"STEP 2: Image Pair Selection\")\n", " print(\"=\"*70)\n", "\n", " max_pairs = min(max_pairs, 50)\n", " pairs = get_image_pairs_asmk(image_paths, max_pairs=max_pairs)\n", " print(f\"Selected {len(pairs)} image pairs\")\n", " clear_memory()\n", "\n", " # STEP 3: MASt3R 3D Reconstruction\n", " print(\"\\n\" + \"=\"*70)\n", " print(\"STEP 3: MASt3R 3D Reconstruction\")\n", " print(\"=\"*70)\n", "\n", " device = Config.DEVICE\n", " model = load_mast3r_model(device)\n", " scene, mast3r_images = run_mast3r_pairs(model, image_paths, pairs, device)\n", "\n", " del model\n", " clear_memory()\n", "\n", " # STEP 4: Converting to COLMAP\n", " print(\"\\n\" + \"=\"*70)\n", " print(\"STEP 4: Converting to COLMAP (PINHOLE)\")\n", " print(\"=\"*70)\n", "\n", " cameras_dict, pts3d, confidence = extract_camera_params_process2(\n", " scene, image_paths, conf_threshold=conf_threshold\n", " )\n", "\n", " del scene\n", " clear_memory()\n", "\n", " if len(pts3d) > max_points:\n", " print(f\"⚠️ Limiting points from {len(pts3d)} to {max_points}\")\n", " indices = np.random.choice(len(pts3d), max_points, replace=False)\n", " pts3d = pts3d[indices]\n", " confidence = confidence[indices]\n", "\n", " print(f\"Final point count: {len(pts3d)}\")\n", "\n", " colmap_dir = os.path.join(output_dir, \"sparse/0\")\n", " os.makedirs(colmap_dir, exist_ok=True)\n", "\n", " write_colmap_sparse(cameras_dict, pts3d, confidence, image_paths, colmap_dir)\n", " clear_memory()\n", "\n", " # STEP 5: Running Gaussian Splatting\n", " print(\"\\n\" + \"=\"*70)\n", " print(\"STEP 5: Running Gaussian Splatting\")\n", " print(\"=\"*70)\n", "\n", " source_dir = output_dir\n", " model_output_dir = os.path.join(output_dir, \"gaussian_splatting\")\n", "\n", " gs_output = run_gaussian_splatting(\n", " source_dir=source_dir,\n", " output_dir=model_output_dir,\n", " iterations=iterations\n", " )\n", "\n", " # STEP 6: Verify Output\n", " print(\"\\n\" + \"=\"*70)\n", " print(\"PIPELINE COMPLETE\")\n", " print(\"=\"*70)\n", "\n", " ply_path = os.path.join(\n", " model_output_dir,\n", " \"point_cloud\",\n", " f\"iteration_{iterations}\",\n", " \"point_cloud.ply\"\n", " )\n", "\n", " if os.path.exists(ply_path):\n", " file_size = os.path.getsize(ply_path) / (1024 * 1024)\n", " print(f\"✓ Point cloud generated: {ply_path}\")\n", " print(f\" Size: {file_size:.2f} MB\")\n", " else:\n", " print(f\"⚠️ Point cloud not found at: {ply_path}\")\n", "\n", " print(f\"\\nOutput directory structure:\")\n", " print(f\" {output_dir}/\")\n", " print(f\" ├── images/ (processed images)\")\n", " if preprocess_mode == 'biplet':\n", " print(f\" ├── original_images/ (original source images)\")\n", " print(f\" ├── sparse/0/ (COLMAP data)\")\n", " print(f\" └── gaussian_splatting/ (GS output)\")\n", "\n", " return gs_output\n", "\n", "# =====================================================================\n", "# CELL 19: Verify Setup\n", "# =====================================================================\n", "print(f\"✓ np: {np.__version__} - {np.__file__}\")\n", "!pip show numpy | grep Version\n", "\n", "try:\n", " import roma\n", " print(\"✓ roma is installed\")\n", "except ModuleNotFoundError:\n", " print(\"⚠️ roma not found, installing...\")\n", " !pip install roma\n", " import roma\n", " print(\"✓ roma installed\")" ], "metadata": { "trusted": true, "id": "bHKT_3EZjLmH", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "1933c5c6-541e-4f9b-f26a-90ec2e83163b" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "✓ np: 1.26.4 - /usr/local/lib/python3.12/dist-packages/numpy/__init__.py\n", "Version: 1.26.4\n", "Version 3.1, 31 March 2009\n", " Version 3, 29 June 2007\n", " 5. Conveying Modified Source Versions.\n", " 14. Revised Versions of this License.\n", "✓ roma is installed\n" ] } ], "execution_count": 7 }, { "cell_type": "code", "source": [ "# =====================================================================\n", "# CELL 20: Run Pipeline\n", "# =====================================================================\n", "if __name__ == \"__main__\":\n", " IMAGE_DIR = \"/content/drive/MyDrive/your_folder/fountain\"\n", " OUTPUT_DIR = \"/content/output\"\n", "\n", " gs_output = main_pipeline(\n", " image_dir=IMAGE_DIR,\n", " output_dir=OUTPUT_DIR,\n", " square_size=512,\n", " iterations=1000,\n", " max_images=10,\n", " max_pairs=100,\n", " max_points=100000,\n", " conf_threshold=0.5,\n", " preprocess_mode='biplet'\n", " )\n", "\n", " print(\"\\n\" + \"=\"*70)\n", " print(\"PIPELINE COMPLETE\")\n", " print(\"=\"*70)\n", " print(f\"Output directory: {gs_output}\")" ], "metadata": { "trusted": true, "id": "n6ZHOb8TjLmI", "colab": { "base_uri": "https://localhost:8080/", "height": 1000 }, "outputId": "b1043745-33cb-467b-bdec-74e5d4747b06" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "======================================================================\n", "STEP 0: Image Preprocessing (Biplet Crops)\n", "======================================================================\n", "\n", "=== Generating Biplet Crops (512x512) ===\n" ] }, { "output_type": "stream", "name": "stderr", "text": [ "Creating biplets: 100%|██████████| 30/30 [00:03<00:00, 9.31it/s]\n" ] }, { "output_type": "stream", "name": "stdout", "text": [ "\n", "✓ Biplet generation complete:\n", " Source images: 30\n", " Biplet crops generated: 60\n", " Original size distribution: {'1440x1920': 30}\n", "✓ Copied 60 biplet images to /content/output/images\n", "✓ Saved 30 original images to /content/output/original_images\n", "\n", "======================================================================\n", "STEP 1: Loading and Preparing Images\n", "======================================================================\n", "\n", "Loading images from: /content/output/images\n", "⚠️ Limiting from 60 to 10 images\n", "✓ Found 10 images\n", "Loaded 10 images\n", "\n", "======================================================================\n", "STEP 2: Image Pair Selection\n", "======================================================================\n", "\n", "=== Getting Image Pairs with ASMK ===\n", "\n", "=== Loading MASt3R Model ===\n", "Attempting to load: naver/MASt3R_ViTLarge_BaseDecoder_512_catmlpdpt_metric\n", "⚠️ Failed to load MASt3R: tried to load naver/MASt3R_ViTLarge_BaseDecoder_512_catmlpdpt_metric from huggingface, but failed\n", "Trying DUSt3R instead: naver/DUSt3R_ViTLarge_BaseDecoder_512_dpt\n", "✓ Loaded DUSt3R model as fallback\n", "✓ Model loaded on cuda\n", "\n", "=== Extracting MASt3R Features ===\n" ] }, { "output_type": "stream", "name": "stderr", "text": [ "\rFeatures: 0%| | 0/10 [00:00> Loading a list of 2 images\n", " - adding /content/output/images/image_001_bottom.jpeg with resolution 512x512 --> 224x224\n", " - adding /content/output/images/image_001_bottom.jpeg with resolution 512x512 --> 224x224\n", " (Found 2 images)\n", ">> Inference with model on 1 image pairs\n" ] }, { "output_type": "stream", "name": "stderr", "text": [ "\n", " 0%| | 0/1 [00:00> Loading a list of 2 images\n", " - adding /content/output/images/image_001_top.jpeg with resolution 512x512 --> 224x224\n", " - adding /content/output/images/image_001_top.jpeg with resolution 512x512 --> 224x224\n", " (Found 2 images)\n", ">> Inference with model on 1 image pairs\n" ] }, { "output_type": "stream", "name": "stderr", "text": [ "\n", " 0%| | 0/1 [00:00> Loading a list of 2 images\n", " - adding /content/output/images/image_002_bottom.jpeg with resolution 512x512 --> 224x224\n", " - adding /content/output/images/image_002_bottom.jpeg with resolution 512x512 --> 224x224\n", " (Found 2 images)\n", ">> Inference with model on 1 image pairs\n" ] }, { "output_type": "stream", "name": "stderr", "text": [ "\n", " 0%| | 0/1 [00:00> Loading a list of 2 images\n", " - adding /content/output/images/image_002_top.jpeg with resolution 512x512 --> 224x224\n", " - adding /content/output/images/image_002_top.jpeg with resolution 512x512 --> 224x224\n", " (Found 2 images)\n", ">> Inference with model on 1 image pairs\n" ] }, { "output_type": "stream", "name": "stderr", "text": [ "\n", " 0%| | 0/1 [00:00> Loading a list of 2 images\n", " - adding /content/output/images/image_003_bottom.jpeg with resolution 512x512 --> 224x224\n", " - adding /content/output/images/image_003_bottom.jpeg with resolution 512x512 --> 224x224\n", " (Found 2 images)\n", ">> Inference with model on 1 image pairs\n" ] }, { "output_type": "stream", "name": "stderr", "text": [ "\n", " 0%| | 0/1 [00:00> Loading a list of 2 images\n", " - adding /content/output/images/image_003_top.jpeg with resolution 512x512 --> 224x224\n", " - adding /content/output/images/image_003_top.jpeg with resolution 512x512 --> 224x224\n", " (Found 2 images)\n", ">> Inference with model on 1 image pairs\n" ] }, { "output_type": "stream", "name": "stderr", "text": [ "\n", " 0%| | 0/1 [00:00> Loading a list of 2 images\n", " - adding /content/output/images/image_004_bottom.jpeg with resolution 512x512 --> 224x224\n", " - adding /content/output/images/image_004_bottom.jpeg with resolution 512x512 --> 224x224\n", " (Found 2 images)\n", ">> Inference with model on 1 image pairs\n" ] }, { "output_type": "stream", "name": "stderr", "text": [ "\n", " 0%| | 0/1 [00:00> Loading a list of 2 images\n", " - adding /content/output/images/image_004_top.jpeg with resolution 512x512 --> 224x224\n", " - adding /content/output/images/image_004_top.jpeg with resolution 512x512 --> 224x224\n", " (Found 2 images)\n", ">> Inference with model on 1 image pairs\n" ] }, { "output_type": "stream", "name": "stderr", "text": [ "\n", " 0%| | 0/1 [00:00> Loading a list of 2 images\n", " - adding /content/output/images/image_005_bottom.jpeg with resolution 512x512 --> 224x224\n", " - adding /content/output/images/image_005_bottom.jpeg with resolution 512x512 --> 224x224\n", " (Found 2 images)\n", ">> Inference with model on 1 image pairs\n" ] }, { "output_type": "stream", "name": "stderr", "text": [ "\n", " 0%| | 0/1 [00:00> Loading a list of 2 images\n", " - adding /content/output/images/image_005_top.jpeg with resolution 512x512 --> 224x224\n", " - adding /content/output/images/image_005_top.jpeg with resolution 512x512 --> 224x224\n", " (Found 2 images)\n", ">> Inference with model on 1 image pairs\n" ] }, { "output_type": "stream", "name": "stderr", "text": [ "\n", " 0%| | 0/1 [00:00> Loading a list of 10 images\n", " - adding /content/output/images/image_001_bottom.jpeg with resolution 512x512 --> 224x224\n", " - adding /content/output/images/image_001_top.jpeg with resolution 512x512 --> 224x224\n", " - adding /content/output/images/image_002_bottom.jpeg with resolution 512x512 --> 224x224\n", " - adding /content/output/images/image_002_top.jpeg with resolution 512x512 --> 224x224\n", " - adding /content/output/images/image_003_bottom.jpeg with resolution 512x512 --> 224x224\n", " - adding /content/output/images/image_003_top.jpeg with resolution 512x512 --> 224x224\n", " - adding /content/output/images/image_004_bottom.jpeg with resolution 512x512 --> 224x224\n", " - adding /content/output/images/image_004_top.jpeg with resolution 512x512 --> 224x224\n", " - adding /content/output/images/image_005_bottom.jpeg with resolution 512x512 --> 224x224\n", " - adding /content/output/images/image_005_top.jpeg with resolution 512x512 --> 224x224\n", " (Found 10 images)\n", "Created 45 image pairs\n", "Running inference on 45 pairs...\n", ">> Inference with model on 45 image pairs\n" ] }, { "output_type": "stream", "name": "stderr", "text": [ "100%|██████████| 45/45 [00:09<00:00, 4.51it/s]\n" ] }, { "output_type": "stream", "name": "stdout", "text": [ "✓ Processed 5 predictions\n", "Running global alignment...\n", " init edge (5*,6*) score=24.7253360748291\n", " init edge (0*,6) score=23.234012603759766\n", " init edge (5,8*) score=23.094316482543945\n", " init edge (4*,8) score=17.659948348999023\n", " init edge (1*,5) score=17.392501831054688\n", " init edge (0,2*) score=24.667621612548828\n", " init edge (3*,4) score=18.220979690551758\n", " init edge (3,7*) score=19.910110473632812\n", " init edge (7,9*) score=16.708948135375977\n", " init loss = 0.03214450180530548\n", "Global alignement - optimizing for:\n", "['pw_poses', 'im_depthmaps', 'im_poses', 'im_focals']\n" ] }, { "output_type": "stream", "name": "stderr", "text": [ "100%|██████████| 50/50 [00:01<00:00, 25.27it/s, lr=1.08654e-05 loss=0.0209993]\n" ] }, { "output_type": "stream", "name": "stdout", "text": [ "✓ Alignment complete (loss: 0.020999)\n", "\n", "======================================================================\n", "STEP 4: Converting to COLMAP (PINHOLE)\n", "======================================================================\n", "\n", "=== Extracting Camera Parameters ===\n", "✓ Extracted camera parameters for 10 images\n", "✓ Total 3D points: 501760\n", "✓ After confidence filtering (>0.5): 501760 points\n", "\n", "信頼度統計:\n", " 最小: 1.000000\n", " 平均: 4.890922\n", " 最大: 13.288536\n", " 中央値: 5.084986\n", "\n", "=== カメラポーズ診断 ===\n", "\n", "Camera 1: image_001_bottom.jpeg\n", " 回転行列の行列式: 1.000000 (正常値: 1.0)\n", " 直交性エラー: 3.818126e-07 (正常値: <1e-6)\n", " 並進ベクトルのノルム: 0.025359\n", " カメラ位置 (world): [-0.025, 0.004, 0.003]\n", " 焦点距離: 451.85\n", " 画像サイズ: 896x896\n", " 視野角 (FOV): 89.5°\n", "\n", "Camera 2: image_001_top.jpeg\n", " 回転行列の行列式: 1.000000 (正常値: 1.0)\n", " 直交性エラー: 1.688033e-07 (正常値: <1e-6)\n", " 並進ベクトルのノルム: 0.074167\n", " カメラ位置 (world): [-0.021, -0.011, -0.070]\n", " 焦点距離: 380.72\n", " 画像サイズ: 896x896\n", " 視野角 (FOV): 99.3°\n", "\n", "Camera 3: image_002_bottom.jpeg\n", " 回転行列の行列式: 1.000000 (正常値: 1.0)\n", " 直交性エラー: 1.193865e-07 (正常値: <1e-6)\n", " 並進ベクトルのノルム: 0.030360\n", " カメラ位置 (world): [-0.026, 0.014, -0.005]\n", " 焦点距離: 389.51\n", " 画像サイズ: 896x896\n", " 視野角 (FOV): 98.0°\n", "\n", "=== カメラ配置統計 ===\n", " カメラ数: 10\n", " 中心位置: [-0.008, 0.007, -0.009]\n", " 中心からの平均距離: 0.030\n", " 距離の標準偏差: 0.016\n", " 最小距離: 0.014\n", " 最大距離: 0.065\n", " ⚠️ WARNING: すべてのカメラがほぼ同じ位置にあります!\n", "\n", "=== スケール補正 ===\n", " 現在の平均距離: 0.030\n", " スケール係数: 33.56x\n", " ✓ スケール補正完了\n", " 補正後の平均距離: 1.000\n", "Final point count: 10\n", "✓ Written cameras.bin\n", "✓ Written images.bin (10 images)\n" ] }, { "output_type": "error", "ename": "error", "evalue": "required argument is not a float", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31merror\u001b[0m Traceback (most recent call last)", "\u001b[0;32m/tmp/ipython-input-2075147261.py\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0mOUTPUT_DIR\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m\"/content/output\"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 8\u001b[0;31m gs_output = main_pipeline(\n\u001b[0m\u001b[1;32m 9\u001b[0m \u001b[0mimage_dir\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mIMAGE_DIR\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 10\u001b[0m \u001b[0moutput_dir\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mOUTPUT_DIR\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;32m/tmp/ipython-input-267542218.py\u001b[0m in \u001b[0;36mmain_pipeline\u001b[0;34m(image_dir, output_dir, square_size, iterations, max_images, max_pairs, max_points, conf_threshold, preprocess_mode)\u001b[0m\n\u001b[1;32m 111\u001b[0m \u001b[0mos\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmakedirs\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mcolmap_dir\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mexist_ok\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mTrue\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 112\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 113\u001b[0;31m \u001b[0mwrite_colmap_sparse\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mcameras_dict\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mpts3d\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mconfidence\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mimage_paths\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mcolmap_dir\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 114\u001b[0m \u001b[0mclear_memory\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 115\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;32m/tmp/ipython-input-1860118596.py\u001b[0m in \u001b[0;36mwrite_colmap_sparse\u001b[0;34m(cameras_dict, pts3d, confidence, image_paths, output_dir)\u001b[0m\n\u001b[1;32m 85\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mpoint_id\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mpoint\u001b[0m \u001b[0;32min\u001b[0m \u001b[0menumerate\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mpts3d\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mstart\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 86\u001b[0m \u001b[0mf\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mwrite\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mstruct\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mpack\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'Q'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mpoint_id\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 87\u001b[0;31m \u001b[0mf\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mwrite\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mstruct\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mpack\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'd'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mpoint\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 88\u001b[0m \u001b[0mf\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mwrite\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mstruct\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mpack\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'd'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mpoint\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 89\u001b[0m \u001b[0mf\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mwrite\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mstruct\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mpack\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'd'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mpoint\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31merror\u001b[0m: required argument is not a float" ] } ], "execution_count": 17 }, { "cell_type": "code", "source": [], "metadata": { "id": "dw6wKvs3kHzi" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [], "metadata": { "id": "S5QAbdhRhNqQ" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [], "metadata": { "id": "aD_jlGNwzfvf" } }, { "cell_type": "code", "source": [], "metadata": { "trusted": true, "id": "Ontdbh48jLmI" }, "outputs": [], "execution_count": null }, { "cell_type": "markdown", "source": [ "\n", "\n", "## 🔧 主要な修正:\n", "\n", "### 1. **特徴量抽出の修正 (CELL 12)**\n", "- RGB画像 `[H, W, 3]` が返される問題を修正\n", "- 特徴量次元が小さい場合は自動的に64次元に拡張\n", "- より堅牢なエラーハンドリング\n", "\n", "### 2. **ASMK類似度計算の修正 (CELL 13)**\n", "- Codebookの使用を削除し、シンプルなコサイン類似度に変更\n", "- 次元ミスマッチエラーを完全に解消\n", "- 動的な特徴量次元に対応\n", "\n", "### 3. **カメラパラメータの修正 (CELL 15)**\n", "- 画像サイズ情報を明示的に保存 (`width`, `height`)\n", "- より堅牢なエラーハンドリング\n", "\n", "### 4. **コード構造の改善**\n", "- 各セルを独立して実行可能に\n", "- メモリ管理の最適化\n", "- エラーメッセージの改善\n", "\n", "## 📋 使用方法:\n", "\n", "1. **セル1**: 依存関係をインストール\n", "2. **セル2**: カーネルを再起動(コメント)\n", "3. **セル3-19**: 順番に実行\n", "4. **セル20**: パイプラインを実行\n", "\n", "## ✨ 改善点:\n", "\n", "- ✅ ASMK失敗エラーを完全に解決\n", "- ✅ 特徴量次元の動的対応\n", "- ✅ メモリ効率の改善\n", "- ✅ より詳細なログ出力\n", "- ✅ エラー時の自動リカバリー\n", "\n" ], "metadata": { "id": "K-TGZRlcjLmI" } } ] }