stpete2 commited on
Commit
3ba8c14
·
verified ·
1 Parent(s): 8bd3422

Delete biplet_colmap_2dgs_colab_07.ipynb

Browse files
Files changed (1) hide show
  1. biplet_colmap_2dgs_colab_07.ipynb +0 -1446
biplet_colmap_2dgs_colab_07.ipynb DELETED
@@ -1,1446 +0,0 @@
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
- }