stpete2 commited on
Commit
c5e7640
·
verified ·
1 Parent(s): 32a6cb4

Upload 2 files

Browse files
biplet_colmap_2dgs_colab_07.ipynb ADDED
@@ -0,0 +1,1446 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "fb1f1fdc",
6
+ "metadata": {
7
+ "papermill": {
8
+ "duration": 0.002985,
9
+ "end_time": "2026-01-10T18:17:32.170524",
10
+ "exception": false,
11
+ "start_time": "2026-01-10T18:17:32.167539",
12
+ "status": "completed"
13
+ },
14
+ "tags": [],
15
+ "id": "fb1f1fdc"
16
+ },
17
+ "source": [
18
+ "# **biplet-dino-colmap-2dgs**"
19
+ ]
20
+ },
21
+ {
22
+ "cell_type": "markdown",
23
+ "source": [
24
+ "# 新しいセクション"
25
+ ],
26
+ "metadata": {
27
+ "id": "jK0ja9PfddVA"
28
+ },
29
+ "id": "jK0ja9PfddVA"
30
+ },
31
+ {
32
+ "cell_type": "code",
33
+ "source": [
34
+ "#サイズの異なる画像を扱う\n",
35
+ "from google.colab import drive\n",
36
+ "drive.mount('/content/drive')"
37
+ ],
38
+ "metadata": {
39
+ "colab": {
40
+ "base_uri": "https://localhost:8080/"
41
+ },
42
+ "id": "JON4rYSEOzCg",
43
+ "outputId": "a5bc5ee0-1d0f-409a-d1cb-c4ff57fcb503"
44
+ },
45
+ "id": "JON4rYSEOzCg",
46
+ "execution_count": 14,
47
+ "outputs": [
48
+ {
49
+ "output_type": "stream",
50
+ "name": "stdout",
51
+ "text": [
52
+ "Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\n"
53
+ ]
54
+ }
55
+ ]
56
+ },
57
+ {
58
+ "cell_type": "code",
59
+ "execution_count": 15,
60
+ "id": "22353010",
61
+ "metadata": {
62
+ "execution": {
63
+ "iopub.execute_input": "2026-01-10T18:17:32.181455Z",
64
+ "iopub.status.busy": "2026-01-10T18:17:32.180969Z",
65
+ "iopub.status.idle": "2026-01-10T18:17:32.355942Z",
66
+ "shell.execute_reply": "2026-01-10T18:17:32.355229Z"
67
+ },
68
+ "papermill": {
69
+ "duration": 0.179454,
70
+ "end_time": "2026-01-10T18:17:32.357275",
71
+ "exception": false,
72
+ "start_time": "2026-01-10T18:17:32.177821",
73
+ "status": "completed"
74
+ },
75
+ "tags": [],
76
+ "id": "22353010"
77
+ },
78
+ "outputs": [],
79
+ "source": [
80
+ "import os\n",
81
+ "import sys\n",
82
+ "import subprocess\n",
83
+ "import shutil\n",
84
+ "from pathlib import Path\n",
85
+ "import cv2\n",
86
+ "from PIL import Image\n",
87
+ "import glob\n",
88
+ "\n",
89
+ "IMAGE_PATH=\"/content/drive/MyDrive/your_folder/fountain100\"\n",
90
+ "\n",
91
+ "#WORK_DIR = '/content/gaussian-splatting'\n",
92
+ "WORK_DIR = \"/content/2d-gaussian-splatting\"\n",
93
+ "\n",
94
+ "OUTPUT_DIR = '/content/output'\n",
95
+ "COLMAP_DIR = '/content/colmap_data'"
96
+ ]
97
+ },
98
+ {
99
+ "cell_type": "code",
100
+ "execution_count": 16,
101
+ "id": "be6df249",
102
+ "metadata": {
103
+ "execution": {
104
+ "iopub.execute_input": "2026-01-10T18:17:32.363444Z",
105
+ "iopub.status.busy": "2026-01-10T18:17:32.363175Z",
106
+ "iopub.status.idle": "2026-01-10T18:22:43.720241Z",
107
+ "shell.execute_reply": "2026-01-10T18:22:43.719380Z"
108
+ },
109
+ "papermill": {
110
+ "duration": 311.361656,
111
+ "end_time": "2026-01-10T18:22:43.721610",
112
+ "exception": false,
113
+ "start_time": "2026-01-10T18:17:32.359954",
114
+ "status": "completed"
115
+ },
116
+ "tags": [],
117
+ "id": "be6df249",
118
+ "outputId": "3ffe7863-8698-470a-9240-4bbd2ac964c9",
119
+ "colab": {
120
+ "base_uri": "https://localhost:8080/",
121
+ "height": 1000
122
+ }
123
+ },
124
+ "outputs": [
125
+ {
126
+ "output_type": "stream",
127
+ "name": "stdout",
128
+ "text": [
129
+ "🚀 Setting up COLAB environment (v8 - Python 3.12 compatible)\n",
130
+ "\n",
131
+ "======================================================================\n",
132
+ "STEP 0: Fix NumPy (Python 3.12 compatible)\n",
133
+ "======================================================================\n",
134
+ "Running: /usr/bin/python3 -m pip uninstall -y numpy\n",
135
+ "Running: /usr/bin/python3 -m pip install numpy==1.26.4\n",
136
+ "Running: /usr/bin/python3 -c import numpy; print('NumPy:', numpy.__version__)\n",
137
+ "\n",
138
+ "======================================================================\n",
139
+ "STEP 1: System packages\n",
140
+ "======================================================================\n",
141
+ "Running: apt-get update -qq\n",
142
+ "Running: apt-get install -y -qq colmap build-essential cmake git libopenblas-dev xvfb\n",
143
+ "\n",
144
+ "======================================================================\n",
145
+ "STEP 2: Clone Gaussian Splatting\n",
146
+ "======================================================================\n",
147
+ "✓ Repository already exists\n",
148
+ "\n",
149
+ "======================================================================\n",
150
+ "STEP 3: Python packages (VERBOSE MODE)\n",
151
+ "======================================================================\n",
152
+ "\n",
153
+ "📦 Installing PyTorch...\n",
154
+ "Running: /usr/bin/python3 -m pip install torch torchvision torchaudio\n",
155
+ "\n",
156
+ "📦 Installing core utilities...\n",
157
+ "Running: /usr/bin/python3 -m pip install opencv-python pillow imageio imageio-ffmpeg plyfile tqdm tensorboard\n",
158
+ "\n",
159
+ "📦 Installing transformers (NumPy 1.26 compatible)...\n",
160
+ "Running: /usr/bin/python3 -m pip install transformers==4.40.0\n",
161
+ "\n",
162
+ "📦 Installing LightGlue stack...\n",
163
+ "Running: /usr/bin/python3 -m pip install kornia\n",
164
+ "Running: /usr/bin/python3 -m pip install h5py\n",
165
+ "Running: /usr/bin/python3 -m pip install matplotlib\n",
166
+ "Running: /usr/bin/python3 -m pip install pycolmap\n",
167
+ "\n",
168
+ "======================================================================\n",
169
+ "STEP 4: Detailed Verification\n",
170
+ "======================================================================\n",
171
+ "\n",
172
+ "🔍 Testing NumPy...\n",
173
+ " ✓ NumPy: 2.0.2\n",
174
+ "\n",
175
+ "🔍 Testing PyTorch...\n",
176
+ " ✓ PyTorch: 2.9.0+cu128\n",
177
+ " ✓ CUDA available: True\n",
178
+ " ✓ CUDA version: 12.8\n",
179
+ "\n",
180
+ "🔍 Testing transformers...\n",
181
+ " ✓ transformers version: 4.40.0\n",
182
+ " ✓ AutoModel import: OK\n",
183
+ "\n",
184
+ "🔍 Testing pycolmap...\n",
185
+ " ✓ pycolmap: OK\n",
186
+ "\n",
187
+ "🔍 Testing kornia...\n",
188
+ " ✓ kornia: 0.8.2\n",
189
+ "\n",
190
+ "======================================================================\n",
191
+ "STEP 5: Build Gaussian Splatting submodules\n",
192
+ "======================================================================\n"
193
+ ]
194
+ },
195
+ {
196
+ "output_type": "error",
197
+ "ename": "TypeError",
198
+ "evalue": "tuple indices must be integers or slices, not str",
199
+ "traceback": [
200
+ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
201
+ "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
202
+ "\u001b[0;32m/tmp/ipython-input-1162498108.py\u001b[0m in \u001b[0;36m<cell line: 0>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 239\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 240\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0m__name__\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;34m\"__main__\"\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 241\u001b[0;31m \u001b[0msetup_environment\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
203
+ "\u001b[0;32m/tmp/ipython-input-1162498108.py\u001b[0m in \u001b[0;36msetup_environment\u001b[0;34m()\u001b[0m\n\u001b[1;32m 209\u001b[0m \u001b[0;34m\"url\"\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0;34m\"https://github.com/hbb1/diff-surfel-rasterization.git\"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 210\u001b[0m },\n\u001b[0;32m--> 211\u001b[0;31m \u001b[0mpath\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0msubmodule\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m\"path\"\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 212\u001b[0m \u001b[0murl\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0msubmodule\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m\"url\"\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 213\u001b[0m \u001b[0mname\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mos\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mpath\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mbasename\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mpath\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
204
+ "\u001b[0;31mTypeError\u001b[0m: tuple indices must be integers or slices, not str"
205
+ ]
206
+ }
207
+ ],
208
+ "source": [
209
+ "def run_cmd(cmd, check=True, capture=False, cwd=None): # ← cwd=None を追加\n",
210
+ " \"\"\"Run command with better error handling\"\"\"\n",
211
+ " print(f\"Running: {' '.join(cmd)}\")\n",
212
+ " result = subprocess.run(\n",
213
+ " cmd,\n",
214
+ " capture_output=capture,\n",
215
+ " text=True,\n",
216
+ " check=False,\n",
217
+ " cwd=cwd # ← ここに渡す\n",
218
+ " )\n",
219
+ " if check and result.returncode != 0:\n",
220
+ " print(f\"❌ Command failed with code {result.returncode}\")\n",
221
+ " if capture:\n",
222
+ " print(f\"STDOUT: {result.stdout}\")\n",
223
+ " print(f\"STDERR: {result.stderr}\")\n",
224
+ " return result\n",
225
+ "\n",
226
+ "\n",
227
+ "def setup_environment():\n",
228
+ " \"\"\"\n",
229
+ " Colab environment setup for Gaussian Splatting + LightGlue + pycolmap\n",
230
+ " Python 3.12 compatible version (v8)\n",
231
+ " \"\"\"\n",
232
+ "\n",
233
+ " print(\"🚀 Setting up COLAB environment (v8 - Python 3.12 compatible)\")\n",
234
+ "\n",
235
+ " WORK_DIR = \"2d-gaussian-splatting\"\n",
236
+ "\n",
237
+ " # =====================================================================\n",
238
+ " # STEP 0: NumPy FIX (Python 3.12 compatible)\n",
239
+ " # =====================================================================\n",
240
+ " print(\"\\n\" + \"=\"*70)\n",
241
+ " print(\"STEP 0: Fix NumPy (Python 3.12 compatible)\")\n",
242
+ " print(\"=\"*70)\n",
243
+ "\n",
244
+ " # Python 3.12 requires numpy >= 1.26\n",
245
+ " run_cmd([sys.executable, \"-m\", \"pip\", \"uninstall\", \"-y\", \"numpy\"])\n",
246
+ " run_cmd([sys.executable, \"-m\", \"pip\", \"install\", \"numpy==1.26.4\"])\n",
247
+ "\n",
248
+ " # sanity check\n",
249
+ " run_cmd([sys.executable, \"-c\", \"import numpy; print('NumPy:', numpy.__version__)\"])\n",
250
+ "\n",
251
+ " # =====================================================================\n",
252
+ " # STEP 1: System packages (Colab)\n",
253
+ " # =====================================================================\n",
254
+ " print(\"\\n\" + \"=\"*70)\n",
255
+ " print(\"STEP 1: System packages\")\n",
256
+ " print(\"=\"*70)\n",
257
+ "\n",
258
+ " run_cmd([\"apt-get\", \"update\", \"-qq\"])\n",
259
+ " run_cmd([\n",
260
+ " \"apt-get\", \"install\", \"-y\", \"-qq\",\n",
261
+ " \"colmap\",\n",
262
+ " \"build-essential\",\n",
263
+ " \"cmake\",\n",
264
+ " \"git\",\n",
265
+ " \"libopenblas-dev\",\n",
266
+ " \"xvfb\"\n",
267
+ " ])\n",
268
+ "\n",
269
+ " # virtual display (COLMAP / OpenCV safety)\n",
270
+ " os.environ[\"QT_QPA_PLATFORM\"] = \"offscreen\"\n",
271
+ " os.environ[\"DISPLAY\"] = \":99\"\n",
272
+ " subprocess.Popen(\n",
273
+ " [\"Xvfb\", \":99\", \"-screen\", \"0\", \"1024x768x24\"],\n",
274
+ " stdout=subprocess.DEVNULL,\n",
275
+ " stderr=subprocess.DEVNULL\n",
276
+ " )\n",
277
+ "\n",
278
+ " # =====================================================================\n",
279
+ " # STEP 2: Clone 2D Gaussian Splatting\n",
280
+ " # =====================================================================\n",
281
+ " print(\"\\n\" + \"=\"*70)\n",
282
+ " print(\"STEP 2: Clone Gaussian Splatting\")\n",
283
+ " print(\"=\"*70)\n",
284
+ "\n",
285
+ " if not os.path.exists(WORK_DIR):\n",
286
+ " run_cmd([\n",
287
+ " \"git\", \"clone\", \"--recursive\",\n",
288
+ " \"https://github.com/hbb1/2d-gaussian-splatting.git\",\n",
289
+ " WORK_DIR\n",
290
+ " ])\n",
291
+ " else:\n",
292
+ " print(\"✓ Repository already exists\")\n",
293
+ "\n",
294
+ " # =====================================================================\n",
295
+ " # STEP 3: Python packages (FIXED ORDER & VERSIONS)\n",
296
+ " # =====================================================================\n",
297
+ " print(\"\\n\" + \"=\"*70)\n",
298
+ " print(\"STEP 3: Python packages (VERBOSE MODE)\")\n",
299
+ " print(\"=\"*70)\n",
300
+ "\n",
301
+ " # ---- PyTorch (Colab CUDA対応) ----\n",
302
+ " print(\"\\n📦 Installing PyTorch...\")\n",
303
+ " run_cmd([\n",
304
+ " sys.executable, \"-m\", \"pip\", \"install\",\n",
305
+ " \"torch\", \"torchvision\", \"torchaudio\"\n",
306
+ " ])\n",
307
+ "\n",
308
+ " # ---- Core utils ----\n",
309
+ " print(\"\\n📦 Installing core utilities...\")\n",
310
+ " run_cmd([\n",
311
+ " sys.executable, \"-m\", \"pip\", \"install\",\n",
312
+ " \"opencv-python\",\n",
313
+ " \"pillow\",\n",
314
+ " \"imageio\",\n",
315
+ " \"imageio-ffmpeg\",\n",
316
+ " \"plyfile\",\n",
317
+ " \"tqdm\",\n",
318
+ " \"tensorboard\"\n",
319
+ " ])\n",
320
+ "\n",
321
+ " # ---- transformers (NumPy 1.26 compatible) ----\n",
322
+ " print(\"\\n📦 Installing transformers (NumPy 1.26 compatible)...\")\n",
323
+ " # Install transformers with proper dependencies\n",
324
+ " run_cmd([\n",
325
+ " sys.executable, \"-m\", \"pip\", \"install\",\n",
326
+ " \"transformers==4.40.0\"\n",
327
+ " ])\n",
328
+ "\n",
329
+ " # ---- LightGlue stack (GITHUB INSTALL) ----\n",
330
+ " print(\"\\n📦 Installing LightGlue stack...\")\n",
331
+ "\n",
332
+ " # Install kornia first\n",
333
+ " run_cmd([sys.executable, \"-m\", \"pip\", \"install\", \"kornia\"])\n",
334
+ "\n",
335
+ " # Install h5py (sometimes needed)\n",
336
+ " run_cmd([sys.executable, \"-m\", \"pip\", \"install\", \"h5py\"])\n",
337
+ "\n",
338
+ " # Install matplotlib (LightGlue dependency)\n",
339
+ " run_cmd([sys.executable, \"-m\", \"pip\", \"install\", \"matplotlib\"])\n",
340
+ "\n",
341
+ " # Install pycolmap\n",
342
+ " run_cmd([sys.executable, \"-m\", \"pip\", \"install\", \"pycolmap\"])\n",
343
+ "\n",
344
+ "\n",
345
+ "\n",
346
+ " # =====================================================================\n",
347
+ " # STEP 5: Detailed Verification\n",
348
+ " # =====================================================================\n",
349
+ " print(\"\\n\" + \"=\"*70)\n",
350
+ " print(\"STEP 4: Detailed Verification\")\n",
351
+ " print(\"=\"*70)\n",
352
+ "\n",
353
+ " # NumPy (verify version first)\n",
354
+ " print(\"\\n🔍 Testing NumPy...\")\n",
355
+ " try:\n",
356
+ " import numpy as np\n",
357
+ " print(f\" ✓ NumPy: {np.__version__}\")\n",
358
+ " except Exception as e:\n",
359
+ " print(f\" ❌ NumPy failed: {e}\")\n",
360
+ "\n",
361
+ " # PyTorch\n",
362
+ " print(\"\\n🔍 Testing PyTorch...\")\n",
363
+ " try:\n",
364
+ " import torch\n",
365
+ " print(f\" ✓ PyTorch: {torch.__version__}\")\n",
366
+ " print(f\" ✓ CUDA available: {torch.cuda.is_available()}\")\n",
367
+ " if torch.cuda.is_available():\n",
368
+ " print(f\" ✓ CUDA version: {torch.version.cuda}\")\n",
369
+ " except Exception as e:\n",
370
+ " print(f\" ❌ PyTorch failed: {e}\")\n",
371
+ "\n",
372
+ " # transformers\n",
373
+ " print(\"\\n🔍 Testing transformers...\")\n",
374
+ " try:\n",
375
+ " import transformers\n",
376
+ " print(f\" ✓ transformers version: {transformers.__version__}\")\n",
377
+ " from transformers import AutoModel\n",
378
+ " print(f\" ✓ AutoModel import: OK\")\n",
379
+ " except Exception as e:\n",
380
+ " print(f\" ❌ transformers failed: {e}\")\n",
381
+ " print(f\" Attempting detailed diagnosis...\")\n",
382
+ " result = run_cmd([\n",
383
+ " sys.executable, \"-c\",\n",
384
+ " \"import transformers; print(transformers.__version__)\"\n",
385
+ " ], capture=True)\n",
386
+ " print(f\" Output: {result.stdout}\")\n",
387
+ " print(f\" Error: {result.stderr}\")\n",
388
+ "\n",
389
+ " # pycolmap\n",
390
+ " print(\"\\n🔍 Testing pycolmap...\")\n",
391
+ " try:\n",
392
+ " import pycolmap\n",
393
+ " print(f\" ✓ pycolmap: OK\")\n",
394
+ " except Exception as e:\n",
395
+ " print(f\" ❌ pycolmap failed: {e}\")\n",
396
+ "\n",
397
+ " # kornia\n",
398
+ " print(\"\\n🔍 Testing kornia...\")\n",
399
+ " try:\n",
400
+ " import kornia\n",
401
+ " print(f\" ✓ kornia: {kornia.__version__}\")\n",
402
+ " except Exception as e:\n",
403
+ " print(f\" ❌ kornia failed: {e}\")\n",
404
+ "\n",
405
+ "\n",
406
+ " # =====================================================================\n",
407
+ " # STEP 4: Build 2D GS submodules (確実な方法)\n",
408
+ " # =====================================================================\n",
409
+ " print(\"\\n\" + \"=\"*70)\n",
410
+ " print(\"STEP 5: Build Gaussian Splatting submodules\")\n",
411
+ " print(\"=\"*70)\n",
412
+ "\n",
413
+ " # diff-surfel-rasterization\n",
414
+ "\n",
415
+ " submodule= {\n",
416
+ " \"path\": os.path.join(WORK_DIR, \"submodules\", \"diff-surfel-rasterization\"),\n",
417
+ " \"url\": \"https://github.com/hbb1/diff-surfel-rasterization.git\"\n",
418
+ " },\n",
419
+ " path = submodule[\"path\"]\n",
420
+ " url = submodule[\"url\"]\n",
421
+ " name = os.path.basename(path)\n",
422
+ " print(f\"\\n📦 Processing {name}...\")\n",
423
+ " if not os.path.exists(path):\n",
424
+ " print(f\" > Cloning {url}...\")\n",
425
+ " # 親ディレクトリが存在することを確認\n",
426
+ " os.makedirs(os.path.dirname(path), exist_ok=True)\n",
427
+ " run_cmd([\"git\", \"clone\", url, path])\n",
428
+ " else:\n",
429
+ " print(f\" ✓ {name} already exists.\")\n",
430
+ " # 2. setup.py install (コンパイル)\n",
431
+ " print(f\" > Compiling and Installing {name}...\")\n",
432
+ " result = run_cmd(\n",
433
+ " [sys.executable, \"setup.py\", \"install\"],\n",
434
+ " cwd=path,\n",
435
+ " check=False, # エラーでも止めない\n",
436
+ " capture=True\n",
437
+ " )\n",
438
+ " if result.returncode != 0:\n",
439
+ " print(f\"❌ Failed to build {name}\")\n",
440
+ " print(\"--- STDERR ---\")\n",
441
+ " print(result.stderr)\n",
442
+ " else:\n",
443
+ " print(f\"✅ Successfully built {name}\")\n",
444
+ "\n",
445
+ " return WORK_DIR\n",
446
+ "\n",
447
+ "\n",
448
+ "if __name__ == \"__main__\":\n",
449
+ " setup_environment()"
450
+ ]
451
+ },
452
+ {
453
+ "cell_type": "code",
454
+ "source": [],
455
+ "metadata": {
456
+ "id": "kLdJ-FeT-kQc"
457
+ },
458
+ "id": "kLdJ-FeT-kQc",
459
+ "execution_count": null,
460
+ "outputs": []
461
+ },
462
+ {
463
+ "cell_type": "code",
464
+ "source": [
465
+ "import os\n",
466
+ "import sys\n",
467
+ "import shutil\n",
468
+ "import subprocess\n",
469
+ "\n",
470
+ "# --- 前準備: 環境の整備 ---\n",
471
+ "print(\"Configuring build environment...\")\n",
472
+ "# 1. CUDAコンパイラの確認\n",
473
+ "!nvcc --version\n",
474
+ "\n",
475
+ "# 2. 必須ツールのインストール (ninjaはビルドを安定・高速化させます)\n",
476
+ "!pip install setuptools wheel ninja\n",
477
+ "\n",
478
+ "# 3. 環境変数のセットアップ (CUDAのパスを明示的に指定)\n",
479
+ "os.environ[\"CUDA_HOME\"] = \"/usr/local/cuda\"\n",
480
+ "os.environ[\"PATH\"] = f'{os.environ[\"CUDA_HOME\"]}/bin:{os.environ[\"PATH\"]}'\n",
481
+ "os.environ[\"LD_LIBRARY_PATH\"] = f'{os.environ[\"CUDA_HOME\"]}/lib64:{os.environ[\"LD_LIBRARY_PATH\"]}'\n",
482
+ "# メモリ不足によるクラッシュを防ぐため、並列ビルド数を制限\n",
483
+ "os.environ[\"MAX_JOBS\"] = \"2\"\n",
484
+ "\n",
485
+ "def run_cmd(cmd, cwd=None, check=True):\n",
486
+ " \"\"\"コマンド実行用のヘルパー関数\"\"\"\n",
487
+ " return subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, check=check)\n",
488
+ "\n",
489
+ "def install_submodule(name, url, base_dir):\n",
490
+ " \"\"\"個別のサブモジュールをインストール\"\"\"\n",
491
+ " print(f\"\\n{'='*70}\")\n",
492
+ " print(f\"Installing {name}\")\n",
493
+ " print(f\"{'='*70}\")\n",
494
+ "\n",
495
+ " # 絶対パスを使用\n",
496
+ " path = os.path.abspath(os.path.join(base_dir, \"submodules\", name))\n",
497
+ " print(f\" > Target path: {path}\")\n",
498
+ "\n",
499
+ " # Step 1: 既存を削除\n",
500
+ " if os.path.exists(path):\n",
501
+ " print(f\" > Removing old {name}...\")\n",
502
+ " shutil.rmtree(path)\n",
503
+ "\n",
504
+ " # Step 2: クローン\n",
505
+ " print(f\" > Cloning from {url}...\")\n",
506
+ " os.makedirs(os.path.dirname(path), exist_ok=True)\n",
507
+ " try:\n",
508
+ " run_cmd([\"git\", \"clone\", url, path])\n",
509
+ " except subprocess.CalledProcessError as e:\n",
510
+ " print(f\"❌ Failed to clone {name}\")\n",
511
+ " print(e.stderr)\n",
512
+ " return False\n",
513
+ "\n",
514
+ " # Step 3: ファイル確認 (spatial.cu 等の存在をチェック)\n",
515
+ " print(f\" > Checking cloned files...\")\n",
516
+ " files = os.listdir(path)\n",
517
+ " print(f\" > Files in {name}: {files[:10]}...\")\n",
518
+ "\n",
519
+ " # Step 4: 特定モジュールのサブモジュール初期化\n",
520
+ " if name == \"diff-surfel-rasterization\":\n",
521
+ " print(f\" > Initializing GLM submodule...\")\n",
522
+ " run_cmd([\"git\", \"submodule\", \"update\", \"--init\", \"--recursive\"], cwd=path)\n",
523
+ "\n",
524
+ " # Step 5: ビルドキャッシュ削除\n",
525
+ " build_dir = os.path.join(path, \"build\")\n",
526
+ " if os.path.exists(build_dir):\n",
527
+ " print(f\" > Cleaning build cache...\")\n",
528
+ " shutil.rmtree(build_dir)\n",
529
+ "\n",
530
+ " # Step 6: インストール\n",
531
+ " print(f\" > Installing {name} (This may take a few minutes)...\")\n",
532
+ " # 環境変数を明示的に引き継ぐ\n",
533
+ " current_env = os.environ.copy()\n",
534
+ "\n",
535
+ " result = subprocess.run(\n",
536
+ " [sys.executable, \"-m\", \"pip\", \"install\", \"-e\", \".\", \"--no-build-isolation\", \"-v\"],\n",
537
+ " cwd=path,\n",
538
+ " env=current_env,\n",
539
+ " capture_output=True,\n",
540
+ " text=True\n",
541
+ " )\n",
542
+ "\n",
543
+ " if result.returncode != 0:\n",
544
+ " print(f\"❌ Failed to install {name}\")\n",
545
+ " # C++/CUDAのビルドエラーは stdout に出ることが多いため、両方出力\n",
546
+ " print(\"\\n--- STDOUT (Build Logs) ---\")\n",
547
+ " stdout_lines = result.stdout.split('\\n')\n",
548
+ " print('\\n'.join(stdout_lines[-60:])) # 最後の60行を表示\n",
549
+ "\n",
550
+ " print(\"\\n--- STDERR (Error Details) ---\")\n",
551
+ " print(result.stderr)\n",
552
+ " return False\n",
553
+ "\n",
554
+ " print(f\"✅ Successfully installed {name}\")\n",
555
+ " return True\n",
556
+ "\n",
557
+ "# =====================================================================\n",
558
+ "# STEP 4: Build 2D GS submodules\n",
559
+ "# =====================================================================\n",
560
+ "print(\"\\n\" + \"=\"*70)\n",
561
+ "print(\"STEP 4: Build Gaussian Splatting submodules\")\n",
562
+ "print(\"=\"*70)\n",
563
+ "\n",
564
+ "# Colabの場合は絶対パス\n",
565
+ "WORK_DIR = \"/content/2d-gaussian-splatting\"\n",
566
+ "\n",
567
+ "# 各サブモジュールのインストール\n",
568
+ "# simple-knn\n",
569
+ "success_knn = install_submodule(\n",
570
+ " \"simple-knn\",\n",
571
+ " \"https://github.com/tztechno/simple-knn.git\",\n",
572
+ " WORK_DIR\n",
573
+ ")\n",
574
+ "\n",
575
+ "\n",
576
+ "# 結果表示\n",
577
+ "print(\"\\n\" + \"=\"*70)\n",
578
+ "print(\"Installation Summary\")\n",
579
+ "print(\"=\"*70)\n",
580
+ "print(f\"simple-knn: {'✅ Success' if success_knn else '❌ Failed'}\")"
581
+ ],
582
+ "metadata": {
583
+ "colab": {
584
+ "base_uri": "https://localhost:8080/"
585
+ },
586
+ "id": "qYgJl2Fw_Phk",
587
+ "outputId": "1731e682-22f1-4cf8-dbed-2122a91fc6f3"
588
+ },
589
+ "id": "qYgJl2Fw_Phk",
590
+ "execution_count": 19,
591
+ "outputs": [
592
+ {
593
+ "output_type": "stream",
594
+ "name": "stdout",
595
+ "text": [
596
+ "Configuring build environment...\n",
597
+ "nvcc: NVIDIA (R) Cuda compiler driver\n",
598
+ "Copyright (c) 2005-2025 NVIDIA Corporation\n",
599
+ "Built on Fri_Feb_21_20:23:50_PST_2025\n",
600
+ "Cuda compilation tools, release 12.8, V12.8.93\n",
601
+ "Build cuda_12.8.r12.8/compiler.35583870_0\n",
602
+ "\u001b[33mDEPRECATION: Loading egg at /usr/local/lib/python3.12/dist-packages/diff_surfel_rasterization-0.0.1-py3.12-linux-x86_64.egg is deprecated. pip 24.3 will enforce this behaviour change. A possible replacement is to use pip for package installation. Discussion can be found at https://github.com/pypa/pip/issues/12330\u001b[0m\u001b[33m\n",
603
+ "\u001b[0mRequirement already satisfied: setuptools in /usr/local/lib/python3.12/dist-packages (75.2.0)\n",
604
+ "Requirement already satisfied: wheel in /usr/local/lib/python3.12/dist-packages (0.46.3)\n",
605
+ "Collecting ninja\n",
606
+ " Downloading ninja-1.13.0-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl.metadata (5.1 kB)\n",
607
+ "Requirement already satisfied: packaging>=24.0 in /usr/local/lib/python3.12/dist-packages (from wheel) (26.0)\n",
608
+ "Downloading ninja-1.13.0-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl (180 kB)\n",
609
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m180.7/180.7 kB\u001b[0m \u001b[31m7.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
610
+ "\u001b[?25hInstalling collected packages: ninja\n",
611
+ "Successfully installed ninja-1.13.0\n",
612
+ "\n",
613
+ "======================================================================\n",
614
+ "STEP 4: Build Gaussian Splatting submodules\n",
615
+ "======================================================================\n",
616
+ "\n",
617
+ "======================================================================\n",
618
+ "Installing simple-knn\n",
619
+ "======================================================================\n",
620
+ " > Target path: /content/2d-gaussian-splatting/submodules/simple-knn\n",
621
+ " > Removing old simple-knn...\n",
622
+ " > Cloning from https://github.com/tztechno/simple-knn.git...\n",
623
+ " > Checking cloned files...\n",
624
+ " > Files in simple-knn: ['.git', 'setup.py', 'simple_knn.h', 'simple_knn', 'README.md', 'spatial.h', 'simple_knn0.cu', 'spatial.cu', '.gitignore', 'ext.cpp']...\n",
625
+ " > Installing simple-knn (This may take a few minutes)...\n",
626
+ "✅ Successfully installed simple-knn\n",
627
+ "\n",
628
+ "======================================================================\n",
629
+ "Installation Summary\n",
630
+ "======================================================================\n",
631
+ "simple-knn: ✅ Success\n"
632
+ ]
633
+ }
634
+ ]
635
+ },
636
+ {
637
+ "cell_type": "code",
638
+ "source": [
639
+ "!nvcc --version\n",
640
+ "import torch\n",
641
+ "print(torch.__version__)\n",
642
+ "print(torch.version.cuda)"
643
+ ],
644
+ "metadata": {
645
+ "id": "Ev9PEUdtpEAx"
646
+ },
647
+ "id": "Ev9PEUdtpEAx",
648
+ "execution_count": null,
649
+ "outputs": []
650
+ },
651
+ {
652
+ "cell_type": "code",
653
+ "execution_count": null,
654
+ "id": "b8690389",
655
+ "metadata": {
656
+ "execution": {
657
+ "iopub.execute_input": "2026-01-10T18:22:43.739411Z",
658
+ "iopub.status.busy": "2026-01-10T18:22:43.738855Z",
659
+ "iopub.status.idle": "2026-01-10T18:22:43.755664Z",
660
+ "shell.execute_reply": "2026-01-10T18:22:43.754865Z"
661
+ },
662
+ "papermill": {
663
+ "duration": 0.027297,
664
+ "end_time": "2026-01-10T18:22:43.756758",
665
+ "exception": false,
666
+ "start_time": "2026-01-10T18:22:43.729461",
667
+ "status": "completed"
668
+ },
669
+ "tags": [],
670
+ "id": "b8690389"
671
+ },
672
+ "outputs": [],
673
+ "source": [
674
+ "import os\n",
675
+ "import glob\n",
676
+ "import cv2\n",
677
+ "import numpy as np\n",
678
+ "from PIL import Image\n",
679
+ "\n",
680
+ "# =========================================================\n",
681
+ "# Utility: aspect ratio preserved + black padding\n",
682
+ "# =========================================================\n",
683
+ "\n",
684
+ "def normalize_image_sizes_biplet(input_dir, output_dir=None, size=1024, max_images=None):\n",
685
+ " \"\"\"\n",
686
+ " Generates two square crops (Left & Right or Top & Bottom)\n",
687
+ " from each image in a directory and returns the output directory\n",
688
+ " and the list of generated file paths.\n",
689
+ "\n",
690
+ " Args:\n",
691
+ " input_dir: Input directory containing source images\n",
692
+ " output_dir: Output directory for processed images\n",
693
+ " size: Target square size (default: 1024)\n",
694
+ " max_images: Maximum number of SOURCE images to process (default: None = all images)\n",
695
+ " \"\"\"\n",
696
+ " if output_dir is None:\n",
697
+ " output_dir = 'output/images_biplet'\n",
698
+ " os.makedirs(output_dir, exist_ok=True)\n",
699
+ "\n",
700
+ " print(f\"--- Step 1: Biplet-Square Normalization ---\")\n",
701
+ " print(f\"Generating 2 cropped squares (Left/Right or Top/Bottom) for each image...\")\n",
702
+ " print()\n",
703
+ "\n",
704
+ " generated_paths = []\n",
705
+ " converted_count = 0\n",
706
+ " size_stats = {}\n",
707
+ "\n",
708
+ " # Sort for consistent processing order\n",
709
+ " image_files = sorted([f for f in os.listdir(input_dir)\n",
710
+ " if f.lower().endswith(('.jpg', '.jpeg', '.png'))])\n",
711
+ "\n",
712
+ " # ★ max_images で元画像数を制限\n",
713
+ " if max_images is not None:\n",
714
+ " image_files = image_files[:max_images]\n",
715
+ " print(f\"Processing limited to {max_images} source images (will generate {max_images * 2} cropped images)\")\n",
716
+ "\n",
717
+ " for img_file in image_files:\n",
718
+ " input_path = os.path.join(input_dir, img_file)\n",
719
+ " try:\n",
720
+ " img = Image.open(input_path)\n",
721
+ " original_size = img.size\n",
722
+ "\n",
723
+ " # Tracking original aspect ratios\n",
724
+ " size_key = f\"{original_size[0]}x{original_size[1]}\"\n",
725
+ " size_stats[size_key] = size_stats.get(size_key, 0) + 1\n",
726
+ "\n",
727
+ " # Generate 2 crops using the helper function\n",
728
+ " crops = generate_two_crops(img, size)\n",
729
+ " base_name, ext = os.path.splitext(img_file)\n",
730
+ "\n",
731
+ " for mode, cropped_img in crops.items():\n",
732
+ " output_path = os.path.join(output_dir, f\"{base_name}_{mode}{ext}\")\n",
733
+ " cropped_img.save(output_path, quality=95)\n",
734
+ " generated_paths.append(output_path)\n",
735
+ "\n",
736
+ " converted_count += 1\n",
737
+ " print(f\" ✓ {img_file}: {original_size} → 2 square images generated\")\n",
738
+ "\n",
739
+ " except Exception as e:\n",
740
+ " print(f\" ✗ Error processing {img_file}: {e}\")\n",
741
+ "\n",
742
+ " print(f\"\\nProcessing complete: {converted_count} source images processed\")\n",
743
+ " print(f\"Total output images: {len(generated_paths)}\")\n",
744
+ " print(f\"Original size distribution: {size_stats}\")\n",
745
+ "\n",
746
+ " return output_dir, generated_paths\n",
747
+ "\n",
748
+ "\n",
749
+ "def generate_two_crops(img, size):\n",
750
+ " \"\"\"\n",
751
+ " Crops the image into a square and returns 2 variations\n",
752
+ " (Left/Right for landscape, Top/Bottom for portrait).\n",
753
+ " \"\"\"\n",
754
+ " width, height = img.size\n",
755
+ " crop_size = min(width, height)\n",
756
+ " crops = {}\n",
757
+ "\n",
758
+ " if width > height:\n",
759
+ " # Landscape → Left & Right\n",
760
+ " positions = {\n",
761
+ " 'left': 0,\n",
762
+ " 'right': width - crop_size\n",
763
+ " }\n",
764
+ " for mode, x_offset in positions.items():\n",
765
+ " box = (x_offset, 0, x_offset + crop_size, crop_size)\n",
766
+ " crops[mode] = img.crop(box).resize(\n",
767
+ " (size, size),\n",
768
+ " Image.Resampling.LANCZOS\n",
769
+ " )\n",
770
+ "\n",
771
+ " else:\n",
772
+ " # Portrait or Square → Top & Bottom\n",
773
+ " positions = {\n",
774
+ " 'top': 0,\n",
775
+ " 'bottom': height - crop_size\n",
776
+ " }\n",
777
+ " for mode, y_offset in positions.items():\n",
778
+ " box = (0, y_offset, crop_size, y_offset + crop_size)\n",
779
+ " crops[mode] = img.crop(box).resize(\n",
780
+ " (size, size),\n",
781
+ " Image.Resampling.LANCZOS\n",
782
+ " )\n",
783
+ "\n",
784
+ " return crops\n"
785
+ ]
786
+ },
787
+ {
788
+ "cell_type": "code",
789
+ "execution_count": null,
790
+ "id": "7acc20b6",
791
+ "metadata": {
792
+ "execution": {
793
+ "iopub.execute_input": "2026-01-10T18:22:43.772525Z",
794
+ "iopub.status.busy": "2026-01-10T18:22:43.772303Z",
795
+ "iopub.status.idle": "2026-01-10T18:22:43.790574Z",
796
+ "shell.execute_reply": "2026-01-10T18:22:43.789515Z"
797
+ },
798
+ "papermill": {
799
+ "duration": 0.027612,
800
+ "end_time": "2026-01-10T18:22:43.791681",
801
+ "exception": false,
802
+ "start_time": "2026-01-10T18:22:43.764069",
803
+ "status": "completed"
804
+ },
805
+ "tags": [],
806
+ "id": "7acc20b6"
807
+ },
808
+ "outputs": [],
809
+ "source": [
810
+ "def run_colmap_reconstruction(image_dir, colmap_dir):\n",
811
+ " \"\"\"Estimate camera poses and 3D point cloud with COLMAP\"\"\"\n",
812
+ " print(\"Running SfM reconstruction with COLMAP...\")\n",
813
+ "\n",
814
+ " database_path = os.path.join(colmap_dir, \"database.db\")\n",
815
+ " sparse_dir = os.path.join(colmap_dir, \"sparse\")\n",
816
+ " os.makedirs(sparse_dir, exist_ok=True)\n",
817
+ "\n",
818
+ " # Set environment variable\n",
819
+ " env = os.environ.copy()\n",
820
+ " env['QT_QPA_PLATFORM'] = 'offscreen'\n",
821
+ "\n",
822
+ " # Feature extraction\n",
823
+ " print(\"1/4: Extracting features...\")\n",
824
+ " subprocess.run([\n",
825
+ " 'colmap', 'feature_extractor',\n",
826
+ " '--database_path', database_path,\n",
827
+ " '--image_path', image_dir,\n",
828
+ " '--ImageReader.single_camera', '1',\n",
829
+ " '--ImageReader.camera_model', 'OPENCV',\n",
830
+ " '--SiftExtraction.use_gpu', '0' # Use CPU\n",
831
+ " ], check=True, env=env)\n",
832
+ "\n",
833
+ " # Feature matching\n",
834
+ " print(\"2/4: Matching features...\")\n",
835
+ " subprocess.run([\n",
836
+ " 'colmap', 'exhaustive_matcher', # Use sequential_matcher instead of exhaustive_matcher\n",
837
+ " '--database_path', database_path,\n",
838
+ " '--SiftMatching.use_gpu', '0' # Use CPU\n",
839
+ " ], check=True, env=env)\n",
840
+ "\n",
841
+ " # Sparse reconstruction\n",
842
+ " print(\"3/4: Sparse reconstruction...\")\n",
843
+ " subprocess.run([\n",
844
+ " 'colmap', 'mapper',\n",
845
+ " '--database_path', database_path,\n",
846
+ " '--image_path', image_dir,\n",
847
+ " '--output_path', sparse_dir,\n",
848
+ " '--Mapper.ba_global_max_num_iterations', '20', # Speed up\n",
849
+ " '--Mapper.ba_local_max_num_iterations', '10'\n",
850
+ " ], check=True, env=env)\n",
851
+ "\n",
852
+ " # Export to text format\n",
853
+ " print(\"4/4: Exporting to text format...\")\n",
854
+ " model_dir = os.path.join(sparse_dir, '0')\n",
855
+ " if not os.path.exists(model_dir):\n",
856
+ " # Use the first model found\n",
857
+ " subdirs = [d for d in os.listdir(sparse_dir) if os.path.isdir(os.path.join(sparse_dir, d))]\n",
858
+ " if subdirs:\n",
859
+ " model_dir = os.path.join(sparse_dir, subdirs[0])\n",
860
+ " else:\n",
861
+ " raise FileNotFoundError(\"COLMAP reconstruction failed\")\n",
862
+ "\n",
863
+ " subprocess.run([\n",
864
+ " 'colmap', 'model_converter',\n",
865
+ " '--input_path', model_dir,\n",
866
+ " '--output_path', model_dir,\n",
867
+ " '--output_type', 'TXT'\n",
868
+ " ], check=True, env=env)\n",
869
+ "\n",
870
+ " print(f\"COLMAP reconstruction complete: {model_dir}\")\n",
871
+ " return model_dir\n",
872
+ "\n",
873
+ "\n",
874
+ "def convert_cameras_to_pinhole(input_file, output_file):\n",
875
+ " \"\"\"Convert camera model to PINHOLE format\"\"\"\n",
876
+ " print(f\"Reading camera file: {input_file}\")\n",
877
+ "\n",
878
+ " with open(input_file, 'r') as f:\n",
879
+ " lines = f.readlines()\n",
880
+ "\n",
881
+ " converted_count = 0\n",
882
+ " with open(output_file, 'w') as f:\n",
883
+ " for line in lines:\n",
884
+ " if line.startswith('#') or line.strip() == '':\n",
885
+ " f.write(line)\n",
886
+ " else:\n",
887
+ " parts = line.strip().split()\n",
888
+ " if len(parts) >= 4:\n",
889
+ " cam_id = parts[0]\n",
890
+ " model = parts[1]\n",
891
+ " width = parts[2]\n",
892
+ " height = parts[3]\n",
893
+ " params = parts[4:]\n",
894
+ "\n",
895
+ " # Convert to PINHOLE format\n",
896
+ " if model == \"PINHOLE\":\n",
897
+ " f.write(line)\n",
898
+ " elif model == \"OPENCV\":\n",
899
+ " # OPENCV: fx, fy, cx, cy, k1, k2, p1, p2\n",
900
+ " fx = params[0]\n",
901
+ " fy = params[1]\n",
902
+ " cx = params[2]\n",
903
+ " cy = params[3]\n",
904
+ " f.write(f\"{cam_id} PINHOLE {width} {height} {fx} {fy} {cx} {cy}\\n\")\n",
905
+ " converted_count += 1\n",
906
+ " else:\n",
907
+ " # Convert other models too\n",
908
+ " fx = fy = max(float(width), float(height))\n",
909
+ " cx = float(width) / 2\n",
910
+ " cy = float(height) / 2\n",
911
+ " f.write(f\"{cam_id} PINHOLE {width} {height} {fx} {fy} {cx} {cy}\\n\")\n",
912
+ " converted_count += 1\n",
913
+ " else:\n",
914
+ " f.write(line)\n",
915
+ "\n",
916
+ " print(f\"Converted {converted_count} cameras to PINHOLE format\")\n",
917
+ "\n",
918
+ "\n",
919
+ "def prepare_gaussian_splatting_data(image_dir, colmap_model_dir):\n",
920
+ " \"\"\"Prepare data for Gaussian Splatting\"\"\"\n",
921
+ " print(\"Preparing data for Gaussian Splatting...\")\n",
922
+ "\n",
923
+ " data_dir = f\"{WORK_DIR}/data/video\"\n",
924
+ " os.makedirs(f\"{data_dir}/sparse/0\", exist_ok=True)\n",
925
+ " os.makedirs(f\"{data_dir}/images\", exist_ok=True)\n",
926
+ "\n",
927
+ " # Copy images\n",
928
+ " print(\"Copying images...\")\n",
929
+ " img_count = 0\n",
930
+ " for img_file in os.listdir(image_dir):\n",
931
+ " if img_file.lower().endswith(('.jpg', '.jpeg', '.png')):\n",
932
+ " shutil.copy(\n",
933
+ " os.path.join(image_dir, img_file),\n",
934
+ " f\"{data_dir}/images/{img_file}\"\n",
935
+ " )\n",
936
+ " img_count += 1\n",
937
+ " print(f\"Copied {img_count} images\")\n",
938
+ "\n",
939
+ " # Convert and copy camera file to PINHOLE format\n",
940
+ " print(\"Converting camera model to PINHOLE format...\")\n",
941
+ " convert_cameras_to_pinhole(\n",
942
+ " os.path.join(colmap_model_dir, 'cameras.txt'),\n",
943
+ " f\"{data_dir}/sparse/0/cameras.txt\"\n",
944
+ " )\n",
945
+ "\n",
946
+ " # Copy other files\n",
947
+ " for filename in ['images.txt', 'points3D.txt']:\n",
948
+ " src = os.path.join(colmap_model_dir, filename)\n",
949
+ " dst = f\"{data_dir}/sparse/0/{filename}\"\n",
950
+ " if os.path.exists(src):\n",
951
+ " shutil.copy(src, dst)\n",
952
+ " print(f\"Copied {filename}\")\n",
953
+ " else:\n",
954
+ " print(f\"Warning: {filename} not found\")\n",
955
+ "\n",
956
+ " print(f\"Data preparation complete: {data_dir}\")\n",
957
+ " return data_dir\n",
958
+ "\n",
959
+ "def run_colmap_reconstruction(image_dir, colmap_dir):\n",
960
+ " \"\"\"Estimate camera poses and 3D point cloud with COLMAP\"\"\"\n",
961
+ " print(\"Running SfM reconstruction with COLMAP...\")\n",
962
+ "\n",
963
+ " database_path = os.path.join(colmap_dir, \"database.db\")\n",
964
+ " sparse_dir = os.path.join(colmap_dir, \"sparse\")\n",
965
+ " os.makedirs(sparse_dir, exist_ok=True)\n",
966
+ "\n",
967
+ " # Set environment variable\n",
968
+ " env = os.environ.copy()\n",
969
+ " env['QT_QPA_PLATFORM'] = 'offscreen'\n",
970
+ "\n",
971
+ " # Feature extraction\n",
972
+ " print(\"1/4: Extracting features...\")\n",
973
+ " subprocess.run([\n",
974
+ " 'colmap', 'feature_extractor',\n",
975
+ " '--database_path', database_path,\n",
976
+ " '--image_path', image_dir,\n",
977
+ " '--ImageReader.single_camera', '1',\n",
978
+ " '--ImageReader.camera_model', 'OPENCV',\n",
979
+ " '--SiftExtraction.use_gpu', '0' # Use CPU\n",
980
+ " ], check=True, env=env)\n",
981
+ "\n",
982
+ " # Feature matching\n",
983
+ " print(\"2/4: Matching features...\")\n",
984
+ " subprocess.run([\n",
985
+ " 'colmap', 'exhaustive_matcher', # Use sequential_matcher instead of exhaustive_matcher\n",
986
+ " '--database_path', database_path,\n",
987
+ " '--SiftMatching.use_gpu', '0' # Use CPU\n",
988
+ " ], check=True, env=env)\n",
989
+ "\n",
990
+ " # Sparse reconstruction\n",
991
+ " print(\"3/4: Sparse reconstruction...\")\n",
992
+ " subprocess.run([\n",
993
+ " 'colmap', 'mapper',\n",
994
+ " '--database_path', database_path,\n",
995
+ " '--image_path', image_dir,\n",
996
+ " '--output_path', sparse_dir,\n",
997
+ " '--Mapper.ba_global_max_num_iterations', '20', # Speed up\n",
998
+ " '--Mapper.ba_local_max_num_iterations', '10'\n",
999
+ " ], check=True, env=env)\n",
1000
+ "\n",
1001
+ " # Export to text format\n",
1002
+ " print(\"4/4: Exporting to text format...\")\n",
1003
+ " model_dir = os.path.join(sparse_dir, '0')\n",
1004
+ " if not os.path.exists(model_dir):\n",
1005
+ " # Use the first model found\n",
1006
+ " subdirs = [d for d in os.listdir(sparse_dir) if os.path.isdir(os.path.join(sparse_dir, d))]\n",
1007
+ " if subdirs:\n",
1008
+ " model_dir = os.path.join(sparse_dir, subdirs[0])\n",
1009
+ " else:\n",
1010
+ " raise FileNotFoundError(\"COLMAP reconstruction failed\")\n",
1011
+ "\n",
1012
+ " subprocess.run([\n",
1013
+ " 'colmap', 'model_converter',\n",
1014
+ " '--input_path', model_dir,\n",
1015
+ " '--output_path', model_dir,\n",
1016
+ " '--output_type', 'TXT'\n",
1017
+ " ], check=True, env=env)\n",
1018
+ "\n",
1019
+ " print(f\"COLMAP reconstruction complete: {model_dir}\")\n",
1020
+ " return model_dir\n",
1021
+ "\n",
1022
+ "\n",
1023
+ "def convert_cameras_to_pinhole(input_file, output_file):\n",
1024
+ " \"\"\"Convert camera model to PINHOLE format\"\"\"\n",
1025
+ " print(f\"Reading camera file: {input_file}\")\n",
1026
+ "\n",
1027
+ " with open(input_file, 'r') as f:\n",
1028
+ " lines = f.readlines()\n",
1029
+ "\n",
1030
+ " converted_count = 0\n",
1031
+ " with open(output_file, 'w') as f:\n",
1032
+ " for line in lines:\n",
1033
+ " if line.startswith('#') or line.strip() == '':\n",
1034
+ " f.write(line)\n",
1035
+ " else:\n",
1036
+ " parts = line.strip().split()\n",
1037
+ " if len(parts) >= 4:\n",
1038
+ " cam_id = parts[0]\n",
1039
+ " model = parts[1]\n",
1040
+ " width = parts[2]\n",
1041
+ " height = parts[3]\n",
1042
+ " params = parts[4:]\n",
1043
+ "\n",
1044
+ " # Convert to PINHOLE format\n",
1045
+ " if model == \"PINHOLE\":\n",
1046
+ " f.write(line)\n",
1047
+ " elif model == \"OPENCV\":\n",
1048
+ " # OPENCV: fx, fy, cx, cy, k1, k2, p1, p2\n",
1049
+ " fx = params[0]\n",
1050
+ " fy = params[1]\n",
1051
+ " cx = params[2]\n",
1052
+ " cy = params[3]\n",
1053
+ " f.write(f\"{cam_id} PINHOLE {width} {height} {fx} {fy} {cx} {cy}\\n\")\n",
1054
+ " converted_count += 1\n",
1055
+ " else:\n",
1056
+ " # Convert other models too\n",
1057
+ " fx = fy = max(float(width), float(height))\n",
1058
+ " cx = float(width) / 2\n",
1059
+ " cy = float(height) / 2\n",
1060
+ " f.write(f\"{cam_id} PINHOLE {width} {height} {fx} {fy} {cx} {cy}\\n\")\n",
1061
+ " converted_count += 1\n",
1062
+ " else:\n",
1063
+ " f.write(line)\n",
1064
+ "\n",
1065
+ " print(f\"Converted {converted_count} cameras to PINHOLE format\")\n",
1066
+ "\n",
1067
+ "\n",
1068
+ "def prepare_gaussian_splatting_data(image_dir, colmap_model_dir):\n",
1069
+ " \"\"\"Prepare data for Gaussian Splatting\"\"\"\n",
1070
+ " print(\"Preparing data for Gaussian Splatting...\")\n",
1071
+ "\n",
1072
+ " data_dir = f\"{WORK_DIR}/data/video\"\n",
1073
+ " os.makedirs(f\"{data_dir}/sparse/0\", exist_ok=True)\n",
1074
+ " os.makedirs(f\"{data_dir}/images\", exist_ok=True)\n",
1075
+ "\n",
1076
+ " # Copy images\n",
1077
+ " print(\"Copying images...\")\n",
1078
+ " img_count = 0\n",
1079
+ " for img_file in os.listdir(image_dir):\n",
1080
+ " if img_file.lower().endswith(('.jpg', '.jpeg', '.png')):\n",
1081
+ " shutil.copy(\n",
1082
+ " os.path.join(image_dir, img_file),\n",
1083
+ " f\"{data_dir}/images/{img_file}\"\n",
1084
+ " )\n",
1085
+ " img_count += 1\n",
1086
+ " print(f\"Copied {img_count} images\")\n",
1087
+ "\n",
1088
+ " # Convert and copy camera file to PINHOLE format\n",
1089
+ " print(\"Converting camera model to PINHOLE format...\")\n",
1090
+ " convert_cameras_to_pinhole(\n",
1091
+ " os.path.join(colmap_model_dir, 'cameras.txt'),\n",
1092
+ " f\"{data_dir}/sparse/0/cameras.txt\"\n",
1093
+ " )\n",
1094
+ "\n",
1095
+ " # Copy other files\n",
1096
+ " for filename in ['images.txt', 'points3D.txt']:\n",
1097
+ " src = os.path.join(colmap_model_dir, filename)\n",
1098
+ " dst = f\"{data_dir}/sparse/0/{filename}\"\n",
1099
+ " if os.path.exists(src):\n",
1100
+ " shutil.copy(src, dst)\n",
1101
+ " print(f\"Copied {filename}\")\n",
1102
+ " else:\n",
1103
+ " print(f\"Warning: {filename} not found\")\n",
1104
+ "\n",
1105
+ " print(f\"Data preparation complete: {data_dir}\")\n",
1106
+ " return data_dir\n",
1107
+ "\n",
1108
+ "\n",
1109
+ "\n",
1110
+ "###############################################################\n",
1111
+ "\n",
1112
+ "# 変更後 (2DGS) - 正則化パラメータを追加\n",
1113
+ "def train_gaussian_splatting(data_dir, iterations=7000,\n",
1114
+ " lambda_normal=0.05,\n",
1115
+ " lambda_distortion=0,\n",
1116
+ " depth_ratio=0):\n",
1117
+ " \"\"\"\n",
1118
+ " 2DGS用のトレーニング関数\n",
1119
+ "\n",
1120
+ " Args:\n",
1121
+ " lambda_normal: 法線一貫性の重み (デフォルト: 0.05)\n",
1122
+ " lambda_distortion: 深度歪みの重み (デフォルト: 0)\n",
1123
+ " depth_ratio: 0=平均深度, 1=中央値深度 (デフォルト: 0)\n",
1124
+ " \"\"\"\n",
1125
+ " model_path = f\"{WORK_DIR}/output/video\"\n",
1126
+ " cmd = [\n",
1127
+ " sys.executable, 'train.py',\n",
1128
+ " '-s', data_dir,\n",
1129
+ " '-m', model_path,\n",
1130
+ " '--iterations', str(iterations),\n",
1131
+ " '--lambda_normal', str(lambda_normal),\n",
1132
+ " '--lambda_distortion', str(lambda_distortion),\n",
1133
+ " '--depth_ratio', str(depth_ratio),\n",
1134
+ " '--eval'\n",
1135
+ " ]\n",
1136
+ " subprocess.run(cmd, cwd=WORK_DIR, check=True)\n",
1137
+ " return model_path\n",
1138
+ "\n",
1139
+ "\n",
1140
+ "\n",
1141
+ "# 2DGSではメッシュ抽出オプションが追加されています\n",
1142
+ "def render_video_and_mesh(model_path, output_video_path, iteration=7000,\n",
1143
+ " extract_mesh=True, unbounded=False, mesh_res=1024):\n",
1144
+ " \"\"\"\n",
1145
+ " 2DGS用のレンダリングとメッシュ抽出\n",
1146
+ "\n",
1147
+ " Args:\n",
1148
+ " extract_mesh: メッシュを抽出するか\n",
1149
+ " unbounded: 境界なしメッシュ抽出を使用するか\n",
1150
+ " mesh_res: メッシュ解像度\n",
1151
+ " \"\"\"\n",
1152
+ " # 通常のレンダリング\n",
1153
+ " cmd = [\n",
1154
+ " sys.executable, 'render.py',\n",
1155
+ " '-m', model_path,\n",
1156
+ " '--iteration', str(iteration)\n",
1157
+ " ]\n",
1158
+ "\n",
1159
+ " # メッシュ抽出オプション追加\n",
1160
+ " if extract_mesh:\n",
1161
+ " if unbounded:\n",
1162
+ " cmd.extend(['--unbounded', '--mesh_res', str(mesh_res)])\n",
1163
+ " cmd.extend(['--skip_test', '--skip_train'])\n",
1164
+ "\n",
1165
+ " subprocess.run(cmd, cwd=WORK_DIR, check=True)\n",
1166
+ "\n",
1167
+ " # Find the rendering directory\n",
1168
+ " possible_dirs = [\n",
1169
+ " f\"{model_path}/test/ours_{iteration}/renders\",\n",
1170
+ " f\"{model_path}/train/ours_{iteration}/renders\",\n",
1171
+ " ]\n",
1172
+ "\n",
1173
+ " render_dir = None\n",
1174
+ " for test_dir in possible_dirs:\n",
1175
+ " if os.path.exists(test_dir):\n",
1176
+ " render_dir = test_dir\n",
1177
+ " print(f\"Rendering directory found: {render_dir}\")\n",
1178
+ " break\n",
1179
+ "\n",
1180
+ " if render_dir and os.path.exists(render_dir):\n",
1181
+ " render_imgs = sorted([f for f in os.listdir(render_dir) if f.endswith('.png')])\n",
1182
+ "\n",
1183
+ " if render_imgs:\n",
1184
+ " print(f\"Found {len(render_imgs)} rendered images\")\n",
1185
+ "\n",
1186
+ " # Create video with ffmpeg\n",
1187
+ " subprocess.run([\n",
1188
+ " 'ffmpeg', '-y',\n",
1189
+ " '-framerate', '30',\n",
1190
+ " '-pattern_type', 'glob',\n",
1191
+ " '-i', f\"{render_dir}/*.png\",\n",
1192
+ " '-c:v', 'libx264',\n",
1193
+ " '-pix_fmt', 'yuv420p',\n",
1194
+ " '-crf', '18',\n",
1195
+ " output_video_path\n",
1196
+ " ], check=True)\n",
1197
+ "\n",
1198
+ " print(f\"Video saved: {output_video_path}\")\n",
1199
+ " return True\n",
1200
+ "\n",
1201
+ " print(\"Error: Rendering directory not found\")\n",
1202
+ " return False\n",
1203
+ "\n",
1204
+ "###############################################################\n",
1205
+ "\n",
1206
+ "\n",
1207
+ "def create_gif(video_path, gif_path):\n",
1208
+ " \"\"\"Create GIF from MP4\"\"\"\n",
1209
+ " print(\"Creating animated GIF...\")\n",
1210
+ "\n",
1211
+ " subprocess.run([\n",
1212
+ " 'ffmpeg', '-y',\n",
1213
+ " '-i', video_path,\n",
1214
+ " '-vf', 'setpts=8*PTS,fps=10,scale=720:-1:flags=lanczos',\n",
1215
+ " '-loop', '0',\n",
1216
+ " gif_path\n",
1217
+ " ], check=True)\n",
1218
+ "\n",
1219
+ " if os.path.exists(gif_path):\n",
1220
+ " size_mb = os.path.getsize(gif_path) / (1024 * 1024)\n",
1221
+ " print(f\"GIF creation complete: {gif_path} ({size_mb:.2f} MB)\")\n",
1222
+ " return True\n",
1223
+ "\n",
1224
+ " return False"
1225
+ ]
1226
+ },
1227
+ {
1228
+ "cell_type": "code",
1229
+ "source": [],
1230
+ "metadata": {
1231
+ "id": "YtqhBP4T3jEH"
1232
+ },
1233
+ "id": "YtqhBP4T3jEH",
1234
+ "execution_count": null,
1235
+ "outputs": []
1236
+ },
1237
+ {
1238
+ "cell_type": "code",
1239
+ "source": [
1240
+ "def main_pipeline(image_dir, output_dir, square_size=1024, max_images=100):\n",
1241
+ " \"\"\"Main execution function\"\"\"\n",
1242
+ " try:\n",
1243
+ " # Step 1: 画像の正規化と前処理\n",
1244
+ " print(\"=\"*60)\n",
1245
+ " print(\"Step 1: Normalizing and preprocessing images\")\n",
1246
+ " print(\"=\"*60)\n",
1247
+ "\n",
1248
+ " frame_dir = os.path.join(COLMAP_DIR, \"images\")\n",
1249
+ " os.makedirs(frame_dir, exist_ok=True)\n",
1250
+ "\n",
1251
+ " # 画像を正規化して直接COLMAPのディレクトリに保存\n",
1252
+ " num_processed = normalize_image_sizes_biplet(\n",
1253
+ " input_dir=image_dir,\n",
1254
+ " output_dir=frame_dir, # 直接colmap/imagesに保存\n",
1255
+ " size=square_size,\n",
1256
+ " max_images=max_images\n",
1257
+ " )\n",
1258
+ "\n",
1259
+ " print(f\"Processed {num_processed} images\")\n",
1260
+ "\n",
1261
+ " # Step 2: Estimate Camera Info with COLMAP\n",
1262
+ " print(\"=\"*60)\n",
1263
+ " print(\"Step 2: Running COLMAP reconstruction\")\n",
1264
+ " print(\"=\"*60)\n",
1265
+ " colmap_model_dir = run_colmap_reconstruction(frame_dir, COLMAP_DIR)\n",
1266
+ "\n",
1267
+ " # Step 3: Prepare Data for Gaussian Splatting\n",
1268
+ " print(\"=\"*60)\n",
1269
+ " print(\"Step 3: Preparing Gaussian Splatting data\")\n",
1270
+ " print(\"=\"*60)\n",
1271
+ " data_dir = prepare_gaussian_splatting_data(frame_dir, colmap_model_dir)\n",
1272
+ "\n",
1273
+ " # Step 4: Train Model\n",
1274
+ " print(\"=\"*60)\n",
1275
+ " print(\"Step 4: Training Gaussian Splatting model\")\n",
1276
+ " print(\"=\"*60)\n",
1277
+ " # 修正: frame_dir → data_dir\n",
1278
+ " model_path = train_gaussian_splatting(\n",
1279
+ " data_dir, # ← ここを修正!\n",
1280
+ " iterations=1000,\n",
1281
+ " lambda_normal=0.05,\n",
1282
+ " lambda_distortion=0,\n",
1283
+ " depth_ratio=0\n",
1284
+ " )\n",
1285
+ "\n",
1286
+ " print(f\"Model trained at: {model_path}\")\n",
1287
+ "\n",
1288
+ " # Step 5: Render Video\n",
1289
+ " print(\"=\"*60)\n",
1290
+ " print(\"Step 5: Rendering video\")\n",
1291
+ " print(\"=\"*60)\n",
1292
+ " os.makedirs(OUTPUT_DIR, exist_ok=True)\n",
1293
+ " output_video = os.path.join(OUTPUT_DIR, \"gaussian_splatting_video.mp4\")\n",
1294
+ "\n",
1295
+ " # 修正: output_video_path → output_video\n",
1296
+ " success = render_video_and_mesh(\n",
1297
+ " model_path,\n",
1298
+ " output_video, # ← ここを修正!\n",
1299
+ " iteration=1000,\n",
1300
+ " extract_mesh=True, # メッシュ抽出を有効化\n",
1301
+ " unbounded=True, # 境界なしメッシュ(推奨)\n",
1302
+ " mesh_res=1024\n",
1303
+ " )\n",
1304
+ "\n",
1305
+ " if success:\n",
1306
+ " print(\"=\"*60)\n",
1307
+ " print(f\"Success! Video generation complete: {output_video}\")\n",
1308
+ " print(\"=\"*60)\n",
1309
+ "\n",
1310
+ " # Create GIF\n",
1311
+ " output_gif = os.path.join(OUTPUT_DIR, \"gaussian_splatting_video.gif\")\n",
1312
+ " create_gif(output_video, output_gif)\n",
1313
+ "\n",
1314
+ " # Display result\n",
1315
+ " from IPython.display import Image, display\n",
1316
+ " display(Image(open(output_gif, 'rb').read()))\n",
1317
+ "\n",
1318
+ " return output_video, output_gif\n",
1319
+ " else:\n",
1320
+ " print(\"Warning: Rendering complete, but video was not generated\")\n",
1321
+ " return None, None\n",
1322
+ "\n",
1323
+ " except Exception as e:\n",
1324
+ " print(f\"Error: {str(e)}\")\n",
1325
+ " import traceback\n",
1326
+ " traceback.print_exc()\n",
1327
+ " return None, None\n",
1328
+ "\n",
1329
+ "\n",
1330
+ "if __name__ == \"__main__\":\n",
1331
+ " IMAGE_DIR = \"/content/drive/MyDrive/your_folder/fountain100\"\n",
1332
+ " OUTPUT_DIR = \"/content/output\"\n",
1333
+ " COLMAP_DIR = \"/content/colmap_workspace\"\n",
1334
+ "\n",
1335
+ " video_path, gif_path = main_pipeline(\n",
1336
+ " image_dir=IMAGE_DIR,\n",
1337
+ " output_dir=OUTPUT_DIR,\n",
1338
+ " square_size=1024,\n",
1339
+ " max_images=20\n",
1340
+ " )\n",
1341
+ "\n",
1342
+ " if video_path:\n",
1343
+ " print(f\"\\n✅ Success!\")\n",
1344
+ " print(f\"Video: {video_path}\")\n",
1345
+ " print(f\"GIF: {gif_path}\")\n",
1346
+ " else:\n",
1347
+ " print(\"\\n❌ Pipeline failed\")"
1348
+ ],
1349
+ "metadata": {
1350
+ "id": "fya3kv62NXM-"
1351
+ },
1352
+ "id": "fya3kv62NXM-",
1353
+ "execution_count": null,
1354
+ "outputs": []
1355
+ },
1356
+ {
1357
+ "cell_type": "markdown",
1358
+ "id": "e17ec719",
1359
+ "metadata": {
1360
+ "papermill": {
1361
+ "duration": 0.49801,
1362
+ "end_time": "2026-01-11T00:00:18.165833",
1363
+ "exception": false,
1364
+ "start_time": "2026-01-11T00:00:17.667823",
1365
+ "status": "completed"
1366
+ },
1367
+ "tags": [],
1368
+ "id": "e17ec719"
1369
+ },
1370
+ "source": []
1371
+ },
1372
+ {
1373
+ "cell_type": "markdown",
1374
+ "id": "38b3974c",
1375
+ "metadata": {
1376
+ "papermill": {
1377
+ "duration": 0.427583,
1378
+ "end_time": "2026-01-11T00:00:19.008387",
1379
+ "exception": false,
1380
+ "start_time": "2026-01-11T00:00:18.580804",
1381
+ "status": "completed"
1382
+ },
1383
+ "tags": [],
1384
+ "id": "38b3974c"
1385
+ },
1386
+ "source": []
1387
+ }
1388
+ ],
1389
+ "metadata": {
1390
+ "kaggle": {
1391
+ "accelerator": "nvidiaTeslaT4",
1392
+ "dataSources": [
1393
+ {
1394
+ "databundleVersionId": 5447706,
1395
+ "sourceId": 49349,
1396
+ "sourceType": "competition"
1397
+ },
1398
+ {
1399
+ "datasetId": 1429416,
1400
+ "sourceId": 14451718,
1401
+ "sourceType": "datasetVersion"
1402
+ }
1403
+ ],
1404
+ "dockerImageVersionId": 31090,
1405
+ "isGpuEnabled": true,
1406
+ "isInternetEnabled": true,
1407
+ "language": "python",
1408
+ "sourceType": "notebook"
1409
+ },
1410
+ "kernelspec": {
1411
+ "display_name": "Python 3",
1412
+ "name": "python3"
1413
+ },
1414
+ "language_info": {
1415
+ "codemirror_mode": {
1416
+ "name": "ipython",
1417
+ "version": 3
1418
+ },
1419
+ "file_extension": ".py",
1420
+ "mimetype": "text/x-python",
1421
+ "name": "python",
1422
+ "nbconvert_exporter": "python",
1423
+ "pygments_lexer": "ipython3",
1424
+ "version": "3.11.13"
1425
+ },
1426
+ "papermill": {
1427
+ "default_parameters": {},
1428
+ "duration": 20573.990788,
1429
+ "end_time": "2026-01-11T00:00:22.081506",
1430
+ "environment_variables": {},
1431
+ "exception": null,
1432
+ "input_path": "__notebook__.ipynb",
1433
+ "output_path": "__notebook__.ipynb",
1434
+ "parameters": {},
1435
+ "start_time": "2026-01-10T18:17:28.090718",
1436
+ "version": "2.6.0"
1437
+ },
1438
+ "colab": {
1439
+ "provenance": [],
1440
+ "gpuType": "T4"
1441
+ },
1442
+ "accelerator": "GPU"
1443
+ },
1444
+ "nbformat": 4,
1445
+ "nbformat_minor": 5
1446
+ }
biplet_colmap_2dgs_colab_08.ipynb ADDED
@@ -0,0 +1,1424 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "fb1f1fdc",
6
+ "metadata": {
7
+ "papermill": {
8
+ "duration": 0.002985,
9
+ "end_time": "2026-01-10T18:17:32.170524",
10
+ "exception": false,
11
+ "start_time": "2026-01-10T18:17:32.167539",
12
+ "status": "completed"
13
+ },
14
+ "tags": [],
15
+ "id": "fb1f1fdc"
16
+ },
17
+ "source": [
18
+ "# **biplet-dino-colmap-2dgs**"
19
+ ]
20
+ },
21
+ {
22
+ "cell_type": "markdown",
23
+ "source": [
24
+ "# 新しいセクション"
25
+ ],
26
+ "metadata": {
27
+ "id": "jK0ja9PfddVA"
28
+ },
29
+ "id": "jK0ja9PfddVA"
30
+ },
31
+ {
32
+ "cell_type": "code",
33
+ "source": [
34
+ "#サイズの異なる画像を扱う\n",
35
+ "from google.colab import drive\n",
36
+ "drive.mount('/content/drive')"
37
+ ],
38
+ "metadata": {
39
+ "colab": {
40
+ "base_uri": "https://localhost:8080/"
41
+ },
42
+ "id": "JON4rYSEOzCg",
43
+ "outputId": "2d88feb8-d071-4109-a0a3-64f4d8a46e9c"
44
+ },
45
+ "id": "JON4rYSEOzCg",
46
+ "execution_count": 1,
47
+ "outputs": [
48
+ {
49
+ "output_type": "stream",
50
+ "name": "stdout",
51
+ "text": [
52
+ "Mounted at /content/drive\n"
53
+ ]
54
+ }
55
+ ]
56
+ },
57
+ {
58
+ "cell_type": "code",
59
+ "execution_count": 2,
60
+ "id": "22353010",
61
+ "metadata": {
62
+ "execution": {
63
+ "iopub.execute_input": "2026-01-10T18:17:32.181455Z",
64
+ "iopub.status.busy": "2026-01-10T18:17:32.180969Z",
65
+ "iopub.status.idle": "2026-01-10T18:17:32.355942Z",
66
+ "shell.execute_reply": "2026-01-10T18:17:32.355229Z"
67
+ },
68
+ "papermill": {
69
+ "duration": 0.179454,
70
+ "end_time": "2026-01-10T18:17:32.357275",
71
+ "exception": false,
72
+ "start_time": "2026-01-10T18:17:32.177821",
73
+ "status": "completed"
74
+ },
75
+ "tags": [],
76
+ "id": "22353010"
77
+ },
78
+ "outputs": [],
79
+ "source": [
80
+ "import os\n",
81
+ "import sys\n",
82
+ "import subprocess\n",
83
+ "import shutil\n",
84
+ "from pathlib import Path\n",
85
+ "import cv2\n",
86
+ "from PIL import Image\n",
87
+ "import glob\n",
88
+ "\n",
89
+ "IMAGE_PATH=\"/content/drive/MyDrive/your_folder/fountain100\"\n",
90
+ "\n",
91
+ "#WORK_DIR = '/content/gaussian-splatting'\n",
92
+ "WORK_DIR = \"/content/2d-gaussian-splatting\"\n",
93
+ "\n",
94
+ "OUTPUT_DIR = '/content/output'\n",
95
+ "COLMAP_DIR = '/content/colmap_data'"
96
+ ]
97
+ },
98
+ {
99
+ "cell_type": "code",
100
+ "execution_count": 4,
101
+ "id": "be6df249",
102
+ "metadata": {
103
+ "execution": {
104
+ "iopub.execute_input": "2026-01-10T18:17:32.363444Z",
105
+ "iopub.status.busy": "2026-01-10T18:17:32.363175Z",
106
+ "iopub.status.idle": "2026-01-10T18:22:43.720241Z",
107
+ "shell.execute_reply": "2026-01-10T18:22:43.719380Z"
108
+ },
109
+ "papermill": {
110
+ "duration": 311.361656,
111
+ "end_time": "2026-01-10T18:22:43.721610",
112
+ "exception": false,
113
+ "start_time": "2026-01-10T18:17:32.359954",
114
+ "status": "completed"
115
+ },
116
+ "tags": [],
117
+ "id": "be6df249",
118
+ "outputId": "93eb3ae2-21fe-4b58-9202-469cd3a1a3ba",
119
+ "colab": {
120
+ "base_uri": "https://localhost:8080/"
121
+ }
122
+ },
123
+ "outputs": [
124
+ {
125
+ "output_type": "stream",
126
+ "name": "stdout",
127
+ "text": [
128
+ "🚀 Setting up COLAB environment (v8 - Python 3.12 compatible)\n",
129
+ "\n",
130
+ "======================================================================\n",
131
+ "STEP 0: Fix NumPy (Python 3.12 compatible)\n",
132
+ "======================================================================\n",
133
+ "Running: /usr/bin/python3 -m pip uninstall -y numpy\n",
134
+ "Running: /usr/bin/python3 -m pip install numpy==1.26.4\n",
135
+ "Running: /usr/bin/python3 -c import numpy; print('NumPy:', numpy.__version__)\n",
136
+ "\n",
137
+ "======================================================================\n",
138
+ "STEP 1: System packages\n",
139
+ "======================================================================\n",
140
+ "Running: apt-get update -qq\n",
141
+ "Running: apt-get install -y -qq colmap build-essential cmake git libopenblas-dev xvfb\n",
142
+ "\n",
143
+ "======================================================================\n",
144
+ "STEP 2: Clone Gaussian Splatting\n",
145
+ "======================================================================\n",
146
+ "✓ Repository already exists\n",
147
+ "\n",
148
+ "======================================================================\n",
149
+ "STEP 3: Python packages (VERBOSE MODE)\n",
150
+ "======================================================================\n",
151
+ "\n",
152
+ "📦 Installing PyTorch...\n",
153
+ "Running: /usr/bin/python3 -m pip install torch torchvision torchaudio\n",
154
+ "\n",
155
+ "📦 Installing core utilities...\n",
156
+ "Running: /usr/bin/python3 -m pip install opencv-python pillow imageio imageio-ffmpeg plyfile tqdm tensorboard\n",
157
+ "\n",
158
+ "📦 Installing transformers (NumPy 1.26 compatible)...\n",
159
+ "Running: /usr/bin/python3 -m pip install transformers==4.40.0\n",
160
+ "\n",
161
+ "📦 Installing LightGlue stack...\n",
162
+ "Running: /usr/bin/python3 -m pip install kornia\n",
163
+ "Running: /usr/bin/python3 -m pip install h5py\n",
164
+ "Running: /usr/bin/python3 -m pip install matplotlib\n",
165
+ "Running: /usr/bin/python3 -m pip install pycolmap\n",
166
+ "\n",
167
+ "======================================================================\n",
168
+ "STEP 4: Detailed Verification\n",
169
+ "======================================================================\n",
170
+ "\n",
171
+ "🔍 Testing NumPy...\n",
172
+ " ✓ NumPy: 2.0.2\n",
173
+ "\n",
174
+ "🔍 Testing PyTorch...\n",
175
+ " ✓ PyTorch: 2.9.0+cu128\n",
176
+ " ✓ CUDA available: True\n",
177
+ " ✓ CUDA version: 12.8\n",
178
+ "\n",
179
+ "🔍 Testing transformers...\n",
180
+ " ✓ transformers version: 4.40.0\n",
181
+ " ✓ AutoModel import: OK\n",
182
+ "\n",
183
+ "🔍 Testing pycolmap...\n",
184
+ " ✓ pycolmap: OK\n",
185
+ "\n",
186
+ "🔍 Testing kornia...\n",
187
+ " ✓ kornia: 0.8.2\n"
188
+ ]
189
+ }
190
+ ],
191
+ "source": [
192
+ "def run_cmd(cmd, check=True, capture=False, cwd=None): # ← cwd=None を追加\n",
193
+ " \"\"\"Run command with better error handling\"\"\"\n",
194
+ " print(f\"Running: {' '.join(cmd)}\")\n",
195
+ " result = subprocess.run(\n",
196
+ " cmd,\n",
197
+ " capture_output=capture,\n",
198
+ " text=True,\n",
199
+ " check=False,\n",
200
+ " cwd=cwd # ← ここに渡す\n",
201
+ " )\n",
202
+ " if check and result.returncode != 0:\n",
203
+ " print(f\"❌ Command failed with code {result.returncode}\")\n",
204
+ " if capture:\n",
205
+ " print(f\"STDOUT: {result.stdout}\")\n",
206
+ " print(f\"STDERR: {result.stderr}\")\n",
207
+ " return result\n",
208
+ "\n",
209
+ "\n",
210
+ "def setup_environment():\n",
211
+ " \"\"\"\n",
212
+ " Colab environment setup for Gaussian Splatting + LightGlue + pycolmap\n",
213
+ " Python 3.12 compatible version (v8)\n",
214
+ " \"\"\"\n",
215
+ "\n",
216
+ " print(\"🚀 Setting up COLAB environment (v8 - Python 3.12 compatible)\")\n",
217
+ "\n",
218
+ " WORK_DIR = \"2d-gaussian-splatting\"\n",
219
+ "\n",
220
+ " # =====================================================================\n",
221
+ " # STEP 0: NumPy FIX (Python 3.12 compatible)\n",
222
+ " # =====================================================================\n",
223
+ " print(\"\\n\" + \"=\"*70)\n",
224
+ " print(\"STEP 0: Fix NumPy (Python 3.12 compatible)\")\n",
225
+ " print(\"=\"*70)\n",
226
+ "\n",
227
+ " # Python 3.12 requires numpy >= 1.26\n",
228
+ " run_cmd([sys.executable, \"-m\", \"pip\", \"uninstall\", \"-y\", \"numpy\"])\n",
229
+ " run_cmd([sys.executable, \"-m\", \"pip\", \"install\", \"numpy==1.26.4\"])\n",
230
+ "\n",
231
+ " # sanity check\n",
232
+ " run_cmd([sys.executable, \"-c\", \"import numpy; print('NumPy:', numpy.__version__)\"])\n",
233
+ "\n",
234
+ " # =====================================================================\n",
235
+ " # STEP 1: System packages (Colab)\n",
236
+ " # =====================================================================\n",
237
+ " print(\"\\n\" + \"=\"*70)\n",
238
+ " print(\"STEP 1: System packages\")\n",
239
+ " print(\"=\"*70)\n",
240
+ "\n",
241
+ " run_cmd([\"apt-get\", \"update\", \"-qq\"])\n",
242
+ " run_cmd([\n",
243
+ " \"apt-get\", \"install\", \"-y\", \"-qq\",\n",
244
+ " \"colmap\",\n",
245
+ " \"build-essential\",\n",
246
+ " \"cmake\",\n",
247
+ " \"git\",\n",
248
+ " \"libopenblas-dev\",\n",
249
+ " \"xvfb\"\n",
250
+ " ])\n",
251
+ "\n",
252
+ " # virtual display (COLMAP / OpenCV safety)\n",
253
+ " os.environ[\"QT_QPA_PLATFORM\"] = \"offscreen\"\n",
254
+ " os.environ[\"DISPLAY\"] = \":99\"\n",
255
+ " subprocess.Popen(\n",
256
+ " [\"Xvfb\", \":99\", \"-screen\", \"0\", \"1024x768x24\"],\n",
257
+ " stdout=subprocess.DEVNULL,\n",
258
+ " stderr=subprocess.DEVNULL\n",
259
+ " )\n",
260
+ "\n",
261
+ " # =====================================================================\n",
262
+ " # STEP 2: Clone 2D Gaussian Splatting\n",
263
+ " # =====================================================================\n",
264
+ " print(\"\\n\" + \"=\"*70)\n",
265
+ " print(\"STEP 2: Clone Gaussian Splatting\")\n",
266
+ " print(\"=\"*70)\n",
267
+ "\n",
268
+ " if not os.path.exists(WORK_DIR):\n",
269
+ " run_cmd([\n",
270
+ " \"git\", \"clone\", \"--recursive\",\n",
271
+ " \"https://github.com/hbb1/2d-gaussian-splatting.git\",\n",
272
+ " WORK_DIR\n",
273
+ " ])\n",
274
+ " else:\n",
275
+ " print(\"✓ Repository already exists\")\n",
276
+ "\n",
277
+ " # =====================================================================\n",
278
+ " # STEP 3: Python packages (FIXED ORDER & VERSIONS)\n",
279
+ " # =====================================================================\n",
280
+ " print(\"\\n\" + \"=\"*70)\n",
281
+ " print(\"STEP 3: Python packages (VERBOSE MODE)\")\n",
282
+ " print(\"=\"*70)\n",
283
+ "\n",
284
+ " # ---- PyTorch (Colab CUDA対応) ----\n",
285
+ " print(\"\\n📦 Installing PyTorch...\")\n",
286
+ " run_cmd([\n",
287
+ " sys.executable, \"-m\", \"pip\", \"install\",\n",
288
+ " \"torch\", \"torchvision\", \"torchaudio\"\n",
289
+ " ])\n",
290
+ "\n",
291
+ " # ---- Core utils ----\n",
292
+ " print(\"\\n📦 Installing core utilities...\")\n",
293
+ " run_cmd([\n",
294
+ " sys.executable, \"-m\", \"pip\", \"install\",\n",
295
+ " \"opencv-python\",\n",
296
+ " \"pillow\",\n",
297
+ " \"imageio\",\n",
298
+ " \"imageio-ffmpeg\",\n",
299
+ " \"plyfile\",\n",
300
+ " \"tqdm\",\n",
301
+ " \"tensorboard\"\n",
302
+ " ])\n",
303
+ "\n",
304
+ " # ---- transformers (NumPy 1.26 compatible) ----\n",
305
+ " print(\"\\n📦 Installing transformers (NumPy 1.26 compatible)...\")\n",
306
+ " # Install transformers with proper dependencies\n",
307
+ " run_cmd([\n",
308
+ " sys.executable, \"-m\", \"pip\", \"install\",\n",
309
+ " \"transformers==4.40.0\"\n",
310
+ " ])\n",
311
+ "\n",
312
+ " # ---- LightGlue stack (GITHUB INSTALL) ----\n",
313
+ " print(\"\\n📦 Installing LightGlue stack...\")\n",
314
+ "\n",
315
+ " # Install kornia first\n",
316
+ " run_cmd([sys.executable, \"-m\", \"pip\", \"install\", \"kornia\"])\n",
317
+ "\n",
318
+ " # Install h5py (sometimes needed)\n",
319
+ " run_cmd([sys.executable, \"-m\", \"pip\", \"install\", \"h5py\"])\n",
320
+ "\n",
321
+ " # Install matplotlib (LightGlue dependency)\n",
322
+ " run_cmd([sys.executable, \"-m\", \"pip\", \"install\", \"matplotlib\"])\n",
323
+ "\n",
324
+ " # Install pycolmap\n",
325
+ " run_cmd([sys.executable, \"-m\", \"pip\", \"install\", \"pycolmap\"])\n",
326
+ "\n",
327
+ "\n",
328
+ "\n",
329
+ " # =====================================================================\n",
330
+ " # STEP 4: Detailed Verification\n",
331
+ " # =====================================================================\n",
332
+ " print(\"\\n\" + \"=\"*70)\n",
333
+ " print(\"STEP 4: Detailed Verification\")\n",
334
+ " print(\"=\"*70)\n",
335
+ "\n",
336
+ " # NumPy (verify version first)\n",
337
+ " print(\"\\n🔍 Testing NumPy...\")\n",
338
+ " try:\n",
339
+ " import numpy as np\n",
340
+ " print(f\" ✓ NumPy: {np.__version__}\")\n",
341
+ " except Exception as e:\n",
342
+ " print(f\" ❌ NumPy failed: {e}\")\n",
343
+ "\n",
344
+ " # PyTorch\n",
345
+ " print(\"\\n🔍 Testing PyTorch...\")\n",
346
+ " try:\n",
347
+ " import torch\n",
348
+ " print(f\" ✓ PyTorch: {torch.__version__}\")\n",
349
+ " print(f\" ✓ CUDA available: {torch.cuda.is_available()}\")\n",
350
+ " if torch.cuda.is_available():\n",
351
+ " print(f\" ✓ CUDA version: {torch.version.cuda}\")\n",
352
+ " except Exception as e:\n",
353
+ " print(f\" ❌ PyTorch failed: {e}\")\n",
354
+ "\n",
355
+ " # transformers\n",
356
+ " print(\"\\n🔍 Testing transformers...\")\n",
357
+ " try:\n",
358
+ " import transformers\n",
359
+ " print(f\" ✓ transformers version: {transformers.__version__}\")\n",
360
+ " from transformers import AutoModel\n",
361
+ " print(f\" ✓ AutoModel import: OK\")\n",
362
+ " except Exception as e:\n",
363
+ " print(f\" ❌ transformers failed: {e}\")\n",
364
+ " print(f\" Attempting detailed diagnosis...\")\n",
365
+ " result = run_cmd([\n",
366
+ " sys.executable, \"-c\",\n",
367
+ " \"import transformers; print(transformers.__version__)\"\n",
368
+ " ], capture=True)\n",
369
+ " print(f\" Output: {result.stdout}\")\n",
370
+ " print(f\" Error: {result.stderr}\")\n",
371
+ "\n",
372
+ " # pycolmap\n",
373
+ " print(\"\\n🔍 Testing pycolmap...\")\n",
374
+ " try:\n",
375
+ " import pycolmap\n",
376
+ " print(f\" ✓ pycolmap: OK\")\n",
377
+ " except Exception as e:\n",
378
+ " print(f\" ❌ pycolmap failed: {e}\")\n",
379
+ "\n",
380
+ " # kornia\n",
381
+ " print(\"\\n🔍 Testing kornia...\")\n",
382
+ " try:\n",
383
+ " import kornia\n",
384
+ " print(f\" ✓ kornia: {kornia.__version__}\")\n",
385
+ " except Exception as e:\n",
386
+ " print(f\" ❌ kornia failed: {e}\")\n",
387
+ "\n",
388
+ " return WORK_DIR\n",
389
+ "\n",
390
+ "\n",
391
+ "if __name__ == \"__main__\":\n",
392
+ " setup_environment()"
393
+ ]
394
+ },
395
+ {
396
+ "cell_type": "code",
397
+ "source": [],
398
+ "metadata": {
399
+ "id": "3UEcAPBILz6Z"
400
+ },
401
+ "id": "3UEcAPBILz6Z",
402
+ "execution_count": null,
403
+ "outputs": []
404
+ },
405
+ {
406
+ "cell_type": "code",
407
+ "source": [
408
+ "# =====================================================================\n",
409
+ "# STEP 4: Build 2D GS submodules (確実な方法)\n",
410
+ "# =====================================================================\n",
411
+ "print(\"\\n\" + \"=\"*70)\n",
412
+ "print(\"STEP 5: Build Gaussian Splatting submodules\")\n",
413
+ "print(\"=\"*70)\n",
414
+ "\n",
415
+ "# diff-surfel-rasterization\n",
416
+ "\n",
417
+ "path = os.path.join(WORK_DIR, \"submodules\", \"diff-surfel-rasterization\")\n",
418
+ "url = \"https://github.com/hbb1/diff-surfel-rasterization.git\"\n",
419
+ "name = os.path.basename(path)\n",
420
+ "print(f\"\\n📦 Processing {name}...\")\n",
421
+ "if not os.path.exists(path):\n",
422
+ " print(f\" > Cloning {url}...\")\n",
423
+ " # 親ディレクトリが存在することを確認\n",
424
+ " os.makedirs(os.path.dirname(path), exist_ok=True)\n",
425
+ " run_cmd([\"git\", \"clone\", url, path])\n",
426
+ "else:\n",
427
+ " print(f\" ✓ {name} already exists.\")\n",
428
+ "# 2. setup.py install (コンパイル)\n",
429
+ "print(f\" > Compiling and Installing {name}...\")\n",
430
+ "result = run_cmd(\n",
431
+ " [sys.executable, \"setup.py\", \"install\"],\n",
432
+ " cwd=path,\n",
433
+ " check=False, # エラーでも止めない\n",
434
+ " capture=True\n",
435
+ ")\n",
436
+ "if result.returncode != 0:\n",
437
+ " print(f\"❌ Failed to build {name}\")\n",
438
+ " print(\"--- STDERR ---\")\n",
439
+ " print(result.stderr)\n",
440
+ "else:\n",
441
+ " print(f\"✅ Successfully built {name}\")"
442
+ ],
443
+ "metadata": {
444
+ "colab": {
445
+ "base_uri": "https://localhost:8080/",
446
+ "height": 538
447
+ },
448
+ "id": "kLdJ-FeT-kQc",
449
+ "outputId": "bdc84b67-f7c5-4ff4-b928-fb6ed217f7ec"
450
+ },
451
+ "id": "kLdJ-FeT-kQc",
452
+ "execution_count": 6,
453
+ "outputs": [
454
+ {
455
+ "output_type": "stream",
456
+ "name": "stdout",
457
+ "text": [
458
+ "\n",
459
+ "======================================================================\n",
460
+ "STEP 5: Build Gaussian Splatting submodules\n",
461
+ "======================================================================\n",
462
+ "\n",
463
+ "📦 Processing diff-surfel-rasterization...\n",
464
+ " ✓ diff-surfel-rasterization already exists.\n",
465
+ " > Compiling and Installing diff-surfel-rasterization...\n",
466
+ "Running: /usr/bin/python3 setup.py install\n"
467
+ ]
468
+ },
469
+ {
470
+ "output_type": "error",
471
+ "ename": "KeyboardInterrupt",
472
+ "evalue": "",
473
+ "traceback": [
474
+ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
475
+ "\u001b[0;31mKeyboardInterrupt\u001b[0m Traceback (most recent call last)",
476
+ "\u001b[0;32m/tmp/ipython-input-3213212644.py\u001b[0m in \u001b[0;36m<cell line: 0>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 21\u001b[0m \u001b[0;31m# 2. setup.py install (コンパイル)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 22\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34mf\" > Compiling and Installing {name}...\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 23\u001b[0;31m result = run_cmd(\n\u001b[0m\u001b[1;32m 24\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0msys\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mexecutable\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m\"setup.py\"\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m\"install\"\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 25\u001b[0m \u001b[0mcwd\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mpath\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
477
+ "\u001b[0;32m/tmp/ipython-input-4121284188.py\u001b[0m in \u001b[0;36mrun_cmd\u001b[0;34m(cmd, check, capture, cwd)\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;34m\"\"\"Run command with better error handling\"\"\"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34mf\"Running: {' '.join(cmd)}\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m result = subprocess.run(\n\u001b[0m\u001b[1;32m 5\u001b[0m \u001b[0mcmd\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0mcapture_output\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mcapture\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
478
+ "\u001b[0;32m/usr/lib/python3.12/subprocess.py\u001b[0m in \u001b[0;36mrun\u001b[0;34m(input, capture_output, timeout, check, *popenargs, **kwargs)\u001b[0m\n\u001b[1;32m 548\u001b[0m \u001b[0;32mwith\u001b[0m \u001b[0mPopen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0mpopenargs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0mprocess\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 549\u001b[0m \u001b[0;32mtry\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 550\u001b[0;31m \u001b[0mstdout\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mstderr\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mprocess\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mcommunicate\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0minput\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mtimeout\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mtimeout\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 551\u001b[0m \u001b[0;32mexcept\u001b[0m \u001b[0mTimeoutExpired\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0mexc\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 552\u001b[0m \u001b[0mprocess\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mkill\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
479
+ "\u001b[0;32m/usr/lib/python3.12/subprocess.py\u001b[0m in \u001b[0;36mcommunicate\u001b[0;34m(self, input, timeout)\u001b[0m\n\u001b[1;32m 1207\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1208\u001b[0m \u001b[0;32mtry\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 1209\u001b[0;31m \u001b[0mstdout\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mstderr\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_communicate\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0minput\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mendtime\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mtimeout\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 1210\u001b[0m \u001b[0;32mexcept\u001b[0m \u001b[0mKeyboardInterrupt\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1211\u001b[0m \u001b[0;31m# https://bugs.python.org/issue25942\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
480
+ "\u001b[0;32m/usr/lib/python3.12/subprocess.py\u001b[0m in \u001b[0;36m_communicate\u001b[0;34m(self, input, endtime, orig_timeout)\u001b[0m\n\u001b[1;32m 2113\u001b[0m 'failed to raise TimeoutExpired.')\n\u001b[1;32m 2114\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 2115\u001b[0;31m \u001b[0mready\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mselector\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mselect\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mtimeout\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 2116\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_check_timeout\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mendtime\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0morig_timeout\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mstdout\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mstderr\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2117\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
481
+ "\u001b[0;32m/usr/lib/python3.12/selectors.py\u001b[0m in \u001b[0;36mselect\u001b[0;34m(self, timeout)\u001b[0m\n\u001b[1;32m 413\u001b[0m \u001b[0mready\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 414\u001b[0m \u001b[0;32mtry\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 415\u001b[0;31m \u001b[0mfd_event_list\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_selector\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mpoll\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mtimeout\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 416\u001b[0m \u001b[0;32mexcept\u001b[0m \u001b[0mInterruptedError\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 417\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mready\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
482
+ "\u001b[0;31mKeyboardInterrupt\u001b[0m: "
483
+ ]
484
+ }
485
+ ]
486
+ },
487
+ {
488
+ "cell_type": "code",
489
+ "source": [
490
+ "import os\n",
491
+ "import sys\n",
492
+ "import shutil\n",
493
+ "import subprocess\n",
494
+ "\n",
495
+ "# --- 前準備: 環境の整備 ---\n",
496
+ "print(\"Configuring build environment...\")\n",
497
+ "# 1. CUDAコンパイラの確認\n",
498
+ "!nvcc --version\n",
499
+ "\n",
500
+ "# 2. 必須ツールのインストール (ninjaはビルドを安定・高速化させます)\n",
501
+ "!pip install setuptools wheel ninja\n",
502
+ "\n",
503
+ "# 3. 環境変数のセットアップ (CUDAのパスを明示的に指定)\n",
504
+ "os.environ[\"CUDA_HOME\"] = \"/usr/local/cuda\"\n",
505
+ "os.environ[\"PATH\"] = f'{os.environ[\"CUDA_HOME\"]}/bin:{os.environ[\"PATH\"]}'\n",
506
+ "os.environ[\"LD_LIBRARY_PATH\"] = f'{os.environ[\"CUDA_HOME\"]}/lib64:{os.environ[\"LD_LIBRARY_PATH\"]}'\n",
507
+ "# メモリ不足によるクラッシュを防ぐため、並列ビルド数を制限\n",
508
+ "os.environ[\"MAX_JOBS\"] = \"2\"\n",
509
+ "\n",
510
+ "def run_cmd(cmd, cwd=None, check=True):\n",
511
+ " \"\"\"コマンド実行用のヘルパー関数\"\"\"\n",
512
+ " return subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, check=check)\n",
513
+ "\n",
514
+ "def install_submodule(name, url, base_dir):\n",
515
+ " \"\"\"個別のサブモジュールをインストール\"\"\"\n",
516
+ " print(f\"\\n{'='*70}\")\n",
517
+ " print(f\"Installing {name}\")\n",
518
+ " print(f\"{'='*70}\")\n",
519
+ "\n",
520
+ " # 絶対パスを使用\n",
521
+ " path = os.path.abspath(os.path.join(base_dir, \"submodules\", name))\n",
522
+ " print(f\" > Target path: {path}\")\n",
523
+ "\n",
524
+ " # Step 1: 既存を削除\n",
525
+ " if os.path.exists(path):\n",
526
+ " print(f\" > Removing old {name}...\")\n",
527
+ " shutil.rmtree(path)\n",
528
+ "\n",
529
+ " # Step 2: クローン\n",
530
+ " print(f\" > Cloning from {url}...\")\n",
531
+ " os.makedirs(os.path.dirname(path), exist_ok=True)\n",
532
+ " try:\n",
533
+ " run_cmd([\"git\", \"clone\", url, path])\n",
534
+ " except subprocess.CalledProcessError as e:\n",
535
+ " print(f\"❌ Failed to clone {name}\")\n",
536
+ " print(e.stderr)\n",
537
+ " return False\n",
538
+ "\n",
539
+ " # Step 3: ファイル確認 (spatial.cu 等の存在をチェック)\n",
540
+ " print(f\" > Checking cloned files...\")\n",
541
+ " files = os.listdir(path)\n",
542
+ " print(f\" > Files in {name}: {files[:10]}...\")\n",
543
+ "\n",
544
+ " # Step 4: 特定モジュールのサブモジュール初期化\n",
545
+ " if name == \"diff-surfel-rasterization\":\n",
546
+ " print(f\" > Initializing GLM submodule...\")\n",
547
+ " run_cmd([\"git\", \"submodule\", \"update\", \"--init\", \"--recursive\"], cwd=path)\n",
548
+ "\n",
549
+ " # Step 5: ビルドキャッシュ削除\n",
550
+ " build_dir = os.path.join(path, \"build\")\n",
551
+ " if os.path.exists(build_dir):\n",
552
+ " print(f\" > Cleaning build cache...\")\n",
553
+ " shutil.rmtree(build_dir)\n",
554
+ "\n",
555
+ " # Step 6: インストール\n",
556
+ " print(f\" > Installing {name} (This may take a few minutes)...\")\n",
557
+ " # 環境変数を明示的に引き継ぐ\n",
558
+ " current_env = os.environ.copy()\n",
559
+ "\n",
560
+ " result = subprocess.run(\n",
561
+ " [sys.executable, \"-m\", \"pip\", \"install\", \"-e\", \".\", \"--no-build-isolation\", \"-v\"],\n",
562
+ " cwd=path,\n",
563
+ " env=current_env,\n",
564
+ " capture_output=True,\n",
565
+ " text=True\n",
566
+ " )\n",
567
+ "\n",
568
+ " if result.returncode != 0:\n",
569
+ " print(f\"❌ Failed to install {name}\")\n",
570
+ " # C++/CUDAのビルドエラーは stdout に出ることが多いため、両方出力\n",
571
+ " print(\"\\n--- STDOUT (Build Logs) ---\")\n",
572
+ " stdout_lines = result.stdout.split('\\n')\n",
573
+ " print('\\n'.join(stdout_lines[-60:])) # 最後の60行を表示\n",
574
+ "\n",
575
+ " print(\"\\n--- STDERR (Error Details) ---\")\n",
576
+ " print(result.stderr)\n",
577
+ " return False\n",
578
+ "\n",
579
+ " print(f\"✅ Successfully installed {name}\")\n",
580
+ " return True\n",
581
+ "\n",
582
+ "# =====================================================================\n",
583
+ "# STEP 4: Build 2D GS submodules\n",
584
+ "# =====================================================================\n",
585
+ "print(\"\\n\" + \"=\"*70)\n",
586
+ "print(\"STEP 4: Build Gaussian Splatting submodules\")\n",
587
+ "print(\"=\"*70)\n",
588
+ "\n",
589
+ "# Colabの場合は絶対パス\n",
590
+ "WORK_DIR = \"/content/2d-gaussian-splatting\"\n",
591
+ "\n",
592
+ "# 各サブモジュールのインストール\n",
593
+ "# simple-knn\n",
594
+ "success_knn = install_submodule(\n",
595
+ " \"simple-knn\",\n",
596
+ " \"https://github.com/tztechno/simple-knn.git\",\n",
597
+ " WORK_DIR\n",
598
+ ")\n",
599
+ "\n",
600
+ "\n",
601
+ "# 結果表示\n",
602
+ "print(\"\\n\" + \"=\"*70)\n",
603
+ "print(\"Installation Summary\")\n",
604
+ "print(\"=\"*70)\n",
605
+ "print(f\"simple-knn: {'✅ Success' if success_knn else '❌ Failed'}\")"
606
+ ],
607
+ "metadata": {
608
+ "id": "qYgJl2Fw_Phk"
609
+ },
610
+ "id": "qYgJl2Fw_Phk",
611
+ "execution_count": null,
612
+ "outputs": []
613
+ },
614
+ {
615
+ "cell_type": "code",
616
+ "source": [
617
+ "!nvcc --version\n",
618
+ "import torch\n",
619
+ "print(torch.__version__)\n",
620
+ "print(torch.version.cuda)"
621
+ ],
622
+ "metadata": {
623
+ "id": "Ev9PEUdtpEAx"
624
+ },
625
+ "id": "Ev9PEUdtpEAx",
626
+ "execution_count": null,
627
+ "outputs": []
628
+ },
629
+ {
630
+ "cell_type": "code",
631
+ "execution_count": null,
632
+ "id": "b8690389",
633
+ "metadata": {
634
+ "execution": {
635
+ "iopub.execute_input": "2026-01-10T18:22:43.739411Z",
636
+ "iopub.status.busy": "2026-01-10T18:22:43.738855Z",
637
+ "iopub.status.idle": "2026-01-10T18:22:43.755664Z",
638
+ "shell.execute_reply": "2026-01-10T18:22:43.754865Z"
639
+ },
640
+ "papermill": {
641
+ "duration": 0.027297,
642
+ "end_time": "2026-01-10T18:22:43.756758",
643
+ "exception": false,
644
+ "start_time": "2026-01-10T18:22:43.729461",
645
+ "status": "completed"
646
+ },
647
+ "tags": [],
648
+ "id": "b8690389"
649
+ },
650
+ "outputs": [],
651
+ "source": [
652
+ "import os\n",
653
+ "import glob\n",
654
+ "import cv2\n",
655
+ "import numpy as np\n",
656
+ "from PIL import Image\n",
657
+ "\n",
658
+ "# =========================================================\n",
659
+ "# Utility: aspect ratio preserved + black padding\n",
660
+ "# =========================================================\n",
661
+ "\n",
662
+ "def normalize_image_sizes_biplet(input_dir, output_dir=None, size=1024, max_images=None):\n",
663
+ " \"\"\"\n",
664
+ " Generates two square crops (Left & Right or Top & Bottom)\n",
665
+ " from each image in a directory and returns the output directory\n",
666
+ " and the list of generated file paths.\n",
667
+ "\n",
668
+ " Args:\n",
669
+ " input_dir: Input directory containing source images\n",
670
+ " output_dir: Output directory for processed images\n",
671
+ " size: Target square size (default: 1024)\n",
672
+ " max_images: Maximum number of SOURCE images to process (default: None = all images)\n",
673
+ " \"\"\"\n",
674
+ " if output_dir is None:\n",
675
+ " output_dir = 'output/images_biplet'\n",
676
+ " os.makedirs(output_dir, exist_ok=True)\n",
677
+ "\n",
678
+ " print(f\"--- Step 1: Biplet-Square Normalization ---\")\n",
679
+ " print(f\"Generating 2 cropped squares (Left/Right or Top/Bottom) for each image...\")\n",
680
+ " print()\n",
681
+ "\n",
682
+ " generated_paths = []\n",
683
+ " converted_count = 0\n",
684
+ " size_stats = {}\n",
685
+ "\n",
686
+ " # Sort for consistent processing order\n",
687
+ " image_files = sorted([f for f in os.listdir(input_dir)\n",
688
+ " if f.lower().endswith(('.jpg', '.jpeg', '.png'))])\n",
689
+ "\n",
690
+ " # ★ max_images で元画像数を制限\n",
691
+ " if max_images is not None:\n",
692
+ " image_files = image_files[:max_images]\n",
693
+ " print(f\"Processing limited to {max_images} source images (will generate {max_images * 2} cropped images)\")\n",
694
+ "\n",
695
+ " for img_file in image_files:\n",
696
+ " input_path = os.path.join(input_dir, img_file)\n",
697
+ " try:\n",
698
+ " img = Image.open(input_path)\n",
699
+ " original_size = img.size\n",
700
+ "\n",
701
+ " # Tracking original aspect ratios\n",
702
+ " size_key = f\"{original_size[0]}x{original_size[1]}\"\n",
703
+ " size_stats[size_key] = size_stats.get(size_key, 0) + 1\n",
704
+ "\n",
705
+ " # Generate 2 crops using the helper function\n",
706
+ " crops = generate_two_crops(img, size)\n",
707
+ " base_name, ext = os.path.splitext(img_file)\n",
708
+ "\n",
709
+ " for mode, cropped_img in crops.items():\n",
710
+ " output_path = os.path.join(output_dir, f\"{base_name}_{mode}{ext}\")\n",
711
+ " cropped_img.save(output_path, quality=95)\n",
712
+ " generated_paths.append(output_path)\n",
713
+ "\n",
714
+ " converted_count += 1\n",
715
+ " print(f\" ✓ {img_file}: {original_size} → 2 square images generated\")\n",
716
+ "\n",
717
+ " except Exception as e:\n",
718
+ " print(f\" ✗ Error processing {img_file}: {e}\")\n",
719
+ "\n",
720
+ " print(f\"\\nProcessing complete: {converted_count} source images processed\")\n",
721
+ " print(f\"Total output images: {len(generated_paths)}\")\n",
722
+ " print(f\"Original size distribution: {size_stats}\")\n",
723
+ "\n",
724
+ " return output_dir, generated_paths\n",
725
+ "\n",
726
+ "\n",
727
+ "def generate_two_crops(img, size):\n",
728
+ " \"\"\"\n",
729
+ " Crops the image into a square and returns 2 variations\n",
730
+ " (Left/Right for landscape, Top/Bottom for portrait).\n",
731
+ " \"\"\"\n",
732
+ " width, height = img.size\n",
733
+ " crop_size = min(width, height)\n",
734
+ " crops = {}\n",
735
+ "\n",
736
+ " if width > height:\n",
737
+ " # Landscape → Left & Right\n",
738
+ " positions = {\n",
739
+ " 'left': 0,\n",
740
+ " 'right': width - crop_size\n",
741
+ " }\n",
742
+ " for mode, x_offset in positions.items():\n",
743
+ " box = (x_offset, 0, x_offset + crop_size, crop_size)\n",
744
+ " crops[mode] = img.crop(box).resize(\n",
745
+ " (size, size),\n",
746
+ " Image.Resampling.LANCZOS\n",
747
+ " )\n",
748
+ "\n",
749
+ " else:\n",
750
+ " # Portrait or Square → Top & Bottom\n",
751
+ " positions = {\n",
752
+ " 'top': 0,\n",
753
+ " 'bottom': height - crop_size\n",
754
+ " }\n",
755
+ " for mode, y_offset in positions.items():\n",
756
+ " box = (0, y_offset, crop_size, y_offset + crop_size)\n",
757
+ " crops[mode] = img.crop(box).resize(\n",
758
+ " (size, size),\n",
759
+ " Image.Resampling.LANCZOS\n",
760
+ " )\n",
761
+ "\n",
762
+ " return crops\n"
763
+ ]
764
+ },
765
+ {
766
+ "cell_type": "code",
767
+ "execution_count": null,
768
+ "id": "7acc20b6",
769
+ "metadata": {
770
+ "execution": {
771
+ "iopub.execute_input": "2026-01-10T18:22:43.772525Z",
772
+ "iopub.status.busy": "2026-01-10T18:22:43.772303Z",
773
+ "iopub.status.idle": "2026-01-10T18:22:43.790574Z",
774
+ "shell.execute_reply": "2026-01-10T18:22:43.789515Z"
775
+ },
776
+ "papermill": {
777
+ "duration": 0.027612,
778
+ "end_time": "2026-01-10T18:22:43.791681",
779
+ "exception": false,
780
+ "start_time": "2026-01-10T18:22:43.764069",
781
+ "status": "completed"
782
+ },
783
+ "tags": [],
784
+ "id": "7acc20b6"
785
+ },
786
+ "outputs": [],
787
+ "source": [
788
+ "def run_colmap_reconstruction(image_dir, colmap_dir):\n",
789
+ " \"\"\"Estimate camera poses and 3D point cloud with COLMAP\"\"\"\n",
790
+ " print(\"Running SfM reconstruction with COLMAP...\")\n",
791
+ "\n",
792
+ " database_path = os.path.join(colmap_dir, \"database.db\")\n",
793
+ " sparse_dir = os.path.join(colmap_dir, \"sparse\")\n",
794
+ " os.makedirs(sparse_dir, exist_ok=True)\n",
795
+ "\n",
796
+ " # Set environment variable\n",
797
+ " env = os.environ.copy()\n",
798
+ " env['QT_QPA_PLATFORM'] = 'offscreen'\n",
799
+ "\n",
800
+ " # Feature extraction\n",
801
+ " print(\"1/4: Extracting features...\")\n",
802
+ " subprocess.run([\n",
803
+ " 'colmap', 'feature_extractor',\n",
804
+ " '--database_path', database_path,\n",
805
+ " '--image_path', image_dir,\n",
806
+ " '--ImageReader.single_camera', '1',\n",
807
+ " '--ImageReader.camera_model', 'OPENCV',\n",
808
+ " '--SiftExtraction.use_gpu', '0' # Use CPU\n",
809
+ " ], check=True, env=env)\n",
810
+ "\n",
811
+ " # Feature matching\n",
812
+ " print(\"2/4: Matching features...\")\n",
813
+ " subprocess.run([\n",
814
+ " 'colmap', 'exhaustive_matcher', # Use sequential_matcher instead of exhaustive_matcher\n",
815
+ " '--database_path', database_path,\n",
816
+ " '--SiftMatching.use_gpu', '0' # Use CPU\n",
817
+ " ], check=True, env=env)\n",
818
+ "\n",
819
+ " # Sparse reconstruction\n",
820
+ " print(\"3/4: Sparse reconstruction...\")\n",
821
+ " subprocess.run([\n",
822
+ " 'colmap', 'mapper',\n",
823
+ " '--database_path', database_path,\n",
824
+ " '--image_path', image_dir,\n",
825
+ " '--output_path', sparse_dir,\n",
826
+ " '--Mapper.ba_global_max_num_iterations', '20', # Speed up\n",
827
+ " '--Mapper.ba_local_max_num_iterations', '10'\n",
828
+ " ], check=True, env=env)\n",
829
+ "\n",
830
+ " # Export to text format\n",
831
+ " print(\"4/4: Exporting to text format...\")\n",
832
+ " model_dir = os.path.join(sparse_dir, '0')\n",
833
+ " if not os.path.exists(model_dir):\n",
834
+ " # Use the first model found\n",
835
+ " subdirs = [d for d in os.listdir(sparse_dir) if os.path.isdir(os.path.join(sparse_dir, d))]\n",
836
+ " if subdirs:\n",
837
+ " model_dir = os.path.join(sparse_dir, subdirs[0])\n",
838
+ " else:\n",
839
+ " raise FileNotFoundError(\"COLMAP reconstruction failed\")\n",
840
+ "\n",
841
+ " subprocess.run([\n",
842
+ " 'colmap', 'model_converter',\n",
843
+ " '--input_path', model_dir,\n",
844
+ " '--output_path', model_dir,\n",
845
+ " '--output_type', 'TXT'\n",
846
+ " ], check=True, env=env)\n",
847
+ "\n",
848
+ " print(f\"COLMAP reconstruction complete: {model_dir}\")\n",
849
+ " return model_dir\n",
850
+ "\n",
851
+ "\n",
852
+ "def convert_cameras_to_pinhole(input_file, output_file):\n",
853
+ " \"\"\"Convert camera model to PINHOLE format\"\"\"\n",
854
+ " print(f\"Reading camera file: {input_file}\")\n",
855
+ "\n",
856
+ " with open(input_file, 'r') as f:\n",
857
+ " lines = f.readlines()\n",
858
+ "\n",
859
+ " converted_count = 0\n",
860
+ " with open(output_file, 'w') as f:\n",
861
+ " for line in lines:\n",
862
+ " if line.startswith('#') or line.strip() == '':\n",
863
+ " f.write(line)\n",
864
+ " else:\n",
865
+ " parts = line.strip().split()\n",
866
+ " if len(parts) >= 4:\n",
867
+ " cam_id = parts[0]\n",
868
+ " model = parts[1]\n",
869
+ " width = parts[2]\n",
870
+ " height = parts[3]\n",
871
+ " params = parts[4:]\n",
872
+ "\n",
873
+ " # Convert to PINHOLE format\n",
874
+ " if model == \"PINHOLE\":\n",
875
+ " f.write(line)\n",
876
+ " elif model == \"OPENCV\":\n",
877
+ " # OPENCV: fx, fy, cx, cy, k1, k2, p1, p2\n",
878
+ " fx = params[0]\n",
879
+ " fy = params[1]\n",
880
+ " cx = params[2]\n",
881
+ " cy = params[3]\n",
882
+ " f.write(f\"{cam_id} PINHOLE {width} {height} {fx} {fy} {cx} {cy}\\n\")\n",
883
+ " converted_count += 1\n",
884
+ " else:\n",
885
+ " # Convert other models too\n",
886
+ " fx = fy = max(float(width), float(height))\n",
887
+ " cx = float(width) / 2\n",
888
+ " cy = float(height) / 2\n",
889
+ " f.write(f\"{cam_id} PINHOLE {width} {height} {fx} {fy} {cx} {cy}\\n\")\n",
890
+ " converted_count += 1\n",
891
+ " else:\n",
892
+ " f.write(line)\n",
893
+ "\n",
894
+ " print(f\"Converted {converted_count} cameras to PINHOLE format\")\n",
895
+ "\n",
896
+ "\n",
897
+ "def prepare_gaussian_splatting_data(image_dir, colmap_model_dir):\n",
898
+ " \"\"\"Prepare data for Gaussian Splatting\"\"\"\n",
899
+ " print(\"Preparing data for Gaussian Splatting...\")\n",
900
+ "\n",
901
+ " data_dir = f\"{WORK_DIR}/data/video\"\n",
902
+ " os.makedirs(f\"{data_dir}/sparse/0\", exist_ok=True)\n",
903
+ " os.makedirs(f\"{data_dir}/images\", exist_ok=True)\n",
904
+ "\n",
905
+ " # Copy images\n",
906
+ " print(\"Copying images...\")\n",
907
+ " img_count = 0\n",
908
+ " for img_file in os.listdir(image_dir):\n",
909
+ " if img_file.lower().endswith(('.jpg', '.jpeg', '.png')):\n",
910
+ " shutil.copy(\n",
911
+ " os.path.join(image_dir, img_file),\n",
912
+ " f\"{data_dir}/images/{img_file}\"\n",
913
+ " )\n",
914
+ " img_count += 1\n",
915
+ " print(f\"Copied {img_count} images\")\n",
916
+ "\n",
917
+ " # Convert and copy camera file to PINHOLE format\n",
918
+ " print(\"Converting camera model to PINHOLE format...\")\n",
919
+ " convert_cameras_to_pinhole(\n",
920
+ " os.path.join(colmap_model_dir, 'cameras.txt'),\n",
921
+ " f\"{data_dir}/sparse/0/cameras.txt\"\n",
922
+ " )\n",
923
+ "\n",
924
+ " # Copy other files\n",
925
+ " for filename in ['images.txt', 'points3D.txt']:\n",
926
+ " src = os.path.join(colmap_model_dir, filename)\n",
927
+ " dst = f\"{data_dir}/sparse/0/{filename}\"\n",
928
+ " if os.path.exists(src):\n",
929
+ " shutil.copy(src, dst)\n",
930
+ " print(f\"Copied {filename}\")\n",
931
+ " else:\n",
932
+ " print(f\"Warning: {filename} not found\")\n",
933
+ "\n",
934
+ " print(f\"Data preparation complete: {data_dir}\")\n",
935
+ " return data_dir\n",
936
+ "\n",
937
+ "def run_colmap_reconstruction(image_dir, colmap_dir):\n",
938
+ " \"\"\"Estimate camera poses and 3D point cloud with COLMAP\"\"\"\n",
939
+ " print(\"Running SfM reconstruction with COLMAP...\")\n",
940
+ "\n",
941
+ " database_path = os.path.join(colmap_dir, \"database.db\")\n",
942
+ " sparse_dir = os.path.join(colmap_dir, \"sparse\")\n",
943
+ " os.makedirs(sparse_dir, exist_ok=True)\n",
944
+ "\n",
945
+ " # Set environment variable\n",
946
+ " env = os.environ.copy()\n",
947
+ " env['QT_QPA_PLATFORM'] = 'offscreen'\n",
948
+ "\n",
949
+ " # Feature extraction\n",
950
+ " print(\"1/4: Extracting features...\")\n",
951
+ " subprocess.run([\n",
952
+ " 'colmap', 'feature_extractor',\n",
953
+ " '--database_path', database_path,\n",
954
+ " '--image_path', image_dir,\n",
955
+ " '--ImageReader.single_camera', '1',\n",
956
+ " '--ImageReader.camera_model', 'OPENCV',\n",
957
+ " '--SiftExtraction.use_gpu', '0' # Use CPU\n",
958
+ " ], check=True, env=env)\n",
959
+ "\n",
960
+ " # Feature matching\n",
961
+ " print(\"2/4: Matching features...\")\n",
962
+ " subprocess.run([\n",
963
+ " 'colmap', 'exhaustive_matcher', # Use sequential_matcher instead of exhaustive_matcher\n",
964
+ " '--database_path', database_path,\n",
965
+ " '--SiftMatching.use_gpu', '0' # Use CPU\n",
966
+ " ], check=True, env=env)\n",
967
+ "\n",
968
+ " # Sparse reconstruction\n",
969
+ " print(\"3/4: Sparse reconstruction...\")\n",
970
+ " subprocess.run([\n",
971
+ " 'colmap', 'mapper',\n",
972
+ " '--database_path', database_path,\n",
973
+ " '--image_path', image_dir,\n",
974
+ " '--output_path', sparse_dir,\n",
975
+ " '--Mapper.ba_global_max_num_iterations', '20', # Speed up\n",
976
+ " '--Mapper.ba_local_max_num_iterations', '10'\n",
977
+ " ], check=True, env=env)\n",
978
+ "\n",
979
+ " # Export to text format\n",
980
+ " print(\"4/4: Exporting to text format...\")\n",
981
+ " model_dir = os.path.join(sparse_dir, '0')\n",
982
+ " if not os.path.exists(model_dir):\n",
983
+ " # Use the first model found\n",
984
+ " subdirs = [d for d in os.listdir(sparse_dir) if os.path.isdir(os.path.join(sparse_dir, d))]\n",
985
+ " if subdirs:\n",
986
+ " model_dir = os.path.join(sparse_dir, subdirs[0])\n",
987
+ " else:\n",
988
+ " raise FileNotFoundError(\"COLMAP reconstruction failed\")\n",
989
+ "\n",
990
+ " subprocess.run([\n",
991
+ " 'colmap', 'model_converter',\n",
992
+ " '--input_path', model_dir,\n",
993
+ " '--output_path', model_dir,\n",
994
+ " '--output_type', 'TXT'\n",
995
+ " ], check=True, env=env)\n",
996
+ "\n",
997
+ " print(f\"COLMAP reconstruction complete: {model_dir}\")\n",
998
+ " return model_dir\n",
999
+ "\n",
1000
+ "\n",
1001
+ "def convert_cameras_to_pinhole(input_file, output_file):\n",
1002
+ " \"\"\"Convert camera model to PINHOLE format\"\"\"\n",
1003
+ " print(f\"Reading camera file: {input_file}\")\n",
1004
+ "\n",
1005
+ " with open(input_file, 'r') as f:\n",
1006
+ " lines = f.readlines()\n",
1007
+ "\n",
1008
+ " converted_count = 0\n",
1009
+ " with open(output_file, 'w') as f:\n",
1010
+ " for line in lines:\n",
1011
+ " if line.startswith('#') or line.strip() == '':\n",
1012
+ " f.write(line)\n",
1013
+ " else:\n",
1014
+ " parts = line.strip().split()\n",
1015
+ " if len(parts) >= 4:\n",
1016
+ " cam_id = parts[0]\n",
1017
+ " model = parts[1]\n",
1018
+ " width = parts[2]\n",
1019
+ " height = parts[3]\n",
1020
+ " params = parts[4:]\n",
1021
+ "\n",
1022
+ " # Convert to PINHOLE format\n",
1023
+ " if model == \"PINHOLE\":\n",
1024
+ " f.write(line)\n",
1025
+ " elif model == \"OPENCV\":\n",
1026
+ " # OPENCV: fx, fy, cx, cy, k1, k2, p1, p2\n",
1027
+ " fx = params[0]\n",
1028
+ " fy = params[1]\n",
1029
+ " cx = params[2]\n",
1030
+ " cy = params[3]\n",
1031
+ " f.write(f\"{cam_id} PINHOLE {width} {height} {fx} {fy} {cx} {cy}\\n\")\n",
1032
+ " converted_count += 1\n",
1033
+ " else:\n",
1034
+ " # Convert other models too\n",
1035
+ " fx = fy = max(float(width), float(height))\n",
1036
+ " cx = float(width) / 2\n",
1037
+ " cy = float(height) / 2\n",
1038
+ " f.write(f\"{cam_id} PINHOLE {width} {height} {fx} {fy} {cx} {cy}\\n\")\n",
1039
+ " converted_count += 1\n",
1040
+ " else:\n",
1041
+ " f.write(line)\n",
1042
+ "\n",
1043
+ " print(f\"Converted {converted_count} cameras to PINHOLE format\")\n",
1044
+ "\n",
1045
+ "\n",
1046
+ "def prepare_gaussian_splatting_data(image_dir, colmap_model_dir):\n",
1047
+ " \"\"\"Prepare data for Gaussian Splatting\"\"\"\n",
1048
+ " print(\"Preparing data for Gaussian Splatting...\")\n",
1049
+ "\n",
1050
+ " data_dir = f\"{WORK_DIR}/data/video\"\n",
1051
+ " os.makedirs(f\"{data_dir}/sparse/0\", exist_ok=True)\n",
1052
+ " os.makedirs(f\"{data_dir}/images\", exist_ok=True)\n",
1053
+ "\n",
1054
+ " # Copy images\n",
1055
+ " print(\"Copying images...\")\n",
1056
+ " img_count = 0\n",
1057
+ " for img_file in os.listdir(image_dir):\n",
1058
+ " if img_file.lower().endswith(('.jpg', '.jpeg', '.png')):\n",
1059
+ " shutil.copy(\n",
1060
+ " os.path.join(image_dir, img_file),\n",
1061
+ " f\"{data_dir}/images/{img_file}\"\n",
1062
+ " )\n",
1063
+ " img_count += 1\n",
1064
+ " print(f\"Copied {img_count} images\")\n",
1065
+ "\n",
1066
+ " # Convert and copy camera file to PINHOLE format\n",
1067
+ " print(\"Converting camera model to PINHOLE format...\")\n",
1068
+ " convert_cameras_to_pinhole(\n",
1069
+ " os.path.join(colmap_model_dir, 'cameras.txt'),\n",
1070
+ " f\"{data_dir}/sparse/0/cameras.txt\"\n",
1071
+ " )\n",
1072
+ "\n",
1073
+ " # Copy other files\n",
1074
+ " for filename in ['images.txt', 'points3D.txt']:\n",
1075
+ " src = os.path.join(colmap_model_dir, filename)\n",
1076
+ " dst = f\"{data_dir}/sparse/0/{filename}\"\n",
1077
+ " if os.path.exists(src):\n",
1078
+ " shutil.copy(src, dst)\n",
1079
+ " print(f\"Copied {filename}\")\n",
1080
+ " else:\n",
1081
+ " print(f\"Warning: {filename} not found\")\n",
1082
+ "\n",
1083
+ " print(f\"Data preparation complete: {data_dir}\")\n",
1084
+ " return data_dir\n",
1085
+ "\n",
1086
+ "\n",
1087
+ "\n",
1088
+ "###############################################################\n",
1089
+ "\n",
1090
+ "# 変更後 (2DGS) - 正則化パラメータを追加\n",
1091
+ "def train_gaussian_splatting(data_dir, iterations=7000,\n",
1092
+ " lambda_normal=0.05,\n",
1093
+ " lambda_distortion=0,\n",
1094
+ " depth_ratio=0):\n",
1095
+ " \"\"\"\n",
1096
+ " 2DGS用のトレーニング関数\n",
1097
+ "\n",
1098
+ " Args:\n",
1099
+ " lambda_normal: 法線一貫性の重み (デフォルト: 0.05)\n",
1100
+ " lambda_distortion: 深度歪みの重み (デフォルト: 0)\n",
1101
+ " depth_ratio: 0=平均深度, 1=中央値深度 (デフォルト: 0)\n",
1102
+ " \"\"\"\n",
1103
+ " model_path = f\"{WORK_DIR}/output/video\"\n",
1104
+ " cmd = [\n",
1105
+ " sys.executable, 'train.py',\n",
1106
+ " '-s', data_dir,\n",
1107
+ " '-m', model_path,\n",
1108
+ " '--iterations', str(iterations),\n",
1109
+ " '--lambda_normal', str(lambda_normal),\n",
1110
+ " '--lambda_distortion', str(lambda_distortion),\n",
1111
+ " '--depth_ratio', str(depth_ratio),\n",
1112
+ " '--eval'\n",
1113
+ " ]\n",
1114
+ " subprocess.run(cmd, cwd=WORK_DIR, check=True)\n",
1115
+ " return model_path\n",
1116
+ "\n",
1117
+ "\n",
1118
+ "\n",
1119
+ "# 2DGSではメッシュ抽出オプションが追加されています\n",
1120
+ "def render_video_and_mesh(model_path, output_video_path, iteration=7000,\n",
1121
+ " extract_mesh=True, unbounded=False, mesh_res=1024):\n",
1122
+ " \"\"\"\n",
1123
+ " 2DGS用のレンダリングとメッシュ抽出\n",
1124
+ "\n",
1125
+ " Args:\n",
1126
+ " extract_mesh: メッシュを抽出するか\n",
1127
+ " unbounded: 境界なしメッシュ抽出を使用するか\n",
1128
+ " mesh_res: メッシュ解像度\n",
1129
+ " \"\"\"\n",
1130
+ " # 通常のレンダリング\n",
1131
+ " cmd = [\n",
1132
+ " sys.executable, 'render.py',\n",
1133
+ " '-m', model_path,\n",
1134
+ " '--iteration', str(iteration)\n",
1135
+ " ]\n",
1136
+ "\n",
1137
+ " # メッシュ抽出オプション追加\n",
1138
+ " if extract_mesh:\n",
1139
+ " if unbounded:\n",
1140
+ " cmd.extend(['--unbounded', '--mesh_res', str(mesh_res)])\n",
1141
+ " cmd.extend(['--skip_test', '--skip_train'])\n",
1142
+ "\n",
1143
+ " subprocess.run(cmd, cwd=WORK_DIR, check=True)\n",
1144
+ "\n",
1145
+ " # Find the rendering directory\n",
1146
+ " possible_dirs = [\n",
1147
+ " f\"{model_path}/test/ours_{iteration}/renders\",\n",
1148
+ " f\"{model_path}/train/ours_{iteration}/renders\",\n",
1149
+ " ]\n",
1150
+ "\n",
1151
+ " render_dir = None\n",
1152
+ " for test_dir in possible_dirs:\n",
1153
+ " if os.path.exists(test_dir):\n",
1154
+ " render_dir = test_dir\n",
1155
+ " print(f\"Rendering directory found: {render_dir}\")\n",
1156
+ " break\n",
1157
+ "\n",
1158
+ " if render_dir and os.path.exists(render_dir):\n",
1159
+ " render_imgs = sorted([f for f in os.listdir(render_dir) if f.endswith('.png')])\n",
1160
+ "\n",
1161
+ " if render_imgs:\n",
1162
+ " print(f\"Found {len(render_imgs)} rendered images\")\n",
1163
+ "\n",
1164
+ " # Create video with ffmpeg\n",
1165
+ " subprocess.run([\n",
1166
+ " 'ffmpeg', '-y',\n",
1167
+ " '-framerate', '30',\n",
1168
+ " '-pattern_type', 'glob',\n",
1169
+ " '-i', f\"{render_dir}/*.png\",\n",
1170
+ " '-c:v', 'libx264',\n",
1171
+ " '-pix_fmt', 'yuv420p',\n",
1172
+ " '-crf', '18',\n",
1173
+ " output_video_path\n",
1174
+ " ], check=True)\n",
1175
+ "\n",
1176
+ " print(f\"Video saved: {output_video_path}\")\n",
1177
+ " return True\n",
1178
+ "\n",
1179
+ " print(\"Error: Rendering directory not found\")\n",
1180
+ " return False\n",
1181
+ "\n",
1182
+ "###############################################################\n",
1183
+ "\n",
1184
+ "\n",
1185
+ "def create_gif(video_path, gif_path):\n",
1186
+ " \"\"\"Create GIF from MP4\"\"\"\n",
1187
+ " print(\"Creating animated GIF...\")\n",
1188
+ "\n",
1189
+ " subprocess.run([\n",
1190
+ " 'ffmpeg', '-y',\n",
1191
+ " '-i', video_path,\n",
1192
+ " '-vf', 'setpts=8*PTS,fps=10,scale=720:-1:flags=lanczos',\n",
1193
+ " '-loop', '0',\n",
1194
+ " gif_path\n",
1195
+ " ], check=True)\n",
1196
+ "\n",
1197
+ " if os.path.exists(gif_path):\n",
1198
+ " size_mb = os.path.getsize(gif_path) / (1024 * 1024)\n",
1199
+ " print(f\"GIF creation complete: {gif_path} ({size_mb:.2f} MB)\")\n",
1200
+ " return True\n",
1201
+ "\n",
1202
+ " return False"
1203
+ ]
1204
+ },
1205
+ {
1206
+ "cell_type": "code",
1207
+ "source": [],
1208
+ "metadata": {
1209
+ "id": "YtqhBP4T3jEH"
1210
+ },
1211
+ "id": "YtqhBP4T3jEH",
1212
+ "execution_count": null,
1213
+ "outputs": []
1214
+ },
1215
+ {
1216
+ "cell_type": "code",
1217
+ "source": [
1218
+ "def main_pipeline(image_dir, output_dir, square_size=1024, max_images=100):\n",
1219
+ " \"\"\"Main execution function\"\"\"\n",
1220
+ " try:\n",
1221
+ " # Step 1: 画像の正規化と前処理\n",
1222
+ " print(\"=\"*60)\n",
1223
+ " print(\"Step 1: Normalizing and preprocessing images\")\n",
1224
+ " print(\"=\"*60)\n",
1225
+ "\n",
1226
+ " frame_dir = os.path.join(COLMAP_DIR, \"images\")\n",
1227
+ " os.makedirs(frame_dir, exist_ok=True)\n",
1228
+ "\n",
1229
+ " # 画像を正規化して直接COLMAPのディレクトリに保存\n",
1230
+ " num_processed = normalize_image_sizes_biplet(\n",
1231
+ " input_dir=image_dir,\n",
1232
+ " output_dir=frame_dir, # 直接colmap/imagesに保存\n",
1233
+ " size=square_size,\n",
1234
+ " max_images=max_images\n",
1235
+ " )\n",
1236
+ "\n",
1237
+ " print(f\"Processed {num_processed} images\")\n",
1238
+ "\n",
1239
+ " # Step 2: Estimate Camera Info with COLMAP\n",
1240
+ " print(\"=\"*60)\n",
1241
+ " print(\"Step 2: Running COLMAP reconstruction\")\n",
1242
+ " print(\"=\"*60)\n",
1243
+ " colmap_model_dir = run_colmap_reconstruction(frame_dir, COLMAP_DIR)\n",
1244
+ "\n",
1245
+ " # Step 3: Prepare Data for Gaussian Splatting\n",
1246
+ " print(\"=\"*60)\n",
1247
+ " print(\"Step 3: Preparing Gaussian Splatting data\")\n",
1248
+ " print(\"=\"*60)\n",
1249
+ " data_dir = prepare_gaussian_splatting_data(frame_dir, colmap_model_dir)\n",
1250
+ "\n",
1251
+ " # Step 4: Train Model\n",
1252
+ " print(\"=\"*60)\n",
1253
+ " print(\"Step 4: Training Gaussian Splatting model\")\n",
1254
+ " print(\"=\"*60)\n",
1255
+ " # 修正: frame_dir → data_dir\n",
1256
+ " model_path = train_gaussian_splatting(\n",
1257
+ " data_dir, # ← ここを修正!\n",
1258
+ " iterations=1000,\n",
1259
+ " lambda_normal=0.05,\n",
1260
+ " lambda_distortion=0,\n",
1261
+ " depth_ratio=0\n",
1262
+ " )\n",
1263
+ "\n",
1264
+ " print(f\"Model trained at: {model_path}\")\n",
1265
+ "\n",
1266
+ " # Step 5: Render Video\n",
1267
+ " print(\"=\"*60)\n",
1268
+ " print(\"Step 5: Rendering video\")\n",
1269
+ " print(\"=\"*60)\n",
1270
+ " os.makedirs(OUTPUT_DIR, exist_ok=True)\n",
1271
+ " output_video = os.path.join(OUTPUT_DIR, \"gaussian_splatting_video.mp4\")\n",
1272
+ "\n",
1273
+ " # 修正: output_video_path → output_video\n",
1274
+ " success = render_video_and_mesh(\n",
1275
+ " model_path,\n",
1276
+ " output_video, # ← ここを修正!\n",
1277
+ " iteration=1000,\n",
1278
+ " extract_mesh=True, # メッシュ抽出を有効化\n",
1279
+ " unbounded=True, # 境界なしメッシュ(推奨)\n",
1280
+ " mesh_res=1024\n",
1281
+ " )\n",
1282
+ "\n",
1283
+ " if success:\n",
1284
+ " print(\"=\"*60)\n",
1285
+ " print(f\"Success! Video generation complete: {output_video}\")\n",
1286
+ " print(\"=\"*60)\n",
1287
+ "\n",
1288
+ " # Create GIF\n",
1289
+ " output_gif = os.path.join(OUTPUT_DIR, \"gaussian_splatting_video.gif\")\n",
1290
+ " create_gif(output_video, output_gif)\n",
1291
+ "\n",
1292
+ " # Display result\n",
1293
+ " from IPython.display import Image, display\n",
1294
+ " display(Image(open(output_gif, 'rb').read()))\n",
1295
+ "\n",
1296
+ " return output_video, output_gif\n",
1297
+ " else:\n",
1298
+ " print(\"Warning: Rendering complete, but video was not generated\")\n",
1299
+ " return None, None\n",
1300
+ "\n",
1301
+ " except Exception as e:\n",
1302
+ " print(f\"Error: {str(e)}\")\n",
1303
+ " import traceback\n",
1304
+ " traceback.print_exc()\n",
1305
+ " return None, None\n",
1306
+ "\n",
1307
+ "\n",
1308
+ "if __name__ == \"__main__\":\n",
1309
+ " IMAGE_DIR = \"/content/drive/MyDrive/your_folder/fountain100\"\n",
1310
+ " OUTPUT_DIR = \"/content/output\"\n",
1311
+ " COLMAP_DIR = \"/content/colmap_workspace\"\n",
1312
+ "\n",
1313
+ " video_path, gif_path = main_pipeline(\n",
1314
+ " image_dir=IMAGE_DIR,\n",
1315
+ " output_dir=OUTPUT_DIR,\n",
1316
+ " square_size=1024,\n",
1317
+ " max_images=20\n",
1318
+ " )\n",
1319
+ "\n",
1320
+ " if video_path:\n",
1321
+ " print(f\"\\n✅ Success!\")\n",
1322
+ " print(f\"Video: {video_path}\")\n",
1323
+ " print(f\"GIF: {gif_path}\")\n",
1324
+ " else:\n",
1325
+ " print(\"\\n❌ Pipeline failed\")"
1326
+ ],
1327
+ "metadata": {
1328
+ "id": "fya3kv62NXM-"
1329
+ },
1330
+ "id": "fya3kv62NXM-",
1331
+ "execution_count": null,
1332
+ "outputs": []
1333
+ },
1334
+ {
1335
+ "cell_type": "markdown",
1336
+ "id": "e17ec719",
1337
+ "metadata": {
1338
+ "papermill": {
1339
+ "duration": 0.49801,
1340
+ "end_time": "2026-01-11T00:00:18.165833",
1341
+ "exception": false,
1342
+ "start_time": "2026-01-11T00:00:17.667823",
1343
+ "status": "completed"
1344
+ },
1345
+ "tags": [],
1346
+ "id": "e17ec719"
1347
+ },
1348
+ "source": []
1349
+ },
1350
+ {
1351
+ "cell_type": "markdown",
1352
+ "id": "38b3974c",
1353
+ "metadata": {
1354
+ "papermill": {
1355
+ "duration": 0.427583,
1356
+ "end_time": "2026-01-11T00:00:19.008387",
1357
+ "exception": false,
1358
+ "start_time": "2026-01-11T00:00:18.580804",
1359
+ "status": "completed"
1360
+ },
1361
+ "tags": [],
1362
+ "id": "38b3974c"
1363
+ },
1364
+ "source": []
1365
+ }
1366
+ ],
1367
+ "metadata": {
1368
+ "kaggle": {
1369
+ "accelerator": "nvidiaTeslaT4",
1370
+ "dataSources": [
1371
+ {
1372
+ "databundleVersionId": 5447706,
1373
+ "sourceId": 49349,
1374
+ "sourceType": "competition"
1375
+ },
1376
+ {
1377
+ "datasetId": 1429416,
1378
+ "sourceId": 14451718,
1379
+ "sourceType": "datasetVersion"
1380
+ }
1381
+ ],
1382
+ "dockerImageVersionId": 31090,
1383
+ "isGpuEnabled": true,
1384
+ "isInternetEnabled": true,
1385
+ "language": "python",
1386
+ "sourceType": "notebook"
1387
+ },
1388
+ "kernelspec": {
1389
+ "display_name": "Python 3",
1390
+ "name": "python3"
1391
+ },
1392
+ "language_info": {
1393
+ "codemirror_mode": {
1394
+ "name": "ipython",
1395
+ "version": 3
1396
+ },
1397
+ "file_extension": ".py",
1398
+ "mimetype": "text/x-python",
1399
+ "name": "python",
1400
+ "nbconvert_exporter": "python",
1401
+ "pygments_lexer": "ipython3",
1402
+ "version": "3.11.13"
1403
+ },
1404
+ "papermill": {
1405
+ "default_parameters": {},
1406
+ "duration": 20573.990788,
1407
+ "end_time": "2026-01-11T00:00:22.081506",
1408
+ "environment_variables": {},
1409
+ "exception": null,
1410
+ "input_path": "__notebook__.ipynb",
1411
+ "output_path": "__notebook__.ipynb",
1412
+ "parameters": {},
1413
+ "start_time": "2026-01-10T18:17:28.090718",
1414
+ "version": "2.6.0"
1415
+ },
1416
+ "colab": {
1417
+ "provenance": [],
1418
+ "gpuType": "T4"
1419
+ },
1420
+ "accelerator": "GPU"
1421
+ },
1422
+ "nbformat": 4,
1423
+ "nbformat_minor": 5
1424
+ }