stpete2 commited on
Commit
826b93d
·
verified ·
1 Parent(s): 21be490

Delete biplet_colmap_2dgs_colab_05.ipynb

Browse files
Files changed (1) hide show
  1. biplet_colmap_2dgs_colab_05.ipynb +0 -1308
biplet_colmap_2dgs_colab_05.ipynb DELETED
@@ -1,1308 +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": "471c818a-8d0c-40f9-a1a2-b57eade5b743"
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": null,
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": "dbbb2f60-b066-4efe-bc19-1668480554d6",
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
- "Running: git clone --recursive https://github.com/hbb1/2d-gaussian-splatting.git gaussian-splatting\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: Build Gaussian Splatting submodules\n",
169
- "======================================================================\n",
170
- "\n",
171
- "📦 Processing diff-surfel-rasterization...\n",
172
- " ✓ diff-surfel-rasterization already exists.\n",
173
- " > Compiling and Installing diff-surfel-rasterization...\n",
174
- "Running: /usr/bin/python3 setup.py install\n",
175
- "✅ Successfully built diff-surfel-rasterization\n",
176
- "\n",
177
- "📦 Processing simple-knn...\n",
178
- " ✓ simple-knn already exists.\n",
179
- " > Compiling and Installing simple-knn...\n",
180
- "Running: /usr/bin/python3 setup.py install\n"
181
- ]
182
- }
183
- ],
184
- "source": [
185
- "def run_cmd(cmd, check=True, capture=False, cwd=None): # ← cwd=None を追加\n",
186
- " \"\"\"Run command with better error handling\"\"\"\n",
187
- " print(f\"Running: {' '.join(cmd)}\")\n",
188
- " result = subprocess.run(\n",
189
- " cmd,\n",
190
- " capture_output=capture,\n",
191
- " text=True,\n",
192
- " check=False,\n",
193
- " cwd=cwd # ← ここに渡す\n",
194
- " )\n",
195
- " if check and result.returncode != 0:\n",
196
- " print(f\"❌ Command failed with code {result.returncode}\")\n",
197
- " if capture:\n",
198
- " print(f\"STDOUT: {result.stdout}\")\n",
199
- " print(f\"STDERR: {result.stderr}\")\n",
200
- " return result\n",
201
- "\n",
202
- "\n",
203
- "def setup_environment():\n",
204
- " \"\"\"\n",
205
- " Colab environment setup for Gaussian Splatting + LightGlue + pycolmap\n",
206
- " Python 3.12 compatible version (v8)\n",
207
- " \"\"\"\n",
208
- "\n",
209
- " print(\"🚀 Setting up COLAB environment (v8 - Python 3.12 compatible)\")\n",
210
- "\n",
211
- " WORK_DIR = \"gaussian-splatting\"\n",
212
- "\n",
213
- " # =====================================================================\n",
214
- " # STEP 0: NumPy FIX (Python 3.12 compatible)\n",
215
- " # =====================================================================\n",
216
- " print(\"\\n\" + \"=\"*70)\n",
217
- " print(\"STEP 0: Fix NumPy (Python 3.12 compatible)\")\n",
218
- " print(\"=\"*70)\n",
219
- "\n",
220
- " # Python 3.12 requires numpy >= 1.26\n",
221
- " run_cmd([sys.executable, \"-m\", \"pip\", \"uninstall\", \"-y\", \"numpy\"])\n",
222
- " run_cmd([sys.executable, \"-m\", \"pip\", \"install\", \"numpy==1.26.4\"])\n",
223
- "\n",
224
- " # sanity check\n",
225
- " run_cmd([sys.executable, \"-c\", \"import numpy; print('NumPy:', numpy.__version__)\"])\n",
226
- "\n",
227
- " # =====================================================================\n",
228
- " # STEP 1: System packages (Colab)\n",
229
- " # =====================================================================\n",
230
- " print(\"\\n\" + \"=\"*70)\n",
231
- " print(\"STEP 1: System packages\")\n",
232
- " print(\"=\"*70)\n",
233
- "\n",
234
- " run_cmd([\"apt-get\", \"update\", \"-qq\"])\n",
235
- " run_cmd([\n",
236
- " \"apt-get\", \"install\", \"-y\", \"-qq\",\n",
237
- " \"colmap\",\n",
238
- " \"build-essential\",\n",
239
- " \"cmake\",\n",
240
- " \"git\",\n",
241
- " \"libopenblas-dev\",\n",
242
- " \"xvfb\"\n",
243
- " ])\n",
244
- "\n",
245
- " # virtual display (COLMAP / OpenCV safety)\n",
246
- " os.environ[\"QT_QPA_PLATFORM\"] = \"offscreen\"\n",
247
- " os.environ[\"DISPLAY\"] = \":99\"\n",
248
- " subprocess.Popen(\n",
249
- " [\"Xvfb\", \":99\", \"-screen\", \"0\", \"1024x768x24\"],\n",
250
- " stdout=subprocess.DEVNULL,\n",
251
- " stderr=subprocess.DEVNULL\n",
252
- " )\n",
253
- "\n",
254
- " # =====================================================================\n",
255
- " # STEP 2: Clone 2D Gaussian Splatting\n",
256
- " # =====================================================================\n",
257
- " print(\"\\n\" + \"=\"*70)\n",
258
- " print(\"STEP 2: Clone Gaussian Splatting\")\n",
259
- " print(\"=\"*70)\n",
260
- "\n",
261
- " if not os.path.exists(WORK_DIR):\n",
262
- " run_cmd([\n",
263
- " \"git\", \"clone\", \"--recursive\",\n",
264
- " \"https://github.com/hbb1/2d-gaussian-splatting.git\",\n",
265
- " WORK_DIR\n",
266
- " ])\n",
267
- " else:\n",
268
- " print(\"✓ Repository already exists\")\n",
269
- "\n",
270
- " # =====================================================================\n",
271
- " # STEP 3: Python packages (FIXED ORDER & VERSIONS)\n",
272
- " # =====================================================================\n",
273
- " print(\"\\n\" + \"=\"*70)\n",
274
- " print(\"STEP 3: Python packages (VERBOSE MODE)\")\n",
275
- " print(\"=\"*70)\n",
276
- "\n",
277
- " # ---- PyTorch (Colab CUDA対応) ----\n",
278
- " print(\"\\n📦 Installing PyTorch...\")\n",
279
- " run_cmd([\n",
280
- " sys.executable, \"-m\", \"pip\", \"install\",\n",
281
- " \"torch\", \"torchvision\", \"torchaudio\"\n",
282
- " ])\n",
283
- "\n",
284
- " # ---- Core utils ----\n",
285
- " print(\"\\n📦 Installing core utilities...\")\n",
286
- " run_cmd([\n",
287
- " sys.executable, \"-m\", \"pip\", \"install\",\n",
288
- " \"opencv-python\",\n",
289
- " \"pillow\",\n",
290
- " \"imageio\",\n",
291
- " \"imageio-ffmpeg\",\n",
292
- " \"plyfile\",\n",
293
- " \"tqdm\",\n",
294
- " \"tensorboard\"\n",
295
- " ])\n",
296
- "\n",
297
- " # ---- transformers (NumPy 1.26 compatible) ----\n",
298
- " print(\"\\n📦 Installing transformers (NumPy 1.26 compatible)...\")\n",
299
- " # Install transformers with proper dependencies\n",
300
- " run_cmd([\n",
301
- " sys.executable, \"-m\", \"pip\", \"install\",\n",
302
- " \"transformers==4.40.0\"\n",
303
- " ])\n",
304
- "\n",
305
- " # ---- LightGlue stack (GITHUB INSTALL) ----\n",
306
- " print(\"\\n📦 Installing LightGlue stack...\")\n",
307
- "\n",
308
- " # Install kornia first\n",
309
- " run_cmd([sys.executable, \"-m\", \"pip\", \"install\", \"kornia\"])\n",
310
- "\n",
311
- " # Install h5py (sometimes needed)\n",
312
- " run_cmd([sys.executable, \"-m\", \"pip\", \"install\", \"h5py\"])\n",
313
- "\n",
314
- " # Install matplotlib (LightGlue dependency)\n",
315
- " run_cmd([sys.executable, \"-m\", \"pip\", \"install\", \"matplotlib\"])\n",
316
- "\n",
317
- " # Install pycolmap\n",
318
- " run_cmd([sys.executable, \"-m\", \"pip\", \"install\", \"pycolmap\"])\n",
319
- "\n",
320
- "\n",
321
- " # =====================================================================\n",
322
- " # STEP 4: Build 2D GS submodules (確実な方法)\n",
323
- " # =====================================================================\n",
324
- " print(\"\\n\" + \"=\"*70)\n",
325
- " print(\"STEP 4: Build Gaussian Splatting submodules\")\n",
326
- " print(\"=\"*70)\n",
327
- "\n",
328
- " # クローン先とリポジトリURLの定義\n",
329
- " submodules = [\n",
330
- " {\n",
331
- " \"path\": os.path.join(WORK_DIR, \"submodules\", \"diff-surfel-rasterization\"),\n",
332
- " \"url\": \"https://github.com/hbb1/diff-surfel-rasterization.git\"\n",
333
- " },\n",
334
- " {\n",
335
- " \"path\": os.path.join(WORK_DIR, \"submodules\", \"simple-knn\"),\n",
336
- " \"url\": \"https://github.com/tztechno/simple-knn.git\"\n",
337
- " }\n",
338
- " ]\n",
339
- "\n",
340
- " for submodule in submodules:\n",
341
- " path = submodule[\"path\"]\n",
342
- " url = submodule[\"url\"]\n",
343
- " name = os.path.basename(path)\n",
344
- "\n",
345
- " print(f\"\\n📦 Processing {name}...\")\n",
346
- "\n",
347
- " # 1. git clone (ディレクトリがない場合のみ)\n",
348
- " if not os.path.exists(path):\n",
349
- " print(f\" > Cloning {url}...\")\n",
350
- " # 親ディレクトリが存在することを確認\n",
351
- " os.makedirs(os.path.dirname(path), exist_ok=True)\n",
352
- " run_cmd([\"git\", \"clone\", url, path])\n",
353
- " else:\n",
354
- " print(f\" ✓ {name} already exists.\")\n",
355
- "\n",
356
- " # 2. setup.py install (コンパイル)\n",
357
- " print(f\" > Compiling and Installing {name}...\")\n",
358
- " # 捕捉してエラーメッセージを見やすくする\n",
359
- " result = run_cmd(\n",
360
- " [sys.executable, \"setup.py\", \"install\"],\n",
361
- " cwd=path,\n",
362
- " check=False, # エラーでも止めない\n",
363
- " capture=True\n",
364
- " )\n",
365
- "\n",
366
- " if result.returncode != 0:\n",
367
- " print(f\"❌ Failed to build {name}\")\n",
368
- " print(\"--- STDERR ---\")\n",
369
- " print(result.stderr)\n",
370
- " else:\n",
371
- " print(f\"✅ Successfully built {name}\")\n",
372
- "\n",
373
- " # =====================================================================\n",
374
- " # STEP 5: Detailed Verification\n",
375
- " # =====================================================================\n",
376
- " print(\"\\n\" + \"=\"*70)\n",
377
- " print(\"STEP 5: Detailed Verification\")\n",
378
- " print(\"=\"*70)\n",
379
- "\n",
380
- " # NumPy (verify version first)\n",
381
- " print(\"\\n🔍 Testing NumPy...\")\n",
382
- " try:\n",
383
- " import numpy as np\n",
384
- " print(f\" ✓ NumPy: {np.__version__}\")\n",
385
- " except Exception as e:\n",
386
- " print(f\" ❌ NumPy failed: {e}\")\n",
387
- "\n",
388
- " # PyTorch\n",
389
- " print(\"\\n🔍 Testing PyTorch...\")\n",
390
- " try:\n",
391
- " import torch\n",
392
- " print(f\" ✓ PyTorch: {torch.__version__}\")\n",
393
- " print(f\" ✓ CUDA available: {torch.cuda.is_available()}\")\n",
394
- " if torch.cuda.is_available():\n",
395
- " print(f\" ✓ CUDA version: {torch.version.cuda}\")\n",
396
- " except Exception as e:\n",
397
- " print(f\" ❌ PyTorch failed: {e}\")\n",
398
- "\n",
399
- " # transformers\n",
400
- " print(\"\\n🔍 Testing transformers...\")\n",
401
- " try:\n",
402
- " import transformers\n",
403
- " print(f\" ✓ transformers version: {transformers.__version__}\")\n",
404
- " from transformers import AutoModel\n",
405
- " print(f\" ✓ AutoModel import: OK\")\n",
406
- " except Exception as e:\n",
407
- " print(f\" ❌ transformers failed: {e}\")\n",
408
- " print(f\" Attempting detailed diagnosis...\")\n",
409
- " result = run_cmd([\n",
410
- " sys.executable, \"-c\",\n",
411
- " \"import transformers; print(transformers.__version__)\"\n",
412
- " ], capture=True)\n",
413
- " print(f\" Output: {result.stdout}\")\n",
414
- " print(f\" Error: {result.stderr}\")\n",
415
- "\n",
416
- " '''\n",
417
- " # LightGlue\n",
418
- " print(\"\\n🔍 Testing LightGlue...\")\n",
419
- " try:\n",
420
- " from lightglue import LightGlue, ALIKED\n",
421
- " print(f\" ✓ LightGlue: OK\")\n",
422
- " print(f\" ✓ ALIKED: OK\")\n",
423
- " except Exception as e:\n",
424
- " print(f\" ❌ LightGlue failed: {e}\")\n",
425
- " print(f\" Attempting detailed diagnosis...\")\n",
426
- " result = run_cmd([\n",
427
- " sys.executable, \"-c\",\n",
428
- " \"from lightglue import LightGlue\"\n",
429
- " ], capture=True)\n",
430
- " print(f\" Output: {result.stdout}\")\n",
431
- " print(f\" Error: {result.stderr}\")\n",
432
- " '''\n",
433
- "\n",
434
- " # pycolmap\n",
435
- " print(\"\\n🔍 Testing pycolmap...\")\n",
436
- " try:\n",
437
- " import pycolmap\n",
438
- " print(f\" ✓ pycolmap: OK\")\n",
439
- " except Exception as e:\n",
440
- " print(f\" ❌ pycolmap failed: {e}\")\n",
441
- "\n",
442
- " # kornia\n",
443
- " print(\"\\n🔍 Testing kornia...\")\n",
444
- " try:\n",
445
- " import kornia\n",
446
- " print(f\" ✓ kornia: {kornia.__version__}\")\n",
447
- " except Exception as e:\n",
448
- " print(f\" ❌ kornia failed: {e}\")\n",
449
- "\n",
450
- " print(\"\\n\" + \"=\"*70)\n",
451
- " print(\"✅ SETUP COMPLETE\")\n",
452
- " print(\"=\"*70)\n",
453
- " print(f\"Working dir: {WORK_DIR}\")\n",
454
- "\n",
455
- " return WORK_DIR\n",
456
- "\n",
457
- "\n",
458
- "if __name__ == \"__main__\":\n",
459
- " setup_environment()"
460
- ]
461
- },
462
- {
463
- "cell_type": "markdown",
464
- "source": [],
465
- "metadata": {
466
- "id": "RsuNog5yYnpD"
467
- },
468
- "id": "RsuNog5yYnpD"
469
- },
470
- {
471
- "cell_type": "markdown",
472
- "source": [],
473
- "metadata": {
474
- "id": "IHxIK-mHYn56"
475
- },
476
- "id": "IHxIK-mHYn56"
477
- },
478
- {
479
- "cell_type": "code",
480
- "source": [],
481
- "metadata": {
482
- "id": "impNUWB3YoLf"
483
- },
484
- "id": "impNUWB3YoLf",
485
- "execution_count": null,
486
- "outputs": []
487
- },
488
- {
489
- "cell_type": "code",
490
- "source": [],
491
- "metadata": {
492
- "id": "5VHWGkbIYoXH"
493
- },
494
- "id": "5VHWGkbIYoXH",
495
- "execution_count": null,
496
- "outputs": []
497
- },
498
- {
499
- "cell_type": "code",
500
- "source": [
501
- "!nvcc --version\n",
502
- "import torch\n",
503
- "print(torch.__version__)\n",
504
- "print(torch.version.cuda)"
505
- ],
506
- "metadata": {
507
- "id": "Ev9PEUdtpEAx"
508
- },
509
- "id": "Ev9PEUdtpEAx",
510
- "execution_count": null,
511
- "outputs": []
512
- },
513
- {
514
- "cell_type": "code",
515
- "execution_count": null,
516
- "id": "b8690389",
517
- "metadata": {
518
- "execution": {
519
- "iopub.execute_input": "2026-01-10T18:22:43.739411Z",
520
- "iopub.status.busy": "2026-01-10T18:22:43.738855Z",
521
- "iopub.status.idle": "2026-01-10T18:22:43.755664Z",
522
- "shell.execute_reply": "2026-01-10T18:22:43.754865Z"
523
- },
524
- "papermill": {
525
- "duration": 0.027297,
526
- "end_time": "2026-01-10T18:22:43.756758",
527
- "exception": false,
528
- "start_time": "2026-01-10T18:22:43.729461",
529
- "status": "completed"
530
- },
531
- "tags": [],
532
- "id": "b8690389"
533
- },
534
- "outputs": [],
535
- "source": [
536
- "import os\n",
537
- "import glob\n",
538
- "import cv2\n",
539
- "import numpy as np\n",
540
- "from PIL import Image\n",
541
- "\n",
542
- "# =========================================================\n",
543
- "# Utility: aspect ratio preserved + black padding\n",
544
- "# =========================================================\n",
545
- "\n",
546
- "def normalize_image_sizes_biplet(input_dir, output_dir=None, size=1024, max_images=None):\n",
547
- " \"\"\"\n",
548
- " Generates two square crops (Left & Right or Top & Bottom)\n",
549
- " from each image in a directory and returns the output directory\n",
550
- " and the list of generated file paths.\n",
551
- "\n",
552
- " Args:\n",
553
- " input_dir: Input directory containing source images\n",
554
- " output_dir: Output directory for processed images\n",
555
- " size: Target square size (default: 1024)\n",
556
- " max_images: Maximum number of SOURCE images to process (default: None = all images)\n",
557
- " \"\"\"\n",
558
- " if output_dir is None:\n",
559
- " output_dir = 'output/images_biplet'\n",
560
- " os.makedirs(output_dir, exist_ok=True)\n",
561
- "\n",
562
- " print(f\"--- Step 1: Biplet-Square Normalization ---\")\n",
563
- " print(f\"Generating 2 cropped squares (Left/Right or Top/Bottom) for each image...\")\n",
564
- " print()\n",
565
- "\n",
566
- " generated_paths = []\n",
567
- " converted_count = 0\n",
568
- " size_stats = {}\n",
569
- "\n",
570
- " # Sort for consistent processing order\n",
571
- " image_files = sorted([f for f in os.listdir(input_dir)\n",
572
- " if f.lower().endswith(('.jpg', '.jpeg', '.png'))])\n",
573
- "\n",
574
- " # ★ max_images で元画像数を制限\n",
575
- " if max_images is not None:\n",
576
- " image_files = image_files[:max_images]\n",
577
- " print(f\"Processing limited to {max_images} source images (will generate {max_images * 2} cropped images)\")\n",
578
- "\n",
579
- " for img_file in image_files:\n",
580
- " input_path = os.path.join(input_dir, img_file)\n",
581
- " try:\n",
582
- " img = Image.open(input_path)\n",
583
- " original_size = img.size\n",
584
- "\n",
585
- " # Tracking original aspect ratios\n",
586
- " size_key = f\"{original_size[0]}x{original_size[1]}\"\n",
587
- " size_stats[size_key] = size_stats.get(size_key, 0) + 1\n",
588
- "\n",
589
- " # Generate 2 crops using the helper function\n",
590
- " crops = generate_two_crops(img, size)\n",
591
- " base_name, ext = os.path.splitext(img_file)\n",
592
- "\n",
593
- " for mode, cropped_img in crops.items():\n",
594
- " output_path = os.path.join(output_dir, f\"{base_name}_{mode}{ext}\")\n",
595
- " cropped_img.save(output_path, quality=95)\n",
596
- " generated_paths.append(output_path)\n",
597
- "\n",
598
- " converted_count += 1\n",
599
- " print(f\" ✓ {img_file}: {original_size} → 2 square images generated\")\n",
600
- "\n",
601
- " except Exception as e:\n",
602
- " print(f\" ✗ Error processing {img_file}: {e}\")\n",
603
- "\n",
604
- " print(f\"\\nProcessing complete: {converted_count} source images processed\")\n",
605
- " print(f\"Total output images: {len(generated_paths)}\")\n",
606
- " print(f\"Original size distribution: {size_stats}\")\n",
607
- "\n",
608
- " return output_dir, generated_paths\n",
609
- "\n",
610
- "\n",
611
- "def generate_two_crops(img, size):\n",
612
- " \"\"\"\n",
613
- " Crops the image into a square and returns 2 variations\n",
614
- " (Left/Right for landscape, Top/Bottom for portrait).\n",
615
- " \"\"\"\n",
616
- " width, height = img.size\n",
617
- " crop_size = min(width, height)\n",
618
- " crops = {}\n",
619
- "\n",
620
- " if width > height:\n",
621
- " # Landscape → Left & Right\n",
622
- " positions = {\n",
623
- " 'left': 0,\n",
624
- " 'right': width - crop_size\n",
625
- " }\n",
626
- " for mode, x_offset in positions.items():\n",
627
- " box = (x_offset, 0, x_offset + crop_size, crop_size)\n",
628
- " crops[mode] = img.crop(box).resize(\n",
629
- " (size, size),\n",
630
- " Image.Resampling.LANCZOS\n",
631
- " )\n",
632
- "\n",
633
- " else:\n",
634
- " # Portrait or Square → Top & Bottom\n",
635
- " positions = {\n",
636
- " 'top': 0,\n",
637
- " 'bottom': height - crop_size\n",
638
- " }\n",
639
- " for mode, y_offset in positions.items():\n",
640
- " box = (0, y_offset, crop_size, y_offset + crop_size)\n",
641
- " crops[mode] = img.crop(box).resize(\n",
642
- " (size, size),\n",
643
- " Image.Resampling.LANCZOS\n",
644
- " )\n",
645
- "\n",
646
- " return crops\n"
647
- ]
648
- },
649
- {
650
- "cell_type": "code",
651
- "execution_count": null,
652
- "id": "7acc20b6",
653
- "metadata": {
654
- "execution": {
655
- "iopub.execute_input": "2026-01-10T18:22:43.772525Z",
656
- "iopub.status.busy": "2026-01-10T18:22:43.772303Z",
657
- "iopub.status.idle": "2026-01-10T18:22:43.790574Z",
658
- "shell.execute_reply": "2026-01-10T18:22:43.789515Z"
659
- },
660
- "papermill": {
661
- "duration": 0.027612,
662
- "end_time": "2026-01-10T18:22:43.791681",
663
- "exception": false,
664
- "start_time": "2026-01-10T18:22:43.764069",
665
- "status": "completed"
666
- },
667
- "tags": [],
668
- "id": "7acc20b6"
669
- },
670
- "outputs": [],
671
- "source": [
672
- "def run_colmap_reconstruction(image_dir, colmap_dir):\n",
673
- " \"\"\"Estimate camera poses and 3D point cloud with COLMAP\"\"\"\n",
674
- " print(\"Running SfM reconstruction with COLMAP...\")\n",
675
- "\n",
676
- " database_path = os.path.join(colmap_dir, \"database.db\")\n",
677
- " sparse_dir = os.path.join(colmap_dir, \"sparse\")\n",
678
- " os.makedirs(sparse_dir, exist_ok=True)\n",
679
- "\n",
680
- " # Set environment variable\n",
681
- " env = os.environ.copy()\n",
682
- " env['QT_QPA_PLATFORM'] = 'offscreen'\n",
683
- "\n",
684
- " # Feature extraction\n",
685
- " print(\"1/4: Extracting features...\")\n",
686
- " subprocess.run([\n",
687
- " 'colmap', 'feature_extractor',\n",
688
- " '--database_path', database_path,\n",
689
- " '--image_path', image_dir,\n",
690
- " '--ImageReader.single_camera', '1',\n",
691
- " '--ImageReader.camera_model', 'OPENCV',\n",
692
- " '--SiftExtraction.use_gpu', '0' # Use CPU\n",
693
- " ], check=True, env=env)\n",
694
- "\n",
695
- " # Feature matching\n",
696
- " print(\"2/4: Matching features...\")\n",
697
- " subprocess.run([\n",
698
- " 'colmap', 'exhaustive_matcher', # Use sequential_matcher instead of exhaustive_matcher\n",
699
- " '--database_path', database_path,\n",
700
- " '--SiftMatching.use_gpu', '0' # Use CPU\n",
701
- " ], check=True, env=env)\n",
702
- "\n",
703
- " # Sparse reconstruction\n",
704
- " print(\"3/4: Sparse reconstruction...\")\n",
705
- " subprocess.run([\n",
706
- " 'colmap', 'mapper',\n",
707
- " '--database_path', database_path,\n",
708
- " '--image_path', image_dir,\n",
709
- " '--output_path', sparse_dir,\n",
710
- " '--Mapper.ba_global_max_num_iterations', '20', # Speed up\n",
711
- " '--Mapper.ba_local_max_num_iterations', '10'\n",
712
- " ], check=True, env=env)\n",
713
- "\n",
714
- " # Export to text format\n",
715
- " print(\"4/4: Exporting to text format...\")\n",
716
- " model_dir = os.path.join(sparse_dir, '0')\n",
717
- " if not os.path.exists(model_dir):\n",
718
- " # Use the first model found\n",
719
- " subdirs = [d for d in os.listdir(sparse_dir) if os.path.isdir(os.path.join(sparse_dir, d))]\n",
720
- " if subdirs:\n",
721
- " model_dir = os.path.join(sparse_dir, subdirs[0])\n",
722
- " else:\n",
723
- " raise FileNotFoundError(\"COLMAP reconstruction failed\")\n",
724
- "\n",
725
- " subprocess.run([\n",
726
- " 'colmap', 'model_converter',\n",
727
- " '--input_path', model_dir,\n",
728
- " '--output_path', model_dir,\n",
729
- " '--output_type', 'TXT'\n",
730
- " ], check=True, env=env)\n",
731
- "\n",
732
- " print(f\"COLMAP reconstruction complete: {model_dir}\")\n",
733
- " return model_dir\n",
734
- "\n",
735
- "\n",
736
- "def convert_cameras_to_pinhole(input_file, output_file):\n",
737
- " \"\"\"Convert camera model to PINHOLE format\"\"\"\n",
738
- " print(f\"Reading camera file: {input_file}\")\n",
739
- "\n",
740
- " with open(input_file, 'r') as f:\n",
741
- " lines = f.readlines()\n",
742
- "\n",
743
- " converted_count = 0\n",
744
- " with open(output_file, 'w') as f:\n",
745
- " for line in lines:\n",
746
- " if line.startswith('#') or line.strip() == '':\n",
747
- " f.write(line)\n",
748
- " else:\n",
749
- " parts = line.strip().split()\n",
750
- " if len(parts) >= 4:\n",
751
- " cam_id = parts[0]\n",
752
- " model = parts[1]\n",
753
- " width = parts[2]\n",
754
- " height = parts[3]\n",
755
- " params = parts[4:]\n",
756
- "\n",
757
- " # Convert to PINHOLE format\n",
758
- " if model == \"PINHOLE\":\n",
759
- " f.write(line)\n",
760
- " elif model == \"OPENCV\":\n",
761
- " # OPENCV: fx, fy, cx, cy, k1, k2, p1, p2\n",
762
- " fx = params[0]\n",
763
- " fy = params[1]\n",
764
- " cx = params[2]\n",
765
- " cy = params[3]\n",
766
- " f.write(f\"{cam_id} PINHOLE {width} {height} {fx} {fy} {cx} {cy}\\n\")\n",
767
- " converted_count += 1\n",
768
- " else:\n",
769
- " # Convert other models too\n",
770
- " fx = fy = max(float(width), float(height))\n",
771
- " cx = float(width) / 2\n",
772
- " cy = float(height) / 2\n",
773
- " f.write(f\"{cam_id} PINHOLE {width} {height} {fx} {fy} {cx} {cy}\\n\")\n",
774
- " converted_count += 1\n",
775
- " else:\n",
776
- " f.write(line)\n",
777
- "\n",
778
- " print(f\"Converted {converted_count} cameras to PINHOLE format\")\n",
779
- "\n",
780
- "\n",
781
- "def prepare_gaussian_splatting_data(image_dir, colmap_model_dir):\n",
782
- " \"\"\"Prepare data for Gaussian Splatting\"\"\"\n",
783
- " print(\"Preparing data for Gaussian Splatting...\")\n",
784
- "\n",
785
- " data_dir = f\"{WORK_DIR}/data/video\"\n",
786
- " os.makedirs(f\"{data_dir}/sparse/0\", exist_ok=True)\n",
787
- " os.makedirs(f\"{data_dir}/images\", exist_ok=True)\n",
788
- "\n",
789
- " # Copy images\n",
790
- " print(\"Copying images...\")\n",
791
- " img_count = 0\n",
792
- " for img_file in os.listdir(image_dir):\n",
793
- " if img_file.lower().endswith(('.jpg', '.jpeg', '.png')):\n",
794
- " shutil.copy(\n",
795
- " os.path.join(image_dir, img_file),\n",
796
- " f\"{data_dir}/images/{img_file}\"\n",
797
- " )\n",
798
- " img_count += 1\n",
799
- " print(f\"Copied {img_count} images\")\n",
800
- "\n",
801
- " # Convert and copy camera file to PINHOLE format\n",
802
- " print(\"Converting camera model to PINHOLE format...\")\n",
803
- " convert_cameras_to_pinhole(\n",
804
- " os.path.join(colmap_model_dir, 'cameras.txt'),\n",
805
- " f\"{data_dir}/sparse/0/cameras.txt\"\n",
806
- " )\n",
807
- "\n",
808
- " # Copy other files\n",
809
- " for filename in ['images.txt', 'points3D.txt']:\n",
810
- " src = os.path.join(colmap_model_dir, filename)\n",
811
- " dst = f\"{data_dir}/sparse/0/{filename}\"\n",
812
- " if os.path.exists(src):\n",
813
- " shutil.copy(src, dst)\n",
814
- " print(f\"Copied {filename}\")\n",
815
- " else:\n",
816
- " print(f\"Warning: {filename} not found\")\n",
817
- "\n",
818
- " print(f\"Data preparation complete: {data_dir}\")\n",
819
- " return data_dir\n",
820
- "\n",
821
- "def run_colmap_reconstruction(image_dir, colmap_dir):\n",
822
- " \"\"\"Estimate camera poses and 3D point cloud with COLMAP\"\"\"\n",
823
- " print(\"Running SfM reconstruction with COLMAP...\")\n",
824
- "\n",
825
- " database_path = os.path.join(colmap_dir, \"database.db\")\n",
826
- " sparse_dir = os.path.join(colmap_dir, \"sparse\")\n",
827
- " os.makedirs(sparse_dir, exist_ok=True)\n",
828
- "\n",
829
- " # Set environment variable\n",
830
- " env = os.environ.copy()\n",
831
- " env['QT_QPA_PLATFORM'] = 'offscreen'\n",
832
- "\n",
833
- " # Feature extraction\n",
834
- " print(\"1/4: Extracting features...\")\n",
835
- " subprocess.run([\n",
836
- " 'colmap', 'feature_extractor',\n",
837
- " '--database_path', database_path,\n",
838
- " '--image_path', image_dir,\n",
839
- " '--ImageReader.single_camera', '1',\n",
840
- " '--ImageReader.camera_model', 'OPENCV',\n",
841
- " '--SiftExtraction.use_gpu', '0' # Use CPU\n",
842
- " ], check=True, env=env)\n",
843
- "\n",
844
- " # Feature matching\n",
845
- " print(\"2/4: Matching features...\")\n",
846
- " subprocess.run([\n",
847
- " 'colmap', 'exhaustive_matcher', # Use sequential_matcher instead of exhaustive_matcher\n",
848
- " '--database_path', database_path,\n",
849
- " '--SiftMatching.use_gpu', '0' # Use CPU\n",
850
- " ], check=True, env=env)\n",
851
- "\n",
852
- " # Sparse reconstruction\n",
853
- " print(\"3/4: Sparse reconstruction...\")\n",
854
- " subprocess.run([\n",
855
- " 'colmap', 'mapper',\n",
856
- " '--database_path', database_path,\n",
857
- " '--image_path', image_dir,\n",
858
- " '--output_path', sparse_dir,\n",
859
- " '--Mapper.ba_global_max_num_iterations', '20', # Speed up\n",
860
- " '--Mapper.ba_local_max_num_iterations', '10'\n",
861
- " ], check=True, env=env)\n",
862
- "\n",
863
- " # Export to text format\n",
864
- " print(\"4/4: Exporting to text format...\")\n",
865
- " model_dir = os.path.join(sparse_dir, '0')\n",
866
- " if not os.path.exists(model_dir):\n",
867
- " # Use the first model found\n",
868
- " subdirs = [d for d in os.listdir(sparse_dir) if os.path.isdir(os.path.join(sparse_dir, d))]\n",
869
- " if subdirs:\n",
870
- " model_dir = os.path.join(sparse_dir, subdirs[0])\n",
871
- " else:\n",
872
- " raise FileNotFoundError(\"COLMAP reconstruction failed\")\n",
873
- "\n",
874
- " subprocess.run([\n",
875
- " 'colmap', 'model_converter',\n",
876
- " '--input_path', model_dir,\n",
877
- " '--output_path', model_dir,\n",
878
- " '--output_type', 'TXT'\n",
879
- " ], check=True, env=env)\n",
880
- "\n",
881
- " print(f\"COLMAP reconstruction complete: {model_dir}\")\n",
882
- " return model_dir\n",
883
- "\n",
884
- "\n",
885
- "def convert_cameras_to_pinhole(input_file, output_file):\n",
886
- " \"\"\"Convert camera model to PINHOLE format\"\"\"\n",
887
- " print(f\"Reading camera file: {input_file}\")\n",
888
- "\n",
889
- " with open(input_file, 'r') as f:\n",
890
- " lines = f.readlines()\n",
891
- "\n",
892
- " converted_count = 0\n",
893
- " with open(output_file, 'w') as f:\n",
894
- " for line in lines:\n",
895
- " if line.startswith('#') or line.strip() == '':\n",
896
- " f.write(line)\n",
897
- " else:\n",
898
- " parts = line.strip().split()\n",
899
- " if len(parts) >= 4:\n",
900
- " cam_id = parts[0]\n",
901
- " model = parts[1]\n",
902
- " width = parts[2]\n",
903
- " height = parts[3]\n",
904
- " params = parts[4:]\n",
905
- "\n",
906
- " # Convert to PINHOLE format\n",
907
- " if model == \"PINHOLE\":\n",
908
- " f.write(line)\n",
909
- " elif model == \"OPENCV\":\n",
910
- " # OPENCV: fx, fy, cx, cy, k1, k2, p1, p2\n",
911
- " fx = params[0]\n",
912
- " fy = params[1]\n",
913
- " cx = params[2]\n",
914
- " cy = params[3]\n",
915
- " f.write(f\"{cam_id} PINHOLE {width} {height} {fx} {fy} {cx} {cy}\\n\")\n",
916
- " converted_count += 1\n",
917
- " else:\n",
918
- " # Convert other models too\n",
919
- " fx = fy = max(float(width), float(height))\n",
920
- " cx = float(width) / 2\n",
921
- " cy = float(height) / 2\n",
922
- " f.write(f\"{cam_id} PINHOLE {width} {height} {fx} {fy} {cx} {cy}\\n\")\n",
923
- " converted_count += 1\n",
924
- " else:\n",
925
- " f.write(line)\n",
926
- "\n",
927
- " print(f\"Converted {converted_count} cameras to PINHOLE format\")\n",
928
- "\n",
929
- "\n",
930
- "def prepare_gaussian_splatting_data(image_dir, colmap_model_dir):\n",
931
- " \"\"\"Prepare data for Gaussian Splatting\"\"\"\n",
932
- " print(\"Preparing data for Gaussian Splatting...\")\n",
933
- "\n",
934
- " data_dir = f\"{WORK_DIR}/data/video\"\n",
935
- " os.makedirs(f\"{data_dir}/sparse/0\", exist_ok=True)\n",
936
- " os.makedirs(f\"{data_dir}/images\", exist_ok=True)\n",
937
- "\n",
938
- " # Copy images\n",
939
- " print(\"Copying images...\")\n",
940
- " img_count = 0\n",
941
- " for img_file in os.listdir(image_dir):\n",
942
- " if img_file.lower().endswith(('.jpg', '.jpeg', '.png')):\n",
943
- " shutil.copy(\n",
944
- " os.path.join(image_dir, img_file),\n",
945
- " f\"{data_dir}/images/{img_file}\"\n",
946
- " )\n",
947
- " img_count += 1\n",
948
- " print(f\"Copied {img_count} images\")\n",
949
- "\n",
950
- " # Convert and copy camera file to PINHOLE format\n",
951
- " print(\"Converting camera model to PINHOLE format...\")\n",
952
- " convert_cameras_to_pinhole(\n",
953
- " os.path.join(colmap_model_dir, 'cameras.txt'),\n",
954
- " f\"{data_dir}/sparse/0/cameras.txt\"\n",
955
- " )\n",
956
- "\n",
957
- " # Copy other files\n",
958
- " for filename in ['images.txt', 'points3D.txt']:\n",
959
- " src = os.path.join(colmap_model_dir, filename)\n",
960
- " dst = f\"{data_dir}/sparse/0/{filename}\"\n",
961
- " if os.path.exists(src):\n",
962
- " shutil.copy(src, dst)\n",
963
- " print(f\"Copied {filename}\")\n",
964
- " else:\n",
965
- " print(f\"Warning: {filename} not found\")\n",
966
- "\n",
967
- " print(f\"Data preparation complete: {data_dir}\")\n",
968
- " return data_dir\n",
969
- "\n",
970
- "\n",
971
- "\n",
972
- "###############################################################\n",
973
- "\n",
974
- "# 変更後 (2DGS) - 正則化パラメータを追加\n",
975
- "def train_gaussian_splatting(data_dir, iterations=7000,\n",
976
- " lambda_normal=0.05,\n",
977
- " lambda_distortion=0,\n",
978
- " depth_ratio=0):\n",
979
- " \"\"\"\n",
980
- " 2DGS用のトレーニング関数\n",
981
- "\n",
982
- " Args:\n",
983
- " lambda_normal: 法線一貫性の重み (デフォルト: 0.05)\n",
984
- " lambda_distortion: 深度歪みの重み (デフォルト: 0)\n",
985
- " depth_ratio: 0=平均深度, 1=中央値深度 (デフォルト: 0)\n",
986
- " \"\"\"\n",
987
- " model_path = f\"{WORK_DIR}/output/video\"\n",
988
- " cmd = [\n",
989
- " sys.executable, 'train.py',\n",
990
- " '-s', data_dir,\n",
991
- " '-m', model_path,\n",
992
- " '--iterations', str(iterations),\n",
993
- " '--lambda_normal', str(lambda_normal),\n",
994
- " '--lambda_distortion', str(lambda_distortion),\n",
995
- " '--depth_ratio', str(depth_ratio),\n",
996
- " '--eval'\n",
997
- " ]\n",
998
- " subprocess.run(cmd, cwd=WORK_DIR, check=True)\n",
999
- " return model_path\n",
1000
- "\n",
1001
- "\n",
1002
- "\n",
1003
- "# 2DGSではメッシュ抽出オプションが追加されています\n",
1004
- "def render_video_and_mesh(model_path, output_video_path, iteration=7000,\n",
1005
- " extract_mesh=True, unbounded=False, mesh_res=1024):\n",
1006
- " \"\"\"\n",
1007
- " 2DGS用のレンダリングとメッシュ抽出\n",
1008
- "\n",
1009
- " Args:\n",
1010
- " extract_mesh: メッシュを抽出するか\n",
1011
- " unbounded: 境界なしメッシュ抽出を使用するか\n",
1012
- " mesh_res: メッシュ解像度\n",
1013
- " \"\"\"\n",
1014
- " # 通常のレンダリング\n",
1015
- " cmd = [\n",
1016
- " sys.executable, 'render.py',\n",
1017
- " '-m', model_path,\n",
1018
- " '--iteration', str(iteration)\n",
1019
- " ]\n",
1020
- "\n",
1021
- " # メッシュ抽出オプション追加\n",
1022
- " if extract_mesh:\n",
1023
- " if unbounded:\n",
1024
- " cmd.extend(['--unbounded', '--mesh_res', str(mesh_res)])\n",
1025
- " cmd.extend(['--skip_test', '--skip_train'])\n",
1026
- "\n",
1027
- " subprocess.run(cmd, cwd=WORK_DIR, check=True)\n",
1028
- "\n",
1029
- " # Find the rendering directory\n",
1030
- " possible_dirs = [\n",
1031
- " f\"{model_path}/test/ours_{iteration}/renders\",\n",
1032
- " f\"{model_path}/train/ours_{iteration}/renders\",\n",
1033
- " ]\n",
1034
- "\n",
1035
- " render_dir = None\n",
1036
- " for test_dir in possible_dirs:\n",
1037
- " if os.path.exists(test_dir):\n",
1038
- " render_dir = test_dir\n",
1039
- " print(f\"Rendering directory found: {render_dir}\")\n",
1040
- " break\n",
1041
- "\n",
1042
- " if render_dir and os.path.exists(render_dir):\n",
1043
- " render_imgs = sorted([f for f in os.listdir(render_dir) if f.endswith('.png')])\n",
1044
- "\n",
1045
- " if render_imgs:\n",
1046
- " print(f\"Found {len(render_imgs)} rendered images\")\n",
1047
- "\n",
1048
- " # Create video with ffmpeg\n",
1049
- " subprocess.run([\n",
1050
- " 'ffmpeg', '-y',\n",
1051
- " '-framerate', '30',\n",
1052
- " '-pattern_type', 'glob',\n",
1053
- " '-i', f\"{render_dir}/*.png\",\n",
1054
- " '-c:v', 'libx264',\n",
1055
- " '-pix_fmt', 'yuv420p',\n",
1056
- " '-crf', '18',\n",
1057
- " output_video_path\n",
1058
- " ], check=True)\n",
1059
- "\n",
1060
- " print(f\"Video saved: {output_video_path}\")\n",
1061
- " return True\n",
1062
- "\n",
1063
- " print(\"Error: Rendering directory not found\")\n",
1064
- " return False\n",
1065
- "\n",
1066
- "###############################################################\n",
1067
- "\n",
1068
- "\n",
1069
- "def create_gif(video_path, gif_path):\n",
1070
- " \"\"\"Create GIF from MP4\"\"\"\n",
1071
- " print(\"Creating animated GIF...\")\n",
1072
- "\n",
1073
- " subprocess.run([\n",
1074
- " 'ffmpeg', '-y',\n",
1075
- " '-i', video_path,\n",
1076
- " '-vf', 'setpts=8*PTS,fps=10,scale=720:-1:flags=lanczos',\n",
1077
- " '-loop', '0',\n",
1078
- " gif_path\n",
1079
- " ], check=True)\n",
1080
- "\n",
1081
- " if os.path.exists(gif_path):\n",
1082
- " size_mb = os.path.getsize(gif_path) / (1024 * 1024)\n",
1083
- " print(f\"GIF creation complete: {gif_path} ({size_mb:.2f} MB)\")\n",
1084
- " return True\n",
1085
- "\n",
1086
- " return False"
1087
- ]
1088
- },
1089
- {
1090
- "cell_type": "code",
1091
- "source": [],
1092
- "metadata": {
1093
- "id": "YtqhBP4T3jEH"
1094
- },
1095
- "id": "YtqhBP4T3jEH",
1096
- "execution_count": null,
1097
- "outputs": []
1098
- },
1099
- {
1100
- "cell_type": "code",
1101
- "source": [
1102
- "def main_pipeline(image_dir, output_dir, square_size=1024, max_images=100):\n",
1103
- " \"\"\"Main execution function\"\"\"\n",
1104
- " try:\n",
1105
- " # Step 1: 画像の正規化と前処理\n",
1106
- " print(\"=\"*60)\n",
1107
- " print(\"Step 1: Normalizing and preprocessing images\")\n",
1108
- " print(\"=\"*60)\n",
1109
- "\n",
1110
- " frame_dir = os.path.join(COLMAP_DIR, \"images\")\n",
1111
- " os.makedirs(frame_dir, exist_ok=True)\n",
1112
- "\n",
1113
- " # 画像を正規化して直接COLMAPのディレクトリに保存\n",
1114
- " num_processed = normalize_image_sizes_biplet(\n",
1115
- " input_dir=image_dir,\n",
1116
- " output_dir=frame_dir, # 直接colmap/imagesに保存\n",
1117
- " size=square_size,\n",
1118
- " max_images=max_images\n",
1119
- " )\n",
1120
- "\n",
1121
- " print(f\"Processed {num_processed} images\")\n",
1122
- "\n",
1123
- " # Step 2: Estimate Camera Info with COLMAP\n",
1124
- " print(\"=\"*60)\n",
1125
- " print(\"Step 2: Running COLMAP reconstruction\")\n",
1126
- " print(\"=\"*60)\n",
1127
- " colmap_model_dir = run_colmap_reconstruction(frame_dir, COLMAP_DIR)\n",
1128
- "\n",
1129
- " # Step 3: Prepare Data for Gaussian Splatting\n",
1130
- " print(\"=\"*60)\n",
1131
- " print(\"Step 3: Preparing Gaussian Splatting data\")\n",
1132
- " print(\"=\"*60)\n",
1133
- " data_dir = prepare_gaussian_splatting_data(frame_dir, colmap_model_dir)\n",
1134
- "\n",
1135
- " # Step 4: Train Model\n",
1136
- " print(\"=\"*60)\n",
1137
- " print(\"Step 4: Training Gaussian Splatting model\")\n",
1138
- " print(\"=\"*60)\n",
1139
- " # 修正: frame_dir → data_dir\n",
1140
- " model_path = train_gaussian_splatting(\n",
1141
- " data_dir, # ← ここを修正!\n",
1142
- " iterations=1000,\n",
1143
- " lambda_normal=0.05,\n",
1144
- " lambda_distortion=0,\n",
1145
- " depth_ratio=0\n",
1146
- " )\n",
1147
- "\n",
1148
- " print(f\"Model trained at: {model_path}\")\n",
1149
- "\n",
1150
- " # Step 5: Render Video\n",
1151
- " print(\"=\"*60)\n",
1152
- " print(\"Step 5: Rendering video\")\n",
1153
- " print(\"=\"*60)\n",
1154
- " os.makedirs(OUTPUT_DIR, exist_ok=True)\n",
1155
- " output_video = os.path.join(OUTPUT_DIR, \"gaussian_splatting_video.mp4\")\n",
1156
- "\n",
1157
- " # 修正: output_video_path → output_video\n",
1158
- " success = render_video_and_mesh(\n",
1159
- " model_path,\n",
1160
- " output_video, # ← ここを修正!\n",
1161
- " iteration=1000,\n",
1162
- " extract_mesh=True, # メッシュ抽出を有効化\n",
1163
- " unbounded=True, # 境界なしメッシュ(推奨)\n",
1164
- " mesh_res=1024\n",
1165
- " )\n",
1166
- "\n",
1167
- " if success:\n",
1168
- " print(\"=\"*60)\n",
1169
- " print(f\"Success! Video generation complete: {output_video}\")\n",
1170
- " print(\"=\"*60)\n",
1171
- "\n",
1172
- " # Create GIF\n",
1173
- " output_gif = os.path.join(OUTPUT_DIR, \"gaussian_splatting_video.gif\")\n",
1174
- " create_gif(output_video, output_gif)\n",
1175
- "\n",
1176
- " # Display result\n",
1177
- " from IPython.display import Image, display\n",
1178
- " display(Image(open(output_gif, 'rb').read()))\n",
1179
- "\n",
1180
- " return output_video, output_gif\n",
1181
- " else:\n",
1182
- " print(\"Warning: Rendering complete, but video was not generated\")\n",
1183
- " return None, None\n",
1184
- "\n",
1185
- " except Exception as e:\n",
1186
- " print(f\"Error: {str(e)}\")\n",
1187
- " import traceback\n",
1188
- " traceback.print_exc()\n",
1189
- " return None, None\n",
1190
- "\n",
1191
- "\n",
1192
- "if __name__ == \"__main__\":\n",
1193
- " IMAGE_DIR = \"/content/drive/MyDrive/your_folder/fountain100\"\n",
1194
- " OUTPUT_DIR = \"/content/output\"\n",
1195
- " COLMAP_DIR = \"/content/colmap_workspace\"\n",
1196
- "\n",
1197
- " video_path, gif_path = main_pipeline(\n",
1198
- " image_dir=IMAGE_DIR,\n",
1199
- " output_dir=OUTPUT_DIR,\n",
1200
- " square_size=1024,\n",
1201
- " max_images=20\n",
1202
- " )\n",
1203
- "\n",
1204
- " if video_path:\n",
1205
- " print(f\"\\n✅ Success!\")\n",
1206
- " print(f\"Video: {video_path}\")\n",
1207
- " print(f\"GIF: {gif_path}\")\n",
1208
- " else:\n",
1209
- " print(\"\\n❌ Pipeline failed\")"
1210
- ],
1211
- "metadata": {
1212
- "id": "fya3kv62NXM-"
1213
- },
1214
- "id": "fya3kv62NXM-",
1215
- "execution_count": null,
1216
- "outputs": []
1217
- },
1218
- {
1219
- "cell_type": "markdown",
1220
- "id": "e17ec719",
1221
- "metadata": {
1222
- "papermill": {
1223
- "duration": 0.49801,
1224
- "end_time": "2026-01-11T00:00:18.165833",
1225
- "exception": false,
1226
- "start_time": "2026-01-11T00:00:17.667823",
1227
- "status": "completed"
1228
- },
1229
- "tags": [],
1230
- "id": "e17ec719"
1231
- },
1232
- "source": []
1233
- },
1234
- {
1235
- "cell_type": "markdown",
1236
- "id": "38b3974c",
1237
- "metadata": {
1238
- "papermill": {
1239
- "duration": 0.427583,
1240
- "end_time": "2026-01-11T00:00:19.008387",
1241
- "exception": false,
1242
- "start_time": "2026-01-11T00:00:18.580804",
1243
- "status": "completed"
1244
- },
1245
- "tags": [],
1246
- "id": "38b3974c"
1247
- },
1248
- "source": []
1249
- }
1250
- ],
1251
- "metadata": {
1252
- "kaggle": {
1253
- "accelerator": "nvidiaTeslaT4",
1254
- "dataSources": [
1255
- {
1256
- "databundleVersionId": 5447706,
1257
- "sourceId": 49349,
1258
- "sourceType": "competition"
1259
- },
1260
- {
1261
- "datasetId": 1429416,
1262
- "sourceId": 14451718,
1263
- "sourceType": "datasetVersion"
1264
- }
1265
- ],
1266
- "dockerImageVersionId": 31090,
1267
- "isGpuEnabled": true,
1268
- "isInternetEnabled": true,
1269
- "language": "python",
1270
- "sourceType": "notebook"
1271
- },
1272
- "kernelspec": {
1273
- "display_name": "Python 3",
1274
- "name": "python3"
1275
- },
1276
- "language_info": {
1277
- "codemirror_mode": {
1278
- "name": "ipython",
1279
- "version": 3
1280
- },
1281
- "file_extension": ".py",
1282
- "mimetype": "text/x-python",
1283
- "name": "python",
1284
- "nbconvert_exporter": "python",
1285
- "pygments_lexer": "ipython3",
1286
- "version": "3.11.13"
1287
- },
1288
- "papermill": {
1289
- "default_parameters": {},
1290
- "duration": 20573.990788,
1291
- "end_time": "2026-01-11T00:00:22.081506",
1292
- "environment_variables": {},
1293
- "exception": null,
1294
- "input_path": "__notebook__.ipynb",
1295
- "output_path": "__notebook__.ipynb",
1296
- "parameters": {},
1297
- "start_time": "2026-01-10T18:17:28.090718",
1298
- "version": "2.6.0"
1299
- },
1300
- "colab": {
1301
- "provenance": [],
1302
- "gpuType": "T4"
1303
- },
1304
- "accelerator": "GPU"
1305
- },
1306
- "nbformat": 4,
1307
- "nbformat_minor": 5
1308
- }