{ "cells": [ { "cell_type": "markdown", "id": "fb1f1fdc", "metadata": { "papermill": { "duration": 0.002985, "end_time": "2026-01-10T18:17:32.170524", "exception": false, "start_time": "2026-01-10T18:17:32.167539", "status": "completed" }, "tags": [], "id": "fb1f1fdc" }, "source": [ "# **biplet-colmap-mipgs-colab-00**" ] }, { "cell_type": "code", "source": [ "#サイズの異なる画像を扱う\n", "from google.colab import drive\n", "drive.mount('/content/drive')" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "JON4rYSEOzCg", "outputId": "26faa569-d3de-41d3-be2f-fbf38d363f7a" }, "id": "JON4rYSEOzCg", "execution_count": 3, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Mounted at /content/drive\n" ] } ] }, { "cell_type": "code", "execution_count": 4, "id": "22353010", "metadata": { "execution": { "iopub.execute_input": "2026-01-10T18:17:32.181455Z", "iopub.status.busy": "2026-01-10T18:17:32.180969Z", "iopub.status.idle": "2026-01-10T18:17:32.355942Z", "shell.execute_reply": "2026-01-10T18:17:32.355229Z" }, "papermill": { "duration": 0.179454, "end_time": "2026-01-10T18:17:32.357275", "exception": false, "start_time": "2026-01-10T18:17:32.177821", "status": "completed" }, "tags": [], "id": "22353010" }, "outputs": [], "source": [ "import os\n", "import sys\n", "import subprocess\n", "import shutil\n", "from pathlib import Path\n", "import cv2\n", "from PIL import Image\n", "import glob\n", "\n", "IMAGE_PATH=\"/content/drive/MyDrive/your_folder/fountain100\"\n", "WORK_DIR = '/content/mip-splatting'\n", "OUTPUT_DIR = '/content/output'\n", "COLMAP_DIR = '/content/colmap_data'" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "execution": { "iopub.execute_input": "2026-01-10T18:22:43.807508Z", "iopub.status.busy": "2026-01-10T18:22:43.807294Z", "iopub.status.idle": "2026-01-11T00:00:17.030890Z", "shell.execute_reply": "2026-01-11T00:00:17.029927Z" }, "papermill": { "duration": 20253.434865, "end_time": "2026-01-11T00:00:17.234174", "exception": false, "start_time": "2026-01-10T18:22:43.799309", "status": "completed" }, "tags": [], "id": "QXI_UOXaNbgI" }, "outputs": [], "source": [ "\n" ], "id": "QXI_UOXaNbgI" }, { "cell_type": "code", "execution_count": 5, "id": "be6df249", "metadata": { "execution": { "iopub.execute_input": "2026-01-10T18:17:32.363444Z", "iopub.status.busy": "2026-01-10T18:17:32.363175Z", "iopub.status.idle": "2026-01-10T18:22:43.720241Z", "shell.execute_reply": "2026-01-10T18:22:43.719380Z" }, "papermill": { "duration": 311.361656, "end_time": "2026-01-10T18:22:43.721610", "exception": false, "start_time": "2026-01-10T18:17:32.359954", "status": "completed" }, "tags": [], "id": "be6df249", "outputId": "9f6895a6-db59-4d18-bddd-b2e42d047cf9", "colab": { "base_uri": "https://localhost:8080/" } }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "======================================================================\n", "Setting up mip-splatting environment\n", "======================================================================\n", "\n", "STEP 1: Clone mip-splatting repository\n", "======================================================================\n", " > Cloning mip-splatting with submodules...\n", "Running: git clone --recursive https://github.com/autonomousvision/mip-splatting.git /content/mip-splatting\n", "✅ Repository cloned with submodules\n", "\n", " > Verifying submodules...\n", " > Found submodules: ['diff-gaussian-rasterization', 'simple-knn']\n", "\n", "======================================================================\n", "STEP 1: System packages\n", "======================================================================\n", "Running: apt-get update -qq\n", "Running: apt-get install -y -qq colmap build-essential cmake git libopenblas-dev xvfb\n", "\n", "STEP 2: Fix numpy compatibility\n", "======================================================================\n", " > Uninstalling numpy 2.x...\n", "Running: /usr/bin/python3 -m pip uninstall numpy -y\n", " > Installing numpy<2.0...\n", "Running: /usr/bin/python3 -m pip install numpy<2.0\n", "✅ numpy<2.0 installed\n", "\n", "STEP 3: Install core dependencies\n", "======================================================================\n", " > Installing open3d...\n", "Running: /usr/bin/python3 -m pip install open3d\n", " > Installing plyfile...\n", "Running: /usr/bin/python3 -m pip install plyfile\n", " > Installing tqdm...\n", "Running: /usr/bin/python3 -m pip install tqdm\n", " > Installing Pillow...\n", "Running: /usr/bin/python3 -m pip install Pillow\n", " > Installing opencv-python...\n", "Running: /usr/bin/python3 -m pip install opencv-python\n", "✅ Core dependencies installed\n", "\n", "STEP 4: Build mip-splatting submodules\n", "======================================================================\n", "\n", "======================================================================\n", "Installing simple-knn\n", "======================================================================\n", " > Target path: /content/mip-splatting/submodules/simple-knn\n", " > Removing old simple-knn...\n", " > Cloning from https://github.com/tztechno/simple-knn.git...\n", "Running: git clone https://github.com/tztechno/simple-knn.git /content/mip-splatting/submodules/simple-knn\n", " > Checking cloned files...\n", " > Files in simple-knn: ['spatial.cu', '.gitignore', '.git', 'setup.py', 'simple_knn.h', 'simple_knn0.cu', 'ext.cpp', 'simple_knn', 'spatial.h', 'simple_knn.cu']...\n", " > Installing simple-knn (This may take a few minutes)...\n", "✅ Successfully installed simple-knn\n", "\n", "======================================================================\n", "Installing diff-gaussian-rasterization (from mip-splatting submodules)\n", "======================================================================\n", " > Target path: /content/mip-splatting/submodules/diff-gaussian-rasterization\n", " > Checking files...\n", " > Files in diff-gaussian-rasterization: ['LICENSE.md', 'rasterize_points.h', 'cuda_rasterizer', 'diff_gaussian_rasterization', 'setup.py', 'ext.cpp', 'rasterize_points.cu', 'diff_gaussian_rasterization.egg-info', 'CMakeLists.txt', 'third_party']...\n", " > Installing diff-gaussian-rasterization (This may take a few minutes)...\n", "✅ Successfully installed diff-gaussian-rasterization\n" ] } ], "source": [ "def run_cmd(cmd, check=True, capture=False, cwd=None): # ← cwd=None を追加\n", " \"\"\"Run command with better error handling\"\"\"\n", " print(f\"Running: {' '.join(cmd)}\")\n", " result = subprocess.run(\n", " cmd,\n", " capture_output=capture,\n", " text=True,\n", " check=False,\n", " cwd=cwd # ← ここに渡す\n", " )\n", " if check and result.returncode != 0:\n", " print(f\"❌ Command failed with code {result.returncode}\")\n", " if capture:\n", " print(f\"STDOUT: {result.stdout}\")\n", " print(f\"STDERR: {result.stderr}\")\n", " return result\n", "\n", "\n", "def install_submodule(name, url, base_dir):\n", " \"\"\"個別のサブモジュールをインストール\"\"\"\n", " print(f\"\\n{'='*70}\")\n", " print(f\"Installing {name}\")\n", " print(f\"{'='*70}\")\n", "\n", " # 絶対パスを使用\n", " path = os.path.abspath(os.path.join(base_dir, \"submodules\", name))\n", " print(f\" > Target path: {path}\")\n", "\n", " # Step 1: 既存を削除\n", " if os.path.exists(path):\n", " print(f\" > Removing old {name}...\")\n", " shutil.rmtree(path)\n", "\n", " # Step 2: クローン\n", " print(f\" > Cloning from {url}...\")\n", " os.makedirs(os.path.dirname(path), exist_ok=True)\n", " try:\n", " run_cmd([\"git\", \"clone\", url, path])\n", " except subprocess.CalledProcessError as e:\n", " print(f\"❌ Failed to clone {name}\")\n", " print(e.stderr)\n", " return False\n", "\n", " # Step 3: ファイル確認\n", " print(f\" > Checking cloned files...\")\n", " files = os.listdir(path)\n", " print(f\" > Files in {name}: {files[:10]}...\")\n", "\n", " # Step 4: ビルドキャッシュ削除\n", " build_dir = os.path.join(path, \"build\")\n", " if os.path.exists(build_dir):\n", " print(f\" > Cleaning build cache...\")\n", " shutil.rmtree(build_dir)\n", "\n", " # Step 5: インストール\n", " print(f\" > Installing {name} (This may take a few minutes)...\")\n", "\n", " # 環境変数を明示的に引き継ぐ\n", " current_env = os.environ.copy()\n", " result = subprocess.run(\n", " [sys.executable, \"-m\", \"pip\", \"install\", \"-e\", \".\", \"--no-build-isolation\", \"-v\"],\n", " cwd=path,\n", " env=current_env,\n", " capture_output=True,\n", " text=True\n", " )\n", "\n", " if result.returncode != 0:\n", " print(f\"❌ Failed to install {name}\")\n", " # C++/CUDAのビルドエラーは stdout に出ることが多いため、両方出力\n", " print(\"\\n--- STDOUT (Build Logs) ---\")\n", " stdout_lines = result.stdout.split('\\n')\n", " print('\\n'.join(stdout_lines[-60:])) # 最後の60行を表示\n", " print(\"\\n--- STDERR (Error Details) ---\")\n", " print(result.stderr)\n", " return False\n", "\n", " print(f\"✅ Successfully installed {name}\")\n", " return True\n", "\n", "\n", "def install_mipsplatting_submodule(name, base_dir):\n", " \"\"\"mip-splattingに含まれるsubmoduleをインストール(クローン不要)\"\"\"\n", " print(f\"\\n{'='*70}\")\n", " print(f\"Installing {name} (from mip-splatting submodules)\")\n", " print(f\"{'='*70}\")\n", "\n", " # submoduleのパス\n", " path = os.path.abspath(os.path.join(base_dir, \"submodules\", name))\n", " print(f\" > Target path: {path}\")\n", "\n", " # ファイルの存在確認\n", " if not os.path.exists(path):\n", " print(f\"❌ Path not found: {path}\")\n", " return False\n", "\n", " # setup.pyの存在確認\n", " setup_py = os.path.join(path, \"setup.py\")\n", " if not os.path.exists(setup_py):\n", " print(f\"❌ setup.py not found: {setup_py}\")\n", " return False\n", "\n", " print(f\" > Checking files...\")\n", " files = os.listdir(path)\n", " print(f\" > Files in {name}: {files[:10]}...\")\n", "\n", " # ビルドキャッシュ削除\n", " build_dir = os.path.join(path, \"build\")\n", " if os.path.exists(build_dir):\n", " print(f\" > Cleaning build cache...\")\n", " shutil.rmtree(build_dir)\n", "\n", " # インストール\n", " print(f\" > Installing {name} (This may take a few minutes)...\")\n", "\n", " current_env = os.environ.copy()\n", " result = subprocess.run(\n", " [sys.executable, \"-m\", \"pip\", \"install\", \"-e\", \".\", \"--no-build-isolation\", \"-v\"],\n", " cwd=path,\n", " env=current_env,\n", " capture_output=True,\n", " text=True\n", " )\n", "\n", " if result.returncode != 0:\n", " print(f\"❌ Failed to install {name}\")\n", " print(\"\\n--- STDOUT (Build Logs) ---\")\n", " stdout_lines = result.stdout.split('\\n')\n", " print('\\n'.join(stdout_lines[-60:]))\n", " print(\"\\n--- STDERR (Error Details) ---\")\n", " print(result.stderr)\n", " return False\n", "\n", " print(f\"✅ Successfully installed {name}\")\n", " return True\n", "\n", "\n", "def setup_environment():\n", " \"\"\"Setup mip-splatting environment with correct submodules\"\"\"\n", " print(\"=\"*70)\n", " print(\"Setting up mip-splatting environment\")\n", " print(\"=\"*70)\n", "\n", " WORK_DIR = \"/content/mip-splatting\"\n", "\n", " # =====================================================================\n", " # STEP 1: Clone main repository with submodules\n", " # =====================================================================\n", " print(\"\\nSTEP 1: Clone mip-splatting repository\")\n", " print(\"=\"*70)\n", "\n", " if os.path.exists(WORK_DIR):\n", " print(f\" > {WORK_DIR} already exists, removing...\")\n", " shutil.rmtree(WORK_DIR)\n", "\n", " print(f\" > Cloning mip-splatting with submodules...\")\n", " # --recursive で submodules も一緒にクローン\n", " run_cmd([\n", " \"git\", \"clone\", \"--recursive\",\n", " \"https://github.com/autonomousvision/mip-splatting.git\",\n", " WORK_DIR\n", " ])\n", " print(\"✅ Repository cloned with submodules\")\n", "\n", " # submodulesが正しくクローンされたか確認\n", " print(\"\\n > Verifying submodules...\")\n", " submodules_dir = os.path.join(WORK_DIR, \"submodules\")\n", " if os.path.exists(submodules_dir):\n", " items = os.listdir(submodules_dir)\n", " print(f\" > Found submodules: {items}\")\n", "\n", " # 空のsubmoduleディレクトリがある場合は初期化\n", " for item in items:\n", " item_path = os.path.join(submodules_dir, item)\n", " if os.path.isdir(item_path):\n", " item_files = os.listdir(item_path)\n", " if not item_files or len(item_files) == 0:\n", " print(f\" > {item} is empty, initializing...\")\n", " run_cmd([\"git\", \"submodule\", \"update\", \"--init\", \"--recursive\"], cwd=WORK_DIR)\n", " break\n", " # =====================================================================\n", " # STEP 1: System packages (Colab)\n", " # =====================================================================\n", " print(\"\\n\" + \"=\"*70)\n", " print(\"STEP 1: System packages\")\n", " print(\"=\"*70)\n", "\n", " run_cmd([\"apt-get\", \"update\", \"-qq\"])\n", " run_cmd([\n", " \"apt-get\", \"install\", \"-y\", \"-qq\",\n", " \"colmap\",\n", " \"build-essential\",\n", " \"cmake\",\n", " \"git\",\n", " \"libopenblas-dev\",\n", " \"xvfb\"\n", " ])\n", "\n", " # virtual display (COLMAP / OpenCV safety)\n", " os.environ[\"QT_QPA_PLATFORM\"] = \"offscreen\"\n", " os.environ[\"DISPLAY\"] = \":99\"\n", " subprocess.Popen(\n", " [\"Xvfb\", \":99\", \"-screen\", \"0\", \"1024x768x24\"],\n", " stdout=subprocess.DEVNULL,\n", " stderr=subprocess.DEVNULL\n", " )\n", "\n", " # =====================================================================\n", " # STEP 2: Fix numpy compatibility\n", " # =====================================================================\n", " print(\"\\nSTEP 2: Fix numpy compatibility\")\n", " print(\"=\"*70)\n", "\n", " print(\" > Uninstalling numpy 2.x...\")\n", " run_cmd([sys.executable, \"-m\", \"pip\", \"uninstall\", \"numpy\", \"-y\"], check=False)\n", "\n", " print(\" > Installing numpy<2.0...\")\n", " run_cmd([sys.executable, \"-m\", \"pip\", \"install\", \"numpy<2.0\"])\n", " print(\"✅ numpy<2.0 installed\")\n", "\n", " # =====================================================================\n", " # STEP 3: Install core dependencies\n", " # =====================================================================\n", " print(\"\\nSTEP 3: Install core dependencies\")\n", " print(\"=\"*70)\n", "\n", " core_packages = [\n", " \"open3d\",\n", " \"plyfile\",\n", " \"tqdm\",\n", " \"Pillow\",\n", " \"opencv-python\"\n", " ]\n", "\n", " for package in core_packages:\n", " print(f\" > Installing {package}...\")\n", " run_cmd([sys.executable, \"-m\", \"pip\", \"install\", package])\n", " print(\"✅ Core dependencies installed\")\n", "\n", " # =====================================================================\n", " # STEP 4: Build mip-splatting submodules\n", " # =====================================================================\n", " print(\"\\nSTEP 4: Build mip-splatting submodules\")\n", " print(\"=\"*70)\n", "\n", " # simple-knn: 実績のあるfixed版を使用(クローンし直す)\n", " success_knn = install_submodule(\n", " \"simple-knn\",\n", " \"https://github.com/tztechno/simple-knn.git\",\n", " WORK_DIR\n", " )\n", "\n", " if not success_knn:\n", " print(\"❌ Failed to install simple-knn\")\n", " return None\n", "\n", " # diff-gaussian-rasterization: mip-splattingに含まれているものを使用\n", " # (kernel_size対応版なのでクローンし直さない)\n", " success_rast = install_mipsplatting_submodule(\n", " \"diff-gaussian-rasterization\",\n", " WORK_DIR\n", " )\n", "\n", " if not success_rast:\n", " print(\"❌ Failed to install diff-gaussian-rasterization\")\n", " return None\n", "\n", "\n", " return WORK_DIR\n", "\n", "\n", "\n", "work_dir = setup_environment()\n", "\n" ] }, { "cell_type": "code", "execution_count": 6, "id": "b8690389", "metadata": { "execution": { "iopub.execute_input": "2026-01-10T18:22:43.739411Z", "iopub.status.busy": "2026-01-10T18:22:43.738855Z", "iopub.status.idle": "2026-01-10T18:22:43.755664Z", "shell.execute_reply": "2026-01-10T18:22:43.754865Z" }, "papermill": { "duration": 0.027297, "end_time": "2026-01-10T18:22:43.756758", "exception": false, "start_time": "2026-01-10T18:22:43.729461", "status": "completed" }, "tags": [], "id": "b8690389" }, "outputs": [], "source": [ "import os\n", "import glob\n", "import cv2\n", "import numpy as np\n", "from PIL import Image\n", "\n", "# =========================================================\n", "# Utility: aspect ratio preserved + black padding\n", "# =========================================================\n", "\n", "def normalize_image_sizes_biplet(input_dir, output_dir=None, size=1024, max_images=None):\n", " \"\"\"\n", " Generates two square crops (Left & Right or Top & Bottom)\n", " from each image in a directory and returns the output directory\n", " and the list of generated file paths.\n", "\n", " Args:\n", " input_dir: Input directory containing source images\n", " output_dir: Output directory for processed images\n", " size: Target square size (default: 1024)\n", " max_images: Maximum number of SOURCE images to process (default: None = all images)\n", " \"\"\"\n", " if output_dir is None:\n", " output_dir = 'output/images_biplet'\n", " os.makedirs(output_dir, exist_ok=True)\n", "\n", " print(f\"--- Step 1: Biplet-Square Normalization ---\")\n", " print(f\"Generating 2 cropped squares (Left/Right or Top/Bottom) for each image...\")\n", " print()\n", "\n", " generated_paths = []\n", " converted_count = 0\n", " size_stats = {}\n", "\n", " # Sort for consistent processing order\n", " image_files = sorted([f for f in os.listdir(input_dir)\n", " if f.lower().endswith(('.jpg', '.jpeg', '.png'))])\n", "\n", " # ★ max_images で元画像数を制限\n", " if max_images is not None:\n", " image_files = image_files[:max_images]\n", " print(f\"Processing limited to {max_images} source images (will generate {max_images * 2} cropped images)\")\n", "\n", " for img_file in image_files:\n", " input_path = os.path.join(input_dir, img_file)\n", " try:\n", " img = Image.open(input_path)\n", " original_size = img.size\n", "\n", " # Tracking original aspect ratios\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 using the helper function\n", " crops = generate_two_crops(img, size)\n", " base_name, ext = os.path.splitext(img_file)\n", "\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", " generated_paths.append(output_path)\n", "\n", " converted_count += 1\n", " print(f\" ✓ {img_file}: {original_size} → 2 square images generated\")\n", "\n", " except Exception as e:\n", " print(f\" ✗ Error processing {img_file}: {e}\")\n", "\n", " print(f\"\\nProcessing complete: {converted_count} source images processed\")\n", " print(f\"Total output images: {len(generated_paths)}\")\n", " print(f\"Original size distribution: {size_stats}\")\n", "\n", " return output_dir, generated_paths\n", "\n", "\n", "def generate_two_crops(img, size):\n", " \"\"\"\n", " Crops the image into a square and returns 2 variations\n", " (Left/Right for landscape, Top/Bottom for portrait).\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", "\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" ] }, { "cell_type": "code", "execution_count": 7, "id": "7acc20b6", "metadata": { "execution": { "iopub.execute_input": "2026-01-10T18:22:43.772525Z", "iopub.status.busy": "2026-01-10T18:22:43.772303Z", "iopub.status.idle": "2026-01-10T18:22:43.790574Z", "shell.execute_reply": "2026-01-10T18:22:43.789515Z" }, "papermill": { "duration": 0.027612, "end_time": "2026-01-10T18:22:43.791681", "exception": false, "start_time": "2026-01-10T18:22:43.764069", "status": "completed" }, "tags": [], "id": "7acc20b6" }, "outputs": [], "source": [ "def run_colmap_reconstruction(image_dir, colmap_dir):\n", " \"\"\"Estimate camera poses and 3D point cloud with COLMAP\"\"\"\n", " print(\"Running SfM reconstruction with COLMAP...\")\n", "\n", " database_path = os.path.join(colmap_dir, \"database.db\")\n", " sparse_dir = os.path.join(colmap_dir, \"sparse\")\n", " os.makedirs(sparse_dir, exist_ok=True)\n", "\n", " # Set environment variable\n", " env = os.environ.copy()\n", " env['QT_QPA_PLATFORM'] = 'offscreen'\n", "\n", " # Feature extraction\n", " print(\"1/4: Extracting features...\")\n", " subprocess.run([\n", " 'colmap', 'feature_extractor',\n", " '--database_path', database_path,\n", " '--image_path', image_dir,\n", " '--ImageReader.single_camera', '1',\n", " '--ImageReader.camera_model', 'OPENCV',\n", " '--SiftExtraction.use_gpu', '0' # Use CPU\n", " ], check=True, env=env)\n", "\n", " # Feature matching\n", " print(\"2/4: Matching features...\")\n", " subprocess.run([\n", " 'colmap', 'exhaustive_matcher', # Use sequential_matcher instead of exhaustive_matcher\n", " '--database_path', database_path,\n", " '--SiftMatching.use_gpu', '0' # Use CPU\n", " ], check=True, env=env)\n", "\n", " # Sparse reconstruction\n", " print(\"3/4: Sparse reconstruction...\")\n", " subprocess.run([\n", " 'colmap', 'mapper',\n", " '--database_path', database_path,\n", " '--image_path', image_dir,\n", " '--output_path', sparse_dir,\n", " '--Mapper.ba_global_max_num_iterations', '20', # Speed up\n", " '--Mapper.ba_local_max_num_iterations', '10'\n", " ], check=True, env=env)\n", "\n", " # Export to text format\n", " print(\"4/4: Exporting to text format...\")\n", " model_dir = os.path.join(sparse_dir, '0')\n", " if not os.path.exists(model_dir):\n", " # Use the first model found\n", " subdirs = [d for d in os.listdir(sparse_dir) if os.path.isdir(os.path.join(sparse_dir, d))]\n", " if subdirs:\n", " model_dir = os.path.join(sparse_dir, subdirs[0])\n", " else:\n", " raise FileNotFoundError(\"COLMAP reconstruction failed\")\n", "\n", " subprocess.run([\n", " 'colmap', 'model_converter',\n", " '--input_path', model_dir,\n", " '--output_path', model_dir,\n", " '--output_type', 'TXT'\n", " ], check=True, env=env)\n", "\n", " print(f\"COLMAP reconstruction complete: {model_dir}\")\n", " return model_dir\n", "\n", "\n", "def convert_cameras_to_pinhole(input_file, output_file):\n", " \"\"\"Convert camera model to PINHOLE format\"\"\"\n", " print(f\"Reading camera file: {input_file}\")\n", "\n", " with open(input_file, 'r') as f:\n", " lines = f.readlines()\n", "\n", " converted_count = 0\n", " with open(output_file, 'w') as f:\n", " for line in lines:\n", " if line.startswith('#') or line.strip() == '':\n", " f.write(line)\n", " else:\n", " parts = line.strip().split()\n", " if len(parts) >= 4:\n", " cam_id = parts[0]\n", " model = parts[1]\n", " width = parts[2]\n", " height = parts[3]\n", " params = parts[4:]\n", "\n", " # Convert to PINHOLE format\n", " if model == \"PINHOLE\":\n", " f.write(line)\n", " elif model == \"OPENCV\":\n", " # OPENCV: fx, fy, cx, cy, k1, k2, p1, p2\n", " fx = params[0]\n", " fy = params[1]\n", " cx = params[2]\n", " cy = params[3]\n", " f.write(f\"{cam_id} PINHOLE {width} {height} {fx} {fy} {cx} {cy}\\n\")\n", " converted_count += 1\n", " else:\n", " # Convert other models too\n", " fx = fy = max(float(width), float(height))\n", " cx = float(width) / 2\n", " cy = float(height) / 2\n", " f.write(f\"{cam_id} PINHOLE {width} {height} {fx} {fy} {cx} {cy}\\n\")\n", " converted_count += 1\n", " else:\n", " f.write(line)\n", "\n", " print(f\"Converted {converted_count} cameras to PINHOLE format\")\n", "\n", "\n", "def prepare_gaussian_splatting_data(image_dir, colmap_model_dir):\n", " \"\"\"Prepare data for Gaussian Splatting\"\"\"\n", " print(\"Preparing data for Gaussian Splatting...\")\n", "\n", " data_dir = f\"{WORK_DIR}/data/video\"\n", " os.makedirs(f\"{data_dir}/sparse/0\", exist_ok=True)\n", " os.makedirs(f\"{data_dir}/images\", exist_ok=True)\n", "\n", " # Copy images\n", " print(\"Copying images...\")\n", " img_count = 0\n", " for img_file in os.listdir(image_dir):\n", " if img_file.lower().endswith(('.jpg', '.jpeg', '.png')):\n", " shutil.copy(\n", " os.path.join(image_dir, img_file),\n", " f\"{data_dir}/images/{img_file}\"\n", " )\n", " img_count += 1\n", " print(f\"Copied {img_count} images\")\n", "\n", " # Convert and copy camera file to PINHOLE format\n", " print(\"Converting camera model to PINHOLE format...\")\n", " convert_cameras_to_pinhole(\n", " os.path.join(colmap_model_dir, 'cameras.txt'),\n", " f\"{data_dir}/sparse/0/cameras.txt\"\n", " )\n", "\n", " # Copy other files\n", " for filename in ['images.txt', 'points3D.txt']:\n", " src = os.path.join(colmap_model_dir, filename)\n", " dst = f\"{data_dir}/sparse/0/{filename}\"\n", " if os.path.exists(src):\n", " shutil.copy(src, dst)\n", " print(f\"Copied {filename}\")\n", " else:\n", " print(f\"Warning: {filename} not found\")\n", "\n", " print(f\"Data preparation complete: {data_dir}\")\n", " return data_dir\n", "\n", "\n", "\n", "\n", "# After (mipGS) - Added Kernel Size and Multi-Scale Support\n", "def train_gaussian_splatting(data_dir, work_dir, iterations=3000):\n", " \"\"\"Training function for mipGS with comprehensive error handling\"\"\"\n", "\n", " # 入力検証\n", " if not work_dir:\n", " raise ValueError(\"work_dir cannot be None or empty\")\n", "\n", " if not os.path.exists(work_dir):\n", " raise FileNotFoundError(f\"Work directory not found: {work_dir}\")\n", "\n", " if not os.path.exists(data_dir):\n", " raise FileNotFoundError(f\"Data directory not found: {data_dir}\")\n", "\n", " train_py_path = os.path.join(work_dir, \"train.py\")\n", " if not os.path.exists(train_py_path):\n", " raise FileNotFoundError(f\"train.py not found: {train_py_path}\")\n", "\n", " # モデル保存パス\n", " model_path = os.path.join(work_dir, \"output\", \"video\")\n", " os.makedirs(model_path, exist_ok=True)\n", "\n", " # コマンド構築\n", " cmd = [\n", " sys.executable, 'train.py',\n", " '-s', data_dir,\n", " '-m', model_path,\n", " '--iterations', str(iterations),\n", " '--eval'\n", " ]\n", "\n", " print(f\"Training configuration:\")\n", " print(f\" Work dir: {work_dir}\")\n", " print(f\" Data dir: {data_dir}\")\n", " print(f\" Model path: {model_path}\")\n", " print(f\" Command: {' '.join(cmd)}\")\n", "\n", " # 実行\n", " result = subprocess.run(\n", " cmd,\n", " cwd=work_dir,\n", " capture_output=True,\n", " text=True\n", " )\n", "\n", " # エラーチェック\n", " if result.returncode != 0:\n", " print(f\"\\n❌ Training failed with exit code {result.returncode}\")\n", " print(\"\\n--- STDOUT ---\")\n", " print(result.stdout)\n", " print(\"\\n--- STDERR ---\")\n", " print(result.stderr)\n", " raise subprocess.CalledProcessError(result.returncode, cmd)\n", "\n", " print(\"\\n✅ Training completed successfully\")\n", " return model_path\n", "\n" ] }, { "cell_type": "code", "source": [ "# New function for mipGS - Fuse 3D filter into Gaussian parameters\n", "def create_fused_ply(model_path, scene_name, output_dir=\"fused\"):\n", " \"\"\"\n", " Fuse the 3D smoothing filter to Gaussian parameters for deployment\n", " This creates a .ply file that can be used in online viewers\n", "\n", " Args:\n", " model_path: Path to trained model\n", " scene_name: Name of the scene\n", " output_dir: Directory to save fused .ply file\n", " \"\"\"\n", " os.makedirs(output_dir, exist_ok=True)\n", " output_ply = f\"{output_dir}/{scene_name}_fused.ply\"\n", "\n", " cmd = [\n", " sys.executable, 'create_fused_ply.py',\n", " '-m', f\"{model_path}/{scene_name}\",\n", " '--output_ply', output_ply\n", " ]\n", " subprocess.run(cmd, cwd=WORK_DIR, check=True)\n", " return output_ply\n", "" ], "metadata": { "id": "-Cwgr3I0b57O" }, "id": "-Cwgr3I0b57O", "execution_count": 8, "outputs": [] }, { "cell_type": "code", "execution_count": 9, "id": "f75233a8", "metadata": { "execution": { "iopub.execute_input": "2026-01-10T18:22:43.807508Z", "iopub.status.busy": "2026-01-10T18:22:43.807294Z", "iopub.status.idle": "2026-01-11T00:00:17.030890Z", "shell.execute_reply": "2026-01-11T00:00:17.029927Z" }, "papermill": { "duration": 20253.434865, "end_time": "2026-01-11T00:00:17.234174", "exception": false, "start_time": "2026-01-10T18:22:43.799309", "status": "completed" }, "tags": [], "id": "f75233a8", "outputId": "4d068a8d-5a0b-4fb5-dbc7-c89fe2422fd6", "colab": { "base_uri": "https://localhost:8080/" } }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "============================================================\n", "Step 1: Normalizing and preprocessing images\n", "============================================================\n", "--- Step 1: Biplet-Square Normalization ---\n", "Generating 2 cropped squares (Left/Right or Top/Bottom) for each image...\n", "\n", "Processing limited to 20 source images (will generate 40 cropped images)\n", " ✓ image_101.jpeg: (1440, 1920) → 2 square images generated\n", " ✓ image_102.jpeg: (1440, 1920) → 2 square images generated\n", " ✓ image_103.jpeg: (1440, 1920) → 2 square images generated\n", " ✓ image_104.jpeg: (1440, 1920) → 2 square images generated\n", " ✓ image_105.jpeg: (1440, 1920) → 2 square images generated\n", " ✓ image_106.jpeg: (1440, 1920) → 2 square images generated\n", " ✓ image_107.jpeg: (1440, 1920) → 2 square images generated\n", " ✓ image_108.jpeg: (1440, 1920) → 2 square images generated\n", " ✓ image_109.jpeg: (1440, 1920) → 2 square images generated\n", " ✓ image_110.jpeg: (1440, 1920) → 2 square images generated\n", " ✓ image_111.jpeg: (1440, 1920) → 2 square images generated\n", " ✓ image_112.jpeg: (1440, 1920) → 2 square images generated\n", " ✓ image_113.jpeg: (1440, 1920) → 2 square images generated\n", " ✓ image_114.jpeg: (1440, 1920) → 2 square images generated\n", " ✓ image_115.jpeg: (1440, 1920) → 2 square images generated\n", " ✓ image_116.jpeg: (1440, 1920) → 2 square images generated\n", " ✓ image_117.jpeg: (1440, 1920) → 2 square images generated\n", " ✓ image_118.jpeg: (1440, 1920) → 2 square images generated\n", " ✓ image_119.jpeg: (1440, 1920) → 2 square images generated\n", " ✓ image_120.jpeg: (1440, 1920) → 2 square images generated\n", "\n", "Processing complete: 20 source images processed\n", "Total output images: 40\n", "Original size distribution: {'1440x1920': 20}\n", "Processed ('/content/colmap/images', ['/content/colmap/images/image_101_top.jpeg', '/content/colmap/images/image_101_bottom.jpeg', '/content/colmap/images/image_102_top.jpeg', '/content/colmap/images/image_102_bottom.jpeg', '/content/colmap/images/image_103_top.jpeg', '/content/colmap/images/image_103_bottom.jpeg', '/content/colmap/images/image_104_top.jpeg', '/content/colmap/images/image_104_bottom.jpeg', '/content/colmap/images/image_105_top.jpeg', '/content/colmap/images/image_105_bottom.jpeg', '/content/colmap/images/image_106_top.jpeg', '/content/colmap/images/image_106_bottom.jpeg', '/content/colmap/images/image_107_top.jpeg', '/content/colmap/images/image_107_bottom.jpeg', '/content/colmap/images/image_108_top.jpeg', '/content/colmap/images/image_108_bottom.jpeg', '/content/colmap/images/image_109_top.jpeg', '/content/colmap/images/image_109_bottom.jpeg', '/content/colmap/images/image_110_top.jpeg', '/content/colmap/images/image_110_bottom.jpeg', '/content/colmap/images/image_111_top.jpeg', '/content/colmap/images/image_111_bottom.jpeg', '/content/colmap/images/image_112_top.jpeg', '/content/colmap/images/image_112_bottom.jpeg', '/content/colmap/images/image_113_top.jpeg', '/content/colmap/images/image_113_bottom.jpeg', '/content/colmap/images/image_114_top.jpeg', '/content/colmap/images/image_114_bottom.jpeg', '/content/colmap/images/image_115_top.jpeg', '/content/colmap/images/image_115_bottom.jpeg', '/content/colmap/images/image_116_top.jpeg', '/content/colmap/images/image_116_bottom.jpeg', '/content/colmap/images/image_117_top.jpeg', '/content/colmap/images/image_117_bottom.jpeg', '/content/colmap/images/image_118_top.jpeg', '/content/colmap/images/image_118_bottom.jpeg', '/content/colmap/images/image_119_top.jpeg', '/content/colmap/images/image_119_bottom.jpeg', '/content/colmap/images/image_120_top.jpeg', '/content/colmap/images/image_120_bottom.jpeg']) images\n", "============================================================\n", "Step 2: Running COLMAP reconstruction\n", "============================================================\n", "Running SfM reconstruction with COLMAP...\n", "1/4: Extracting features...\n", "2/4: Matching features...\n", "3/4: Sparse reconstruction...\n", "4/4: Exporting to text format...\n", "COLMAP reconstruction complete: /content/colmap/sparse/0\n", "/content/colmap/images\n", "/content/colmap/sparse/0\n", "============================================================\n", "Step 3: Preparing Gaussian Splatting data\n", "============================================================\n", "Preparing data for Gaussian Splatting...\n", "Copying images...\n", "Copied 40 images\n", "Converting camera model to PINHOLE format...\n", "Reading camera file: /content/colmap/sparse/0/cameras.txt\n", "Converted 1 cameras to PINHOLE format\n", "Copied images.txt\n", "Copied points3D.txt\n", "Data preparation complete: /content/mip-splatting/data/video\n", "============================================================\n", "Step 4: Training Gaussian Splatting model\n", "============================================================\n", "Training configuration:\n", " Work dir: /content/mip-splatting\n", " Data dir: /content/mip-splatting/data/video\n", " Model path: /content/mip-splatting/output/video\n", " Command: /usr/bin/python3 train.py -s /content/mip-splatting/data/video -m /content/mip-splatting/output/video --iterations 3000 --eval\n", "\n", "✅ Training completed successfully\n" ] } ], "source": [ "def main_pipeline(image_dir, output_dir,\n", " square_size=1024, max_images=100):\n", " \"\"\"Main execution function\"\"\"\n", " try:\n", " # Step 1: 画像の正規化と前処理\n", " print(\"=\"*60)\n", " print(\"Step 1: Normalizing and preprocessing images\")\n", " print(\"=\"*60)\n", "\n", " frame_dir = os.path.join(COLMAP_DIR, \"images\")\n", " os.makedirs(frame_dir, exist_ok=True)\n", "\n", " # 画像を正規化して直接COLMAPのディレクトリに保存\n", " num_processed = normalize_image_sizes_biplet(\n", " input_dir=image_dir,\n", " output_dir=frame_dir, # 直接colmap/imagesに保存\n", " size=square_size,\n", " max_images=max_images\n", " )\n", "\n", " print(f\"Processed {num_processed} images\")\n", "\n", " # Step 2: Estimate Camera Info with COLMAP\n", " print(\"=\"*60)\n", " print(\"Step 2: Running COLMAP reconstruction\")\n", " print(\"=\"*60)\n", " colmap_model_dir = run_colmap_reconstruction(frame_dir, COLMAP_DIR)\n", "\n", " print(frame_dir)\n", " print(colmap_model_dir)\n", "\n", " # Step 3: Prepare Data for Gaussian Splatting\n", " print(\"=\"*60)\n", " print(\"Step 3: Preparing Gaussian Splatting data\")\n", " print(\"=\"*60)\n", " data_dir = prepare_gaussian_splatting_data(frame_dir, colmap_model_dir)\n", "\n", " # Step 4: Train Model\n", " print(\"=\"*60)\n", " print(\"Step 4: Training Gaussian Splatting model\")\n", " print(\"=\"*60)\n", " model_path = train_gaussian_splatting(\n", " data_dir=data_dir,\n", " work_dir=work_dir, # 明示的に渡す\n", " iterations=3000\n", " )\n", "\n", " return ply_path\n", "\n", " except Exception as e:\n", " print(f\"Error: {str(e)}\")\n", " import traceback\n", " traceback.print_exc()\n", " return None, None\n", "\n", "\n", "\n", "\n", "if __name__ == \"__main__\":\n", " IMAGE_DIR = \"/content/drive/MyDrive/your_folder/fountain100\"\n", " OUTPUT_DIR = \"/content/output\"\n", " COLMAP_DIR = \"/content/colmap\"\n", "\n", " ply_path = main_pipeline(\n", " image_dir=IMAGE_DIR,\n", " output_dir=OUTPUT_DIR,\n", " square_size=1024,\n", " max_images=20\n", " )\n", "\n", "\n" ] }, { "cell_type": "markdown", "id": "e17ec719", "metadata": { "papermill": { "duration": 0.49801, "end_time": "2026-01-11T00:00:18.165833", "exception": false, "start_time": "2026-01-11T00:00:17.667823", "status": "completed" }, "tags": [], "id": "e17ec719" }, "source": [] }, { "cell_type": "markdown", "id": "38b3974c", "metadata": { "papermill": { "duration": 0.427583, "end_time": "2026-01-11T00:00:19.008387", "exception": false, "start_time": "2026-01-11T00:00:18.580804", "status": "completed" }, "tags": [], "id": "38b3974c" }, "source": [] } ], "metadata": { "kaggle": { "accelerator": "nvidiaTeslaT4", "dataSources": [ { "databundleVersionId": 5447706, "sourceId": 49349, "sourceType": "competition" }, { "datasetId": 1429416, "sourceId": 14451718, "sourceType": "datasetVersion" } ], "dockerImageVersionId": 31090, "isGpuEnabled": true, "isInternetEnabled": true, "language": "python", "sourceType": "notebook" }, "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.11.13" }, "papermill": { "default_parameters": {}, "duration": 20573.990788, "end_time": "2026-01-11T00:00:22.081506", "environment_variables": {}, "exception": null, "input_path": "__notebook__.ipynb", "output_path": "__notebook__.ipynb", "parameters": {}, "start_time": "2026-01-10T18:17:28.090718", "version": "2.6.0" }, "colab": { "provenance": [], "gpuType": "T4" }, "accelerator": "GPU" }, "nbformat": 4, "nbformat_minor": 5 }