{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "4755b4ab", "metadata": { "_cell_guid": "8ed69b5e-6ae1-4690-bae7-5846cf3b19c9", "_uuid": "eeb1acde-fd95-42f4-983e-58854c0b2f2a", "collapsed": false, "jupyter": { "outputs_hidden": false }, "papermill": { "duration": 0.003598, "end_time": "2025-12-27T14:06:03.951232", "exception": false, "start_time": "2025-12-27T14:06:03.947634", "status": "completed" }, "tags": [] }, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "de983c5c", "metadata": { "papermill": { "duration": 0.002841, "end_time": "2025-12-27T14:06:03.957224", "exception": false, "start_time": "2025-12-27T14:06:03.954383", "status": "completed" }, "tags": [] }, "source": [ "# **Tetsu28 Frames: CUDA/MPS/CPU Gaussian Splat**" ] }, { "cell_type": "markdown", "id": "48f0f1d3", "metadata": { "papermill": { "duration": 0.002443, "end_time": "2025-12-27T14:06:03.962181", "exception": false, "start_time": "2025-12-27T14:06:03.959738", "status": "completed" }, "tags": [] }, "source": [ "\n", " n_images = 30\n", " unique frames total = 500\n", " exhaustive_matcher\n", " normalize_image_sizes = 1280\n", " iteration = 60\n", " time = 00 min w/cpu\n", " result = " ] }, { "cell_type": "code", "execution_count": 16, "id": "a499b6cb", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Requirement already satisfied: torch in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (2.9.1)\n", "Requirement already satisfied: filelock in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from torch) (3.20.1)\n", "Requirement already satisfied: typing-extensions>=4.10.0 in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from torch) (4.15.0)\n", "Requirement already satisfied: sympy>=1.13.3 in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from torch) (1.14.0)\n", "Requirement already satisfied: networkx>=2.5.1 in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from torch) (3.6.1)\n", "Requirement already satisfied: jinja2 in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from torch) (3.1.6)\n", "Requirement already satisfied: fsspec>=0.8.5 in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from torch) (2025.12.0)\n", "Requirement already satisfied: mpmath<1.4,>=1.1.0 in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from sympy>=1.13.3->torch) (1.3.0)\n", "Requirement already satisfied: MarkupSafe>=2.0 in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from jinja2->torch) (3.0.3)\n", "Note: you may need to restart the kernel to use updated packages.\n", "Requirement already satisfied: opencv-python in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (4.12.0.88)\n", "Requirement already satisfied: numpy<2.3.0,>=2 in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from opencv-python) (2.2.6)\n", "Note: you may need to restart the kernel to use updated packages.\n", "Requirement already satisfied: Pillow in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (12.0.0)\n", "Note: you may need to restart the kernel to use updated packages.\n", "Found existing installation: numpy 2.2.6\n", "Uninstalling numpy-2.2.6:\n", " Successfully uninstalled numpy-2.2.6\n", "Note: you may need to restart the kernel to use updated packages.\n", "Collecting numpy<2.0\n", " Using cached numpy-1.26.4-cp311-cp311-macosx_11_0_arm64.whl.metadata (114 kB)\n", "Using cached numpy-1.26.4-cp311-cp311-macosx_11_0_arm64.whl (14.0 MB)\n", "Installing collected packages: numpy\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", "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.\u001b[0m\u001b[31m\n", "\u001b[0mSuccessfully installed numpy-1.26.4\n", "Note: you may need to restart the kernel to use updated packages.\n" ] } ], "source": [ "%pip install torch\n", "%pip install opencv-python\n", "%pip install Pillow\n", "%pip uninstall -y numpy\n", "%pip install \"numpy<2.0\"" ] }, { "cell_type": "code", "execution_count": 17, "id": "3a32d42b", "metadata": {}, "outputs": [], "source": [ "\n", "\n", "# Global Settings\n", "IMAGE_PATH = \"tetsu28_frames\" # Set path to your image folder, inside WRK_DIR\n", "WORK_DIR = './gaussian_splatting'\n", "OUTPUT_DIR = './output'\n", "COLMAP_DIR = './colmap_data'\n" ] }, { "cell_type": "code", "execution_count": 18, "id": "e5c155b6", "metadata": {}, "outputs": [], "source": [ "import subprocess\n", "import sys\n", "import os\n", "import platform\n", "from pathlib import Path\n", "\n", "WORK_DIR = Path.home() / 'gaussian_splatting'\n", "\n", "def setup_environment():\n", " \"\"\"Install necessary packages and clone the repository (cross-platform)\"\"\"\n", " print(\"Setting up environment...\")\n", " \n", " system = platform.system()\n", " print(f\"Detected operating system: {system}\")\n", " \n", " # Platform-specific setup\n", " if system == \"Linux\":\n", " print(\"Setting up virtual display for Linux...\")\n", " try:\n", " subprocess.run(['apt-get', 'update', '-qq'], check=True)\n", " subprocess.run(['apt-get', 'install', '-y', '-qq', 'xvfb'], check=True)\n", " \n", " os.environ['QT_QPA_PLATFORM'] = 'offscreen'\n", " os.environ['DISPLAY'] = ':99'\n", " subprocess.Popen(['Xvfb', ':99', '-screen', '0', '1024x768x24'])\n", " \n", " print(\"Installing COLMAP...\")\n", " subprocess.run(['apt-get', 'install', '-y', '-qq', 'colmap'], check=True)\n", " \n", " print(\"Installing build dependencies...\")\n", " subprocess.run([\n", " 'apt-get', 'install', '-y', '-qq',\n", " 'build-essential', 'cmake', 'git'\n", " ], check=True)\n", " except FileNotFoundError:\n", " print(\"Warning: apt-get not found.\")\n", " \n", " elif system == \"Darwin\": # macOS\n", " print(\"Running on macOS - CPU/MPS mode\")\n", " \n", " machine = platform.machine()\n", " print(f\"Architecture: {machine}\")\n", " \n", " if machine == \"arm64\":\n", " print(\"✓ Apple Silicon detected - MPS acceleration available\")\n", " else:\n", " print(\"✓ Intel Mac detected - CPU mode\")\n", " \n", " try:\n", " subprocess.run(['brew', '--version'], capture_output=True, check=True)\n", " print(\"✓ Homebrew detected\")\n", " \n", " try:\n", " subprocess.run(['colmap', '--version'], capture_output=True, check=True)\n", " print(\"✓ COLMAP already installed\")\n", " except (FileNotFoundError, subprocess.CalledProcessError):\n", " print(\"Installing COLMAP via Homebrew...\")\n", " subprocess.run(['brew', 'install', 'colmap'], check=True)\n", " \n", " subprocess.run(['xcode-select', '--install'], \n", " capture_output=True, check=False)\n", " \n", " except (FileNotFoundError, subprocess.CalledProcessError):\n", " print(\"Warning: Homebrew not found.\")\n", " \n", " # Clone repository\n", " print(f\"\\nWorking directory: {WORK_DIR}\")\n", " \n", " if not WORK_DIR.exists():\n", " print(\"Cloning Gaussian Splatting repository...\")\n", " WORK_DIR.parent.mkdir(parents=True, exist_ok=True)\n", " subprocess.run([\n", " 'git', 'clone', '--recursive',\n", " 'https://github.com/tztechno/gaussian-splatting.git',\n", " str(WORK_DIR)\n", " ], check=True)\n", " else:\n", " print(f\"Repository already exists at {WORK_DIR}\")\n", " \n", " os.chdir(str(WORK_DIR))\n", " print(f\"Changed directory to: {os.getcwd()}\")\n", " \n", " # Install base packages\n", " print(\"\\nInstalling base Python packages...\")\n", " subprocess.run([\n", " sys.executable, '-m', 'pip', 'install', '--upgrade',\n", " 'pip', 'setuptools', 'wheel', 'ninja'\n", " ], check=True)\n", " \n", " # Install PyTorch\n", " print(\"Installing PyTorch...\")\n", " subprocess.run([\n", " sys.executable, '-m', 'pip', 'install',\n", " 'torch', 'torchvision', 'torchaudio'\n", " ], check=True)\n", " \n", " # Check acceleration availability\n", " import torch\n", " print(f\"\\n✓ PyTorch {torch.__version__} installed\")\n", " \n", " has_cuda = torch.cuda.is_available()\n", " has_mps = torch.backends.mps.is_available() if hasattr(torch.backends, 'mps') else False\n", " \n", " if has_cuda:\n", " device_info = f\"CUDA - {torch.cuda.get_device_name(0)}\"\n", " device_type = \"cuda\"\n", " elif has_mps:\n", " device_info = \"MPS (Apple Metal)\"\n", " device_type = \"mps\"\n", " else:\n", " device_info = \"CPU only\"\n", " device_type = \"cpu\"\n", " \n", " print(f\"✓ Acceleration: {device_info}\")\n", " \n", " # Install other dependencies\n", " print(\"\\nInstalling other dependencies...\")\n", " subprocess.run([\n", " sys.executable, '-m', 'pip', 'install',\n", " 'plyfile', 'tqdm', 'opencv-python', 'pillow'\n", " ], check=True)\n", " \n", " # Handle CUDA extensions\n", " submodule_raster = WORK_DIR / 'submodules' / 'diff-gaussian-rasterization'\n", " submodule_knn = WORK_DIR / 'submodules' / 'simple-knn'\n", " \n", " if has_cuda:\n", " # Full CUDA build\n", " print(\"\\n\" + \"=\"*60)\n", " print(\"Building CUDA extensions (full GPU acceleration)...\")\n", " print(\"=\"*60)\n", " \n", " if submodule_raster.exists():\n", " print(\"\\nBuilding diff-gaussian-rasterization...\")\n", " try:\n", " subprocess.run([\n", " sys.executable, '-m', 'pip', 'install',\n", " '--no-build-isolation',\n", " str(submodule_raster)\n", " ], check=True)\n", " print(\"✓ diff-gaussian-rasterization built\")\n", " except subprocess.CalledProcessError:\n", " print(\"✗ Failed to build diff-gaussian-rasterization\")\n", " \n", " if submodule_knn.exists():\n", " print(\"\\nBuilding simple-knn...\")\n", " try:\n", " subprocess.run([\n", " sys.executable, '-m', 'pip', 'install',\n", " '--no-build-isolation',\n", " str(submodule_knn)\n", " ], check=True)\n", " print(\"✓ simple-knn built\")\n", " except subprocess.CalledProcessError:\n", " print(\"✗ Failed to build simple-knn\")\n", " \n", " else:\n", " # CPU/MPS mode - skip CUDA extensions\n", " print(\"\\n\" + \"=\"*60)\n", " print(\"CPU/MPS Mode - Skipping CUDA extensions\")\n", " print(\"=\"*60)\n", " print(\"\\nThe CUDA-specific extensions won't be built.\")\n", " print(\"The script will run in CPU/MPS mode with reduced performance.\")\n", " print(\"\\nAvailable functionality:\")\n", " print(\" ✓ Data preparation\")\n", " print(\" ✓ COLMAP processing\")\n", " print(\" ✓ Visualization\")\n", " print(\" ✓ Training (slower, CPU/MPS)\")\n", " print(\"\\nLimited functionality:\")\n", " print(\" ⚠ Slower training/inference\")\n", " print(\" ⚠ Some optimizations unavailable\")\n", " print(\"=\"*60)\n", " \n", " # Create a device configuration file\n", " config_file = WORK_DIR / 'device_config.py'\n", " with open(config_file, 'w') as f:\n", " f.write(f\"\"\"# Auto-generated device configuration\n", "import torch\n", "\n", "# Device selection\n", "DEVICE_TYPE = '{device_type}'\n", "HAS_CUDA = {has_cuda}\n", "HAS_MPS = {has_mps}\n", "\n", "def get_device():\n", " \\\"\\\"\\\"Get the best available device\\\"\\\"\\\"\n", " if HAS_CUDA:\n", " return torch.device('cuda')\n", " elif HAS_MPS:\n", " return torch.device('mps')\n", " else:\n", " return torch.device('cpu')\n", "\n", "# Set default device\n", "torch.set_default_device(get_device())\n", "print(f\"Using device: {{get_device()}}\")\n", "\"\"\")\n", " print(f\"\\n✓ Created device config: {config_file}\")\n", " \n", " print(\"\\n\" + \"=\"*60)\n", " print(\"Setup Complete!\")\n", " print(\"=\"*60)\n", " print(f\"Working directory: {WORK_DIR}\")\n", " print(f\"Device: {device_info}\")\n", " print(f\"Mode: {'Full GPU' if has_cuda else 'CPU/MPS (partial)'}\")\n", " print(\"=\"*60)\n", " \n", " if not has_cuda:\n", " print(\"\\n💡 Tip: For faster training, use a cloud platform with CUDA:\")\n", " print(\" • Kaggle Notebooks (free): https://www.kaggle.com/\")\n", " print(\" • Google Colab (free): https://colab.research.google.com/\")" ] }, { "cell_type": "code", "execution_count": 19, "id": "79bbfb5a", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Setting up environment...\n", "Detected operating system: Darwin\n", "Running on macOS - CPU/MPS mode\n", "Architecture: arm64\n", "✓ Apple Silicon detected - MPS acceleration available\n", "✓ Homebrew detected\n", "Installing COLMAP via Homebrew...\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Warning: colmap 3.13.0_3 is already installed and up-to-date.\n", "To reinstall 3.13.0_3, run:\n", " brew reinstall colmap\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Working directory: /Users/shun_ishii/gaussian_splatting\n", "Repository already exists at /Users/shun_ishii/gaussian_splatting\n", "Changed directory to: /Users/shun_ishii/gaussian_splatting\n", "\n", "Installing base Python packages...\n", "Requirement already satisfied: pip in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (25.3)\n", "Requirement already satisfied: setuptools in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (80.9.0)\n", "Requirement already satisfied: wheel in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (0.45.1)\n", "Requirement already satisfied: ninja in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (1.13.0)\n", "Installing PyTorch...\n", "Requirement already satisfied: torch in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (2.9.1)\n", "Requirement already satisfied: torchvision in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (0.24.1)\n", "Requirement already satisfied: torchaudio in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (2.9.1)\n", "Requirement already satisfied: filelock in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from torch) (3.20.1)\n", "Requirement already satisfied: typing-extensions>=4.10.0 in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from torch) (4.15.0)\n", "Requirement already satisfied: sympy>=1.13.3 in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from torch) (1.14.0)\n", "Requirement already satisfied: networkx>=2.5.1 in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from torch) (3.6.1)\n", "Requirement already satisfied: jinja2 in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from torch) (3.1.6)\n", "Requirement already satisfied: fsspec>=0.8.5 in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from torch) (2025.12.0)\n", "Requirement already satisfied: numpy in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from torchvision) (1.26.4)\n", "Requirement already satisfied: pillow!=8.3.*,>=5.3.0 in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from torchvision) (12.0.0)\n", "Requirement already satisfied: mpmath<1.4,>=1.1.0 in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from sympy>=1.13.3->torch) (1.3.0)\n", "Requirement already satisfied: MarkupSafe>=2.0 in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from jinja2->torch) (3.0.3)\n", "\n", "✓ PyTorch 2.9.1 installed\n", "✓ Acceleration: MPS (Apple Metal)\n", "\n", "Installing other dependencies...\n", "Requirement already satisfied: plyfile in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (1.1.3)\n", "Requirement already satisfied: tqdm in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (4.67.1)\n", "Requirement already satisfied: opencv-python in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (4.12.0.88)\n", "Requirement already satisfied: pillow in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (12.0.0)\n", "Requirement already satisfied: numpy>=1.21 in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from plyfile) (1.26.4)\n", "Collecting numpy>=1.21 (from plyfile)\n", " Using cached numpy-2.2.6-cp311-cp311-macosx_14_0_arm64.whl.metadata (62 kB)\n", "Using cached numpy-2.2.6-cp311-cp311-macosx_14_0_arm64.whl (5.4 MB)\n", "Installing collected packages: numpy\n", " Attempting uninstall: numpy\n", " Found existing installation: numpy 1.26.4\n", " Uninstalling numpy-1.26.4:\n", " Successfully uninstalled numpy-1.26.4\n", "Successfully installed numpy-2.2.6\n", "\n", "============================================================\n", "CPU/MPS Mode - Skipping CUDA extensions\n", "============================================================\n", "\n", "The CUDA-specific extensions won't be built.\n", "The script will run in CPU/MPS mode with reduced performance.\n", "\n", "Available functionality:\n", " ✓ Data preparation\n", " ✓ COLMAP processing\n", " ✓ Visualization\n", " ✓ Training (slower, CPU/MPS)\n", "\n", "Limited functionality:\n", " ⚠ Slower training/inference\n", " ⚠ Some optimizations unavailable\n", "============================================================\n", "\n", "✓ Created device config: /Users/shun_ishii/gaussian_splatting/device_config.py\n", "\n", "============================================================\n", "Setup Complete!\n", "============================================================\n", "Working directory: /Users/shun_ishii/gaussian_splatting\n", "Device: MPS (Apple Metal)\n", "Mode: CPU/MPS (partial)\n", "============================================================\n", "\n", "💡 Tip: For faster training, use a cloud platform with CUDA:\n", " • Kaggle Notebooks (free): https://www.kaggle.com/\n", " • Google Colab (free): https://colab.research.google.com/\n" ] } ], "source": [ "setup_environment()" ] }, { "cell_type": "code", "execution_count": 20, "id": "b17d066b", "metadata": { "execution": { "iopub.execute_input": "2025-12-27T14:06:28.227911Z", "iopub.status.busy": "2025-12-27T14:06:28.227522Z", "iopub.status.idle": "2025-12-27T17:30:13.779267Z", "shell.execute_reply": "2025-12-27T17:30:13.775012Z" }, "papermill": { "duration": 12225.570841, "end_time": "2025-12-27T17:30:13.783931", "exception": false, "start_time": "2025-12-27T14:06:28.213090", "status": "completed" }, "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Detected device: mps (Apple Silicon GPU (MPS))\n", "============================================================\n", "Gaussian Splatting Generation (Mac MPS Support)\n", "============================================================\n", "Using Device: mps\n", "============================================================\n", "Setting up environment...\n", "Detected device: mps\n", "NumPy Version: 1.26.4\n", "\n", "======================================================================\n", "Checking System Packages\n", "======================================================================\n", "\n", "Checking COLMAP installation...\n", "✓ COLMAP found: /opt/homebrew/bin/colmap\n", "\n", "======================================================================\n", "Cloning Gaussian Splatting Repository\n", "======================================================================\n", "✓ Repository exists: /Users/shun_ishii/gaussian_splatting\n", "\n", "======================================================================\n", "Installing Python Packages\n", "======================================================================\n", "✓ Installed torch\n", "✓ Installed torchvision\n", "✓ Installed torchaudio\n", "✓ Installed plyfile\n", "✓ Installed tqdm\n", "✓ Installed opencv-python\n", "✓ Installed pillow\n", "✓ Installed imageio\n", "✓ Installed imageio-ffmpeg\n", "✓ Installed tensorboard\n", "\n", "======================================================================\n", "PyTorch Device Verification\n", "======================================================================\n", "PyTorch: 2.9.1\n", "CUDA Available: False\n", "MPS Available: True\n", "Using Device: mps\n", "\n", "Note: Using MPS.\n", "CUDA extensions (diff-gaussian-rasterization) may not work on MPS.\n", "In this case, CPU fallback will be used.\n", "\n", "======================================================================\n", "Building Submodules\n", "======================================================================\n", "\n", "----------------------------------------------------------------------\n", "Building diff-gaussian-rasterization...\n", "----------------------------------------------------------------------\n", "Installing via pip...\n", "⚠ Failed to install diff-gaussian-rasterization\n", " Error: Command '['/Users/shun_ishii/miniconda3/envs/kaggle_local_env/bin/python', '-m', 'pip', 'install', '/Users/shun_ishii/gaussian_splatting/submodules/diff-gaussian-rasterization']' returned non-zero exit status 1.\n", " Note: diff-gaussian-rasterization may not be compatible with MPS\n", "\n", "----------------------------------------------------------------------\n", "Building simple-knn...\n", "----------------------------------------------------------------------\n", "Installing via pip...\n", "⚠ Failed to install simple-knn\n", " Error: Command '['/Users/shun_ishii/miniconda3/envs/kaggle_local_env/bin/python', '-m', 'pip', 'install', '/Users/shun_ishii/gaussian_splatting/submodules/simple-knn']' returned non-zero exit status 1.\n", " Note: simple-knn may not be compatible with MPS\n", "\n", "======================================================================\n", "Final Verification\n", "======================================================================\n", "✗ diff_gaussian_rasterization not found\n", " Note: May not work on MPS. Please use CPU if needed.\n", "✗ simple_knn not found\n", "\n", "======================================================================\n", "⚠⚠⚠ Setup finished with warnings ⚠⚠⚠\n", "Some modules are missing. Training may fail.\n", "Working Directory: /Users/shun_ishii/gaussian_splatting\n", "======================================================================\n", "Resolved relative path to: /Users/shun_ishii/gaussian_splatting/tetsu28_frames\n", "Looking for images in: /Users/shun_ishii/gaussian_splatting/tetsu28_frames\n", "Absolute path: /Users/shun_ishii/gaussian_splatting/tetsu28_frames\n", "Path exists: False\n", "Path doesn't exist. Trying: /Users/shun_ishii/gaussian_splatting/tetsu28_frames\n", "Error: Image folder not found: /Users/shun_ishii/gaussian_splatting/tetsu28_frames\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Traceback (most recent call last):\n", " File \"/var/folders/95/y683rx814wq4p3z5srkkjb7r0000gn/T/ipykernel_67930/2734908124.py\", line 801, in main\n", " process_frames_from_folder(IMAGE_PATH, frame_dir, max_frames=30)\n", " File \"/var/folders/95/y683rx814wq4p3z5srkkjb7r0000gn/T/ipykernel_67930/2734908124.py\", line 307, in process_frames_from_folder\n", " raise ValueError(f\"Image folder not found: {image_folder}\")\n", "ValueError: Image folder not found: /Users/shun_ishii/gaussian_splatting/tetsu28_frames\n" ] } ], "source": [ "import os\n", "import cv2\n", "from PIL import Image\n", "import glob\n", "import numpy as np\n", "import sys\n", "import subprocess\n", "import shutil\n", "from pathlib import Path\n", "import random\n", "import torch\n", "\n", "# ============================================================================\n", "# Device Detection and Setup\n", "# ============================================================================\n", "def detect_device():\n", " \"\"\"Detect available device (CUDA/MPS/CPU)\"\"\"\n", " if torch.cuda.is_available():\n", " device = 'cuda'\n", " device_name = torch.cuda.get_device_name(0)\n", " elif torch.backends.mps.is_available():\n", " device = 'mps'\n", " device_name = 'Apple Silicon GPU (MPS)'\n", " else:\n", " device = 'cpu'\n", " device_name = 'CPU'\n", " \n", " print(f\"Detected device: {device} ({device_name})\")\n", " return device\n", "\n", "\n", "\n", "# Device Detection\n", "DEVICE = detect_device()\n", "USE_GPU = DEVICE in ['cuda', 'mps']\n", "\n", "# Environment variable setup (CUDA only)\n", "if DEVICE == 'cuda':\n", " os.environ['TORCH_CUDA_ARCH_LIST'] = '7.0;7.5;8.0;8.6'\n", " os.environ['FORCE_CUDA'] = '1'\n", "\n", "\n", "# ============================================================================\n", "# Environment Setup Function (MPS Compatible)\n", "# ============================================================================\n", "def setup_environment():\n", " \"\"\"Setup environment (Mac MPS compatible)\"\"\"\n", " print(\"Setting up environment...\")\n", " print(f\"Detected device: {DEVICE}\")\n", " \n", " # ========================================================================\n", " # NumPy Compatibility Check\n", " # ========================================================================\n", " try:\n", " import numpy\n", " numpy_version = numpy.__version__\n", " print(f\"NumPy Version: {numpy_version}\")\n", " \n", " if numpy_version.startswith('2.'):\n", " print(\"Warning: NumPy 2.x detected. Recommend installing 1.x for compatibility.\")\n", " response = input(\"Install NumPy 1.x? (y/n): \")\n", " if response.lower() == 'y':\n", " subprocess.run([sys.executable, '-m', 'pip', 'install', 'numpy<2'], check=True)\n", " print(\"NumPy 1.x installed. Please restart the kernel.\")\n", " except ImportError:\n", " print(\"Installing NumPy...\")\n", " subprocess.run([sys.executable, '-m', 'pip', 'install', 'numpy<2'], check=True)\n", " \n", " # ========================================================================\n", " # System Packages\n", " # ========================================================================\n", " print(\"\\n\" + \"=\"*70)\n", " print(\"Checking System Packages\")\n", " print(\"=\"*70)\n", " \n", " # Check COLMAP installation\n", " print(\"\\nChecking COLMAP installation...\")\n", " colmap_found = False\n", " \n", " try:\n", " result = subprocess.run(['which', 'colmap'], capture_output=True, text=True)\n", " if result.returncode == 0:\n", " colmap_path = result.stdout.strip()\n", " print(f\"✓ COLMAP found: {colmap_path}\")\n", " \n", " # Check version\n", " version_result = subprocess.run(['colmap', '--version'], \n", " capture_output=True, text=True)\n", " if version_result.returncode == 0:\n", " print(f\" Version: {version_result.stdout.strip()}\")\n", " colmap_found = True\n", " else:\n", " print(\"✗ COLMAP not found\")\n", " except Exception as e:\n", " print(f\"✗ COLMAP check error: {e}\")\n", " \n", " if not colmap_found:\n", " print(\"\\n\" + \"=\"*70)\n", " print(\"⚠️ COLMAP installation required\")\n", " print(\"=\"*70)\n", " print(\"\\n[Installation Methods]\")\n", " print(\"\\n1. Mac (Homebrew):\")\n", " print(\" brew install colmap\")\n", " print(\"\\n2. Ubuntu:\")\n", " print(\" sudo apt-get install colmap\")\n", " print(\"\\n3. Conda:\")\n", " print(\" conda install -c conda-forge colmap\")\n", " print(\"\\n4. Build from source:\")\n", " print(\" https://colmap.github.io/install.html\")\n", " print(\"\\n\" + \"=\"*70)\n", " \n", " response = input(\"\\nContinue without COLMAP? (Warning: may fail) (y/n): \")\n", " if response.lower() != 'y':\n", " print(\"Please run again after installing COLMAP.\")\n", " sys.exit(1)\n", " print(\"⚠️ Warning: Proceeding without COLMAP\")\n", " \n", " # ========================================================================\n", " # Clone Repository\n", " # ========================================================================\n", " print(\"\\n\" + \"=\"*70)\n", " print(\"Cloning Gaussian Splatting Repository\")\n", " print(\"=\"*70)\n", " \n", " if not os.path.exists(WORK_DIR):\n", " print(f\"Cloning into {WORK_DIR}...\")\n", " try:\n", " subprocess.run([\n", " 'git', 'clone', '--recursive',\n", " 'https://github.com/graphdeco-inria/gaussian-splatting.git',\n", " WORK_DIR\n", " ], check=True)\n", " print(\"✓ Repository cloned\")\n", " except subprocess.CalledProcessError as e:\n", " print(f\"✗ Clone failed: {e}\")\n", " raise\n", " else:\n", " print(f\"✓ Repository exists: {WORK_DIR}\")\n", " \n", " # ========================================================================\n", " # Install Python Packages\n", " # ========================================================================\n", " print(\"\\n\" + \"=\"*70)\n", " print(\"Installing Python Packages\")\n", " print(\"=\"*70)\n", " \n", " pip_packages = [\n", " 'torch', 'torchvision', 'torchaudio',\n", " 'plyfile', 'tqdm', 'opencv-python', 'pillow',\n", " 'imageio', 'imageio-ffmpeg', 'tensorboard'\n", " ]\n", " \n", " for package in pip_packages:\n", " try:\n", " subprocess.run([\n", " sys.executable, '-m', 'pip', 'install', '-q', package\n", " ], check=True, capture_output=True)\n", " print(f\"✓ Installed {package}\")\n", " except subprocess.CalledProcessError:\n", " print(f\"⚠ Failed to install {package}\")\n", " \n", " # ========================================================================\n", " # Device Verification\n", " # ========================================================================\n", " print(\"\\n\" + \"=\"*70)\n", " print(\"PyTorch Device Verification\")\n", " print(\"=\"*70)\n", " \n", " print(f\"PyTorch: {torch.__version__}\")\n", " print(f\"CUDA Available: {torch.cuda.is_available()}\")\n", " print(f\"MPS Available: {torch.backends.mps.is_available()}\")\n", " print(f\"Using Device: {DEVICE}\")\n", " \n", " if DEVICE == 'mps':\n", " print(\"\\nNote: Using MPS.\")\n", " print(\"CUDA extensions (diff-gaussian-rasterization) may not work on MPS.\")\n", " print(\"In this case, CPU fallback will be used.\")\n", " \n", " # ========================================================================\n", " # Build Submodules (MPS compatible)\n", " # ========================================================================\n", " print(\"\\n\" + \"=\"*70)\n", " print(\"Building Submodules\")\n", " print(\"=\"*70)\n", " \n", " submodules = [\n", " ('diff-gaussian-rasterization',\n", " 'https://github.com/graphdeco-inria/diff-gaussian-rasterization.git'),\n", " ('simple-knn',\n", " 'https://github.com/camenduru/simple-knn.git')\n", " ]\n", " \n", " for submodule_name, fallback_url in submodules:\n", " print(f\"\\n{'-'*70}\")\n", " print(f\"Building {submodule_name}...\")\n", " print(f\"{'-'*70}\")\n", " \n", " submodule_dir = os.path.join(WORK_DIR, 'submodules', submodule_name)\n", " \n", " # Check clone\n", " if not os.path.exists(submodule_dir) or not os.listdir(submodule_dir):\n", " print(f\"Cloning {submodule_name}...\")\n", " try:\n", " subprocess.run(['git', 'clone', fallback_url, submodule_dir], check=True)\n", " print(f\"✓ Cloned {submodule_name}\")\n", " except subprocess.CalledProcessError:\n", " print(f\"✗ Failed to clone {submodule_name}\")\n", " continue\n", " \n", " # Install (Adjust env variables for MPS)\n", " build_env = os.environ.copy()\n", " if DEVICE == 'mps':\n", " build_env.pop('FORCE_CUDA', None)\n", " build_env.pop('TORCH_CUDA_ARCH_LIST', None)\n", " \n", " try:\n", " print(f\"Installing via pip...\")\n", " subprocess.run([\n", " sys.executable, '-m', 'pip', 'install', submodule_dir\n", " ], check=True, capture_output=True, env=build_env)\n", " print(f\"✓ Installed {submodule_name}\")\n", " except subprocess.CalledProcessError as e:\n", " print(f\"⚠ Failed to install {submodule_name}\")\n", " print(f\" Error: {e}\")\n", " if DEVICE == 'mps':\n", " print(f\" Note: {submodule_name} may not be compatible with MPS\")\n", " \n", " # ========================================================================\n", " # Verification\n", " # ========================================================================\n", " print(\"\\n\" + \"=\"*70)\n", " print(\"Final Verification\")\n", " print(\"=\"*70)\n", " \n", " all_good = True\n", " \n", " try:\n", " import diff_gaussian_rasterization\n", " print(\"✓ diff_gaussian_rasterization is available\")\n", " except ImportError:\n", " print(\"✗ diff_gaussian_rasterization not found\")\n", " all_good = False\n", " if DEVICE == 'mps':\n", " print(\" Note: May not work on MPS. Please use CPU if needed.\")\n", " \n", " try:\n", " import simple_knn\n", " print(\"✓ simple_knn is available\")\n", " except ImportError:\n", " print(\"✗ simple_knn not found\")\n", " all_good = False\n", " \n", " print(\"\\n\" + \"=\"*70)\n", " if all_good:\n", " print(\"✓✓✓ Setup Complete - Ready to run ✓✓✓\")\n", " else:\n", " print(\"⚠⚠⚠ Setup finished with warnings ⚠⚠⚠\")\n", " print(\"Some modules are missing. Training may fail.\")\n", " print(f\"Working Directory: {WORK_DIR}\")\n", " print(\"=\"*70)\n", " \n", " return WORK_DIR\n", "\n", "\n", "# ============================================================================\n", "# Frame Processing Functions\n", "# ============================================================================\n", "def adjust_gamma(image, gamma=1.2):\n", " \"\"\"gamma > 1.0 brightens, gamma < 1.0 darkens\"\"\"\n", " invGamma = 1.0 / gamma\n", " table = (np.array([((i / 255.0) ** invGamma) * 255\n", " for i in np.arange(0, 256)])).astype(\"uint8\")\n", " return cv2.LUT(image, table)\n", "\n", "\n", "import os\n", "from pathlib import Path\n", "import glob\n", "\n", "\n", "def process_frames_from_folder(image_folder, output_dir, max_frames=30):\n", " \"\"\"Process frames from a folder with improved path handling\"\"\"\n", " \n", " # Convert to Path object for better handling\n", " if isinstance(image_folder, str):\n", " image_folder = Path(image_folder)\n", " if isinstance(output_dir, str):\n", " output_dir = Path(output_dir)\n", " \n", " # Make image_folder absolute if it's relative\n", " if not image_folder.is_absolute():\n", " # Try relative to current working directory\n", " image_folder = Path.cwd() / image_folder\n", " print(f\"Resolved relative path to: {image_folder}\")\n", " \n", " print(f\"Looking for images in: {image_folder}\")\n", " print(f\"Absolute path: {image_folder.absolute()}\")\n", " print(f\"Path exists: {image_folder.exists()}\")\n", " \n", " if not image_folder.exists():\n", " # Try relative to WORK_DIR\n", " alt_path = WORK_DIR / image_folder.name\n", " print(f\"Path doesn't exist. Trying: {alt_path}\")\n", " if alt_path.exists():\n", " image_folder = alt_path\n", " else:\n", " raise ValueError(f\"Image folder not found: {image_folder}\")\n", " \n", " # List all files in the directory for debugging\n", " if image_folder.exists():\n", " all_files = list(image_folder.iterdir())\n", " print(f\"Found {len(all_files)} total files/folders in directory\")\n", " if all_files:\n", " print(\"First 5 items:\")\n", " for item in all_files[:5]:\n", " print(f\" - {item.name} (is_file: {item.is_file()})\")\n", " \n", " # Look for image files with multiple extensions\n", " image_extensions = ['*.png', '*.jpg', '*.jpeg', '*.PNG', '*.JPG', '*.JPEG']\n", " image_files = []\n", " \n", " for ext in image_extensions:\n", " found = list(image_folder.glob(ext))\n", " image_files.extend(found)\n", " if found:\n", " print(f\"Found {len(found)} {ext} files\")\n", " \n", " # Remove duplicates and sort\n", " image_files = sorted(set(image_files))\n", " \n", " print(f\"\\nTotal image files found: {len(image_files)}\")\n", " \n", " if not image_files:\n", " print(\"\\n\" + \"=\"*60)\n", " print(\"ERROR: No image files found\")\n", " print(\"=\"*60)\n", " print(f\"Searched in: {image_folder}\")\n", " print(f\"Looking for extensions: {image_extensions}\")\n", " print(\"\\nDebugging steps:\")\n", " print(f\"1. Check if folder exists: {image_folder.exists()}\")\n", " print(f\"2. Check folder contents:\")\n", " if image_folder.exists():\n", " for item in image_folder.iterdir():\n", " print(f\" {item.name}\")\n", " print(\"=\"*60)\n", " raise ValueError(f\"No image files found in: {image_folder}\")\n", " \n", " # Show found images\n", " print(f\"\\nFirst few images found:\")\n", " for img in image_files[:5]:\n", " print(f\" - {img.name}\")\n", " if len(image_files) > 5:\n", " print(f\" ... and {len(image_files) - 5} more\")\n", " \n", " # Create output directory\n", " output_dir.mkdir(parents=True, exist_ok=True)\n", " \n", " # Limit number of frames\n", " selected_files = image_files[:max_frames]\n", " print(f\"\\nProcessing {len(selected_files)} frames (max: {max_frames})...\")\n", " \n", " # Copy/process files to output directory\n", " for i, src_file in enumerate(selected_files):\n", " # Create sequential filename\n", " dst_file = output_dir / f\"frame_{i:04d}{src_file.suffix}\"\n", " \n", " # Copy file (or process if needed)\n", " import shutil\n", " shutil.copy2(src_file, dst_file)\n", " \n", " if (i + 1) % 10 == 0:\n", " print(f\"Processed {i + 1}/{len(selected_files)} frames\")\n", " \n", " print(f\"✓ Completed! {len(selected_files)} frames saved to: {output_dir}\")\n", " return output_dir\n", "\n", "\n", "# Example usage in your main function:\n", "def main():\n", " print(\"=\"*70)\n", " print(\"Processing images from folder: tetsu28_frames\")\n", " \n", " # Define paths - use absolute path or ensure correct relative path\n", " IMAGE_PATH = Path('tetsu28_frames') # or use absolute: Path('/full/path/to/tetsu28_frames')\n", " frame_dir = WORK_DIR / 'data' / 'input'\n", " \n", " # Option 1: If images are in current directory\n", " # IMAGE_PATH = Path.cwd() / 'tetsu28_frames'\n", " \n", " # Option 2: If images are in WORK_DIR\n", " # IMAGE_PATH = WORK_DIR / 'tetsu28_frames'\n", " \n", " # Option 3: Absolute path\n", " # IMAGE_PATH = Path('/Users/shun_ishii/path/to/tetsu28_frames')\n", " \n", " try:\n", " process_frames_from_folder(IMAGE_PATH, frame_dir, max_frames=30)\n", " except ValueError as e:\n", " print(f\"\\n❌ Error: {e}\")\n", " print(\"\\n💡 Solutions:\")\n", " print(f\"1. Check if the folder exists: ls -la {IMAGE_PATH}\")\n", " print(f\"2. Use absolute path: IMAGE_PATH = Path('/full/path/to/tetsu28_frames')\")\n", " print(f\"3. Verify PNG files exist: ls {IMAGE_PATH}/*.png\")\n", " print(f\"4. Current working directory: {Path.cwd()}\")\n", " raise\n", "\n", "# ============================================================================\n", "# COLMAP Reconstruction (MPS/CPU compatible)\n", "# ============================================================================\n", "def run_colmap_reconstruction(image_dir, colmap_dir):\n", " \"\"\"SfM reconstruction via COLMAP\"\"\"\n", " print(\"Running COLMAP SfM reconstruction...\")\n", " \n", " # Check for COLMAP command\n", " try:\n", " subprocess.run(['colmap', '--version'], capture_output=True, check=True)\n", " except FileNotFoundError:\n", " print(\"\\n\" + \"=\"*70)\n", " print(\"❌ Error: colmap command not found\")\n", " print(\"=\"*70)\n", " print(\"\\n[Solutions]\")\n", " print(\"\\n1. Mac:\")\n", " print(\" brew install colmap\")\n", " print(\"\\n2. Ubuntu:\")\n", " print(\" sudo apt-get update && sudo apt-get install colmap\")\n", " print(\"\\n3. Conda:\")\n", " print(\" conda install -c conda-forge colmap\")\n", " print(\"\\n4. Build from source:\")\n", " print(\" https://colmap.github.io/install.html\")\n", " print(\"\\nRestart kernel after installation.\")\n", " print(\"=\"*70)\n", " raise RuntimeError(\"COLMAP is not installed\")\n", " except subprocess.CalledProcessError:\n", " print(\"⚠️ Warning: COLMAP encountered an error but will try to continue\")\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", " env = os.environ.copy()\n", " env['QT_QPA_PLATFORM'] = 'offscreen'\n", " \n", " # Use GPU for CUDA, CPU for others (MPS)\n", " use_colmap_gpu = '1' if DEVICE == 'cuda' else '0'\n", " \n", " # Feature Extraction\n", " print(\"1/4: Extracting features...\")\n", " try:\n", " result = 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', use_colmap_gpu\n", " ], capture_output=True, text=True, env=env)\n", " \n", " if result.returncode != 0:\n", " print(f\"❌ Feature extraction error:\")\n", " print(f\"stdout: {result.stdout}\")\n", " print(f\"stderr: {result.stderr}\")\n", " raise subprocess.CalledProcessError(result.returncode, result.args)\n", " \n", " print(f\"✓ Feature extraction complete\")\n", " \n", " if os.path.exists(database_path):\n", " size_mb = os.path.getsize(database_path) / (1024 * 1024)\n", " print(f\" Database size: {size_mb:.2f} MB\")\n", " else:\n", " raise FileNotFoundError(f\"Database file not created: {database_path}\")\n", " \n", " except subprocess.CalledProcessError as e:\n", " print(f\"❌ COLMAP execution error: {e}\")\n", " raise\n", " \n", " # Feature Matching\n", " print(\"2/4: Matching features...\")\n", " try:\n", " result = subprocess.run([\n", " 'colmap', 'exhaustive_matcher',\n", " '--database_path', database_path,\n", " '--SiftMatching.use_gpu', use_colmap_gpu\n", " ], capture_output=True, text=True, env=env)\n", " \n", " if result.returncode != 0:\n", " print(f\"❌ Feature matching error\")\n", " raise subprocess.CalledProcessError(result.returncode, result.args)\n", " \n", " print(f\"✓ Feature matching complete\")\n", " except subprocess.CalledProcessError as e:\n", " print(f\"❌ Feature matching error: {e}\")\n", " raise\n", " \n", " # Sparse Reconstruction\n", " print(\"3/4: Sparse reconstruction...\")\n", " try:\n", " result = 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',\n", " '--Mapper.ba_local_max_num_iterations', '10'\n", " ], capture_output=True, text=True, env=env)\n", " \n", " if result.returncode != 0:\n", " print(f\"❌ Sparse reconstruction error\")\n", " raise subprocess.CalledProcessError(result.returncode, result.args)\n", " \n", " print(f\"✓ Sparse reconstruction complete\")\n", " except subprocess.CalledProcessError as e:\n", " print(f\"❌ Sparse reconstruction error: {e}\")\n", " raise\n", " \n", " # Export as Text\n", " print(\"4/4: Exporting as text format...\")\n", " model_dir = os.path.join(sparse_dir, '0')\n", " if not os.path.exists(model_dir):\n", " subdirs = [d for d in os.listdir(sparse_dir) \n", " 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", " print(f\"❌ Error: Model directory not found\")\n", " raise FileNotFoundError(\"COLMAP reconstruction failed: Model directory not found\")\n", " \n", " try:\n", " result = subprocess.run([\n", " 'colmap', 'model_converter',\n", " '--input_path', model_dir,\n", " '--output_path', model_dir,\n", " '--output_type', 'TXT'\n", " ], capture_output=True, text=True, env=env)\n", " \n", " if result.returncode != 0:\n", " print(f\"❌ Model conversion error\")\n", " raise subprocess.CalledProcessError(result.returncode, result.args)\n", " \n", " print(f\"✓ Export to text complete\")\n", " \n", " required_files = ['cameras.txt', 'images.txt', 'points3D.txt']\n", " for filename in required_files:\n", " filepath = os.path.join(model_dir, filename)\n", " if os.path.exists(filepath):\n", " size_kb = os.path.getsize(filepath) / 1024\n", " print(f\" ✓ {filename}: {size_kb:.2f} KB\")\n", " else:\n", " print(f\" ⚠️ {filename}: Not found\")\n", " \n", " except subprocess.CalledProcessError as e:\n", " print(f\"❌ Model conversion error: {e}\")\n", " raise\n", " \n", " print(f\"✓ COLMAP reconstruction finished: {model_dir}\")\n", " return model_dir\n", "\n", "\n", "# ============================================================================\n", "# Camera Model Conversion\n", "# ============================================================================\n", "def convert_cameras_to_pinhole(input_file, output_file):\n", " \"\"\"Convert camera models 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", " if model == \"PINHOLE\":\n", " f.write(line)\n", " elif model == \"OPENCV\":\n", " fx, fy, cx, cy = params[0], params[1], params[2], params[3]\n", " f.write(f\"{cam_id} PINHOLE {width} {height} {fx} {fy} {cx} {cy}\\n\")\n", " converted_count += 1\n", " else:\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 cameras\n", " print(\"Converting camera models to PINHOLE...\")\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", "# Image Size Normalization\n", "# ============================================================================\n", "def center_crop_and_resize(img, target_size):\n", " \"\"\"Center crop and resize image\"\"\"\n", " width, height = img.size\n", " crop_size = min(width, height)\n", " \n", " left = (width - crop_size) // 2\n", " top = (height - crop_size) // 2\n", " right = left + crop_size\n", " bottom = top + crop_size\n", " \n", " img_cropped = img.crop((left, top, right, bottom))\n", " img_resized = img_cropped.resize((target_size, target_size), Image.Resampling.LANCZOS)\n", " \n", " return img_resized\n", "\n", "\n", "def normalize_image_sizes(image_dir, output_dir=None, target_size=1200):\n", " \"\"\"Normalize image dimensions\"\"\"\n", " if output_dir is None:\n", " output_dir = image_dir\n", " \n", " os.makedirs(output_dir, exist_ok=True)\n", " print(f\"Normalizing image sizes to {target_size}x{target_size}...\")\n", " \n", " converted_count = 0\n", " \n", " for img_file in sorted(os.listdir(image_dir)):\n", " if not img_file.lower().endswith(('.jpg', '.jpeg', '.png')):\n", " continue\n", " \n", " input_path = os.path.join(image_dir, img_file)\n", " output_path = os.path.join(output_dir, img_file)\n", " \n", " try:\n", " img = Image.open(input_path)\n", " original_size = img.size\n", " \n", " img = center_crop_and_resize(img, target_size)\n", " img.save(output_path, quality=95)\n", " converted_count += 1\n", " \n", " print(f\" ✓ {img_file}: {original_size} → {target_size}x{target_size}\")\n", " \n", " except Exception as e:\n", " print(f\" ✗ Error processing {img_file}: {e}\")\n", " \n", " print(f\"\\nConversion complete: {converted_count} images\")\n", " return converted_count\n", "\n", "\n", "# ============================================================================\n", "# Training and Rendering\n", "# ============================================================================\n", "def train_gaussian_splatting(data_dir, iterations=3000):\n", " \"\"\"Train Gaussian Splatting model\"\"\"\n", " print(f\"Training Gaussian Splatting model for {iterations} iterations...\")\n", " \n", " model_path = f\"{WORK_DIR}/output/video\"\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", " subprocess.run(cmd, cwd=WORK_DIR, check=True)\n", " \n", " return model_path\n", "\n", "\n", "def render_video(model_path, output_video_path, iteration=3000):\n", " \"\"\"Render video from trained model\"\"\"\n", " print(\"Rendering video...\")\n", " \n", " cmd = [\n", " sys.executable, 'render.py',\n", " '-m', model_path,\n", " '--iteration', str(iteration)\n", " ]\n", " \n", " subprocess.run(cmd, cwd=WORK_DIR, check=True)\n", " \n", " possible_dirs = [\n", " f\"{model_path}/test/ours_{iteration}/renders\",\n", " f\"{model_path}/train/ours_{iteration}/renders\",\n", " ]\n", " \n", " render_dir = None\n", " for test_dir in possible_dirs:\n", " if os.path.exists(test_dir):\n", " render_dir = test_dir\n", " print(f\"Render directory found: {render_dir}\")\n", " break\n", " \n", " if render_dir and os.path.exists(render_dir):\n", " render_imgs = sorted([f for f in os.listdir(render_dir) if f.endswith('.png')])\n", " \n", " if render_imgs:\n", " print(f\"Found {len(render_imgs)} rendered images\")\n", " \n", " subprocess.run([\n", " 'ffmpeg', '-y',\n", " '-framerate', '30',\n", " '-pattern_type', 'glob',\n", " '-i', f\"{render_dir}/*.png\",\n", " '-c:v', 'libx264',\n", " '-pix_fmt', 'yuv420p',\n", " '-crf', '18',\n", " output_video_path\n", " ], check=True)\n", " \n", " print(f\"Video saved: {output_video_path}\")\n", " return True\n", " \n", " print(\"Error: Render directory not found or no images rendered\")\n", " return False\n", "\n", "\n", "def create_gif(video_path, gif_path):\n", " \"\"\"Create animated GIF from MP4 video\"\"\"\n", " print(\"Creating animated GIF...\")\n", " \n", " subprocess.run([\n", " 'ffmpeg', '-y',\n", " '-i', video_path,\n", " '-vf', 'setpts=8*PTS,fps=10,scale=720:-1:flags=lanczos',\n", " '-loop', '0',\n", " gif_path\n", " ], check=True)\n", " \n", " if os.path.exists(gif_path):\n", " size_mb = os.path.getsize(gif_path) / (1024 * 1024)\n", " print(f\"GIF created: {gif_path} ({size_mb:.2f} MB)\")\n", " return True\n", " \n", " return False\n", "\n", "\n", "# ============================================================================\n", "# Main Execution Function\n", "# ============================================================================\n", "def main():\n", " \"\"\"Main execution flow\"\"\"\n", " print(\"=\"*60)\n", " print(\"Gaussian Splatting Generation (Mac MPS Support)\")\n", " print(\"=\"*60)\n", " print(f\"Using Device: {DEVICE}\")\n", " print(\"=\"*60)\n", " \n", " try:\n", " # Step 1: Environment Setup\n", " setup_environment()\n", " \n", " # Step 2: Frame Extraction\n", " frame_dir = f\"{COLMAP_DIR}/images\"\n", " process_frames_from_folder(IMAGE_PATH, frame_dir, max_frames=30)\n", " \n", " # Step 2.5: Size Normalization\n", " print(\"\\n\" + \"=\"*60)\n", " print(\"Step 2.5: Normalizing image sizes...\")\n", " print(\"=\"*60)\n", " normalize_image_sizes(frame_dir, target_size=1280)\n", " \n", " # Step 3: Estimate Camera Info via COLMAP\n", " colmap_model_dir = run_colmap_reconstruction(frame_dir, COLMAP_DIR)\n", " \n", " # Step 4: Prepare GS Data\n", " data_dir = prepare_gaussian_splatting_data(frame_dir, colmap_model_dir)\n", " \n", " # Step 5: Train Model\n", " # Set low iterations (60) for testing\n", " model_path = train_gaussian_splatting(data_dir, iterations=60)\n", " \n", " # Step 6: Render Video\n", " os.makedirs(OUTPUT_DIR, exist_ok=True)\n", " output_video = f\"{OUTPUT_DIR}/gaussian_splatting_video.mp4\"\n", " success = render_video(model_path, output_video, iteration=60)\n", " \n", " if success:\n", " print(\"=\"*60)\n", " print(f\"Success! Video generation complete: {output_video}\")\n", " print(\"=\"*60)\n", " \n", " # Create GIF\n", " output_gif = f\"{OUTPUT_DIR}/gaussian_splatting_video.gif\"\n", " create_gif(output_video, output_gif)\n", " \n", " print(f\"\\nResult Files:\")\n", " print(f\" Video: {output_video}\")\n", " print(f\" GIF: {output_gif}\")\n", " else:\n", " print(\"Warning: Rendering completed but video was not generated\")\n", " \n", " except Exception as e:\n", " print(f\"Error: {str(e)}\")\n", " import traceback\n", " traceback.print_exc()\n", "\n", "\n", "if __name__ == \"__main__\":\n", " main()" ] }, { "cell_type": "markdown", "id": "55b3bfd0", "metadata": { "papermill": { "duration": 0.021856, "end_time": "2025-12-27T17:30:13.828385", "exception": false, "start_time": "2025-12-27T17:30:13.806529", "status": "completed" }, "tags": [] }, "source": [ "**Please check the result in 3D Gaussian Splat Viewer**\n", "\n", "https://splat-three.vercel.app/?url=tetsu28_frame.splat" ] } ], "metadata": { "kaggle": { "accelerator": "none", "dataSources": [ { "datasetId": 1429416, "sourceId": 14308076, "sourceType": "datasetVersion" } ], "isGpuEnabled": false, "isInternetEnabled": true, "language": "python", "sourceType": "notebook" }, "kernelspec": { "display_name": "kaggle_local_env", "language": "python", "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.14" }, "papermill": { "default_parameters": {}, "duration": 12257.123004, "end_time": "2025-12-27T17:30:15.493589", "environment_variables": {}, "exception": null, "input_path": "__notebook__.ipynb", "output_path": "__notebook__.ipynb", "parameters": {}, "start_time": "2025-12-27T14:05:58.370585", "version": "2.6.0" } }, "nbformat": 4, "nbformat_minor": 5 }