stpete2 commited on
Commit
02b9d6f
·
verified ·
1 Parent(s): b5666c7

Upload tetsu28-frames-cuda-mps-cpu-gaussian-splat.ipynb

Browse files
tetsu28-frames-cuda-mps-cpu-gaussian-splat.ipynb ADDED
@@ -0,0 +1,1507 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "id": "4755b4ab",
7
+ "metadata": {
8
+ "_cell_guid": "8ed69b5e-6ae1-4690-bae7-5846cf3b19c9",
9
+ "_uuid": "eeb1acde-fd95-42f4-983e-58854c0b2f2a",
10
+ "collapsed": false,
11
+ "jupyter": {
12
+ "outputs_hidden": false
13
+ },
14
+ "papermill": {
15
+ "duration": 0.003598,
16
+ "end_time": "2025-12-27T14:06:03.951232",
17
+ "exception": false,
18
+ "start_time": "2025-12-27T14:06:03.947634",
19
+ "status": "completed"
20
+ },
21
+ "tags": []
22
+ },
23
+ "outputs": [],
24
+ "source": []
25
+ },
26
+ {
27
+ "cell_type": "markdown",
28
+ "id": "de983c5c",
29
+ "metadata": {
30
+ "papermill": {
31
+ "duration": 0.002841,
32
+ "end_time": "2025-12-27T14:06:03.957224",
33
+ "exception": false,
34
+ "start_time": "2025-12-27T14:06:03.954383",
35
+ "status": "completed"
36
+ },
37
+ "tags": []
38
+ },
39
+ "source": [
40
+ "# **Tetsu28 Frames: CUDA/MPS/CPU Gaussian Splat**"
41
+ ]
42
+ },
43
+ {
44
+ "cell_type": "markdown",
45
+ "id": "48f0f1d3",
46
+ "metadata": {
47
+ "papermill": {
48
+ "duration": 0.002443,
49
+ "end_time": "2025-12-27T14:06:03.962181",
50
+ "exception": false,
51
+ "start_time": "2025-12-27T14:06:03.959738",
52
+ "status": "completed"
53
+ },
54
+ "tags": []
55
+ },
56
+ "source": [
57
+ "\n",
58
+ " n_images = 30\n",
59
+ " unique frames total = 500\n",
60
+ " exhaustive_matcher\n",
61
+ " normalize_image_sizes = 1280\n",
62
+ " iteration = 60\n",
63
+ " time = 00 min w/cpu\n",
64
+ " result = "
65
+ ]
66
+ },
67
+ {
68
+ "cell_type": "code",
69
+ "execution_count": 16,
70
+ "id": "a499b6cb",
71
+ "metadata": {},
72
+ "outputs": [
73
+ {
74
+ "name": "stdout",
75
+ "output_type": "stream",
76
+ "text": [
77
+ "Requirement already satisfied: torch in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (2.9.1)\n",
78
+ "Requirement already satisfied: filelock in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from torch) (3.20.1)\n",
79
+ "Requirement already satisfied: typing-extensions>=4.10.0 in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from torch) (4.15.0)\n",
80
+ "Requirement already satisfied: sympy>=1.13.3 in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from torch) (1.14.0)\n",
81
+ "Requirement already satisfied: networkx>=2.5.1 in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from torch) (3.6.1)\n",
82
+ "Requirement already satisfied: jinja2 in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from torch) (3.1.6)\n",
83
+ "Requirement already satisfied: fsspec>=0.8.5 in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from torch) (2025.12.0)\n",
84
+ "Requirement already satisfied: mpmath<1.4,>=1.1.0 in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from sympy>=1.13.3->torch) (1.3.0)\n",
85
+ "Requirement already satisfied: MarkupSafe>=2.0 in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from jinja2->torch) (3.0.3)\n",
86
+ "Note: you may need to restart the kernel to use updated packages.\n",
87
+ "Requirement already satisfied: opencv-python in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (4.12.0.88)\n",
88
+ "Requirement already satisfied: numpy<2.3.0,>=2 in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from opencv-python) (2.2.6)\n",
89
+ "Note: you may need to restart the kernel to use updated packages.\n",
90
+ "Requirement already satisfied: Pillow in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (12.0.0)\n",
91
+ "Note: you may need to restart the kernel to use updated packages.\n",
92
+ "Found existing installation: numpy 2.2.6\n",
93
+ "Uninstalling numpy-2.2.6:\n",
94
+ " Successfully uninstalled numpy-2.2.6\n",
95
+ "Note: you may need to restart the kernel to use updated packages.\n",
96
+ "Collecting numpy<2.0\n",
97
+ " Using cached numpy-1.26.4-cp311-cp311-macosx_11_0_arm64.whl.metadata (114 kB)\n",
98
+ "Using cached numpy-1.26.4-cp311-cp311-macosx_11_0_arm64.whl (14.0 MB)\n",
99
+ "Installing collected packages: numpy\n",
100
+ "\u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n",
101
+ "opencv-python 4.12.0.88 requires numpy<2.3.0,>=2; python_version >= \"3.9\", but you have numpy 1.26.4 which is incompatible.\u001b[0m\u001b[31m\n",
102
+ "\u001b[0mSuccessfully installed numpy-1.26.4\n",
103
+ "Note: you may need to restart the kernel to use updated packages.\n"
104
+ ]
105
+ }
106
+ ],
107
+ "source": [
108
+ "%pip install torch\n",
109
+ "%pip install opencv-python\n",
110
+ "%pip install Pillow\n",
111
+ "%pip uninstall -y numpy\n",
112
+ "%pip install \"numpy<2.0\""
113
+ ]
114
+ },
115
+ {
116
+ "cell_type": "code",
117
+ "execution_count": 17,
118
+ "id": "3a32d42b",
119
+ "metadata": {},
120
+ "outputs": [],
121
+ "source": [
122
+ "\n",
123
+ "\n",
124
+ "# Global Settings\n",
125
+ "IMAGE_PATH = \"tetsu28_frames\" # Set path to your image folder, inside WRK_DIR\n",
126
+ "WORK_DIR = './gaussian_splatting'\n",
127
+ "OUTPUT_DIR = './output'\n",
128
+ "COLMAP_DIR = './colmap_data'\n"
129
+ ]
130
+ },
131
+ {
132
+ "cell_type": "code",
133
+ "execution_count": 18,
134
+ "id": "e5c155b6",
135
+ "metadata": {},
136
+ "outputs": [],
137
+ "source": [
138
+ "import subprocess\n",
139
+ "import sys\n",
140
+ "import os\n",
141
+ "import platform\n",
142
+ "from pathlib import Path\n",
143
+ "\n",
144
+ "WORK_DIR = Path.home() / 'gaussian_splatting'\n",
145
+ "\n",
146
+ "def setup_environment():\n",
147
+ " \"\"\"Install necessary packages and clone the repository (cross-platform)\"\"\"\n",
148
+ " print(\"Setting up environment...\")\n",
149
+ " \n",
150
+ " system = platform.system()\n",
151
+ " print(f\"Detected operating system: {system}\")\n",
152
+ " \n",
153
+ " # Platform-specific setup\n",
154
+ " if system == \"Linux\":\n",
155
+ " print(\"Setting up virtual display for Linux...\")\n",
156
+ " try:\n",
157
+ " subprocess.run(['apt-get', 'update', '-qq'], check=True)\n",
158
+ " subprocess.run(['apt-get', 'install', '-y', '-qq', 'xvfb'], check=True)\n",
159
+ " \n",
160
+ " os.environ['QT_QPA_PLATFORM'] = 'offscreen'\n",
161
+ " os.environ['DISPLAY'] = ':99'\n",
162
+ " subprocess.Popen(['Xvfb', ':99', '-screen', '0', '1024x768x24'])\n",
163
+ " \n",
164
+ " print(\"Installing COLMAP...\")\n",
165
+ " subprocess.run(['apt-get', 'install', '-y', '-qq', 'colmap'], check=True)\n",
166
+ " \n",
167
+ " print(\"Installing build dependencies...\")\n",
168
+ " subprocess.run([\n",
169
+ " 'apt-get', 'install', '-y', '-qq',\n",
170
+ " 'build-essential', 'cmake', 'git'\n",
171
+ " ], check=True)\n",
172
+ " except FileNotFoundError:\n",
173
+ " print(\"Warning: apt-get not found.\")\n",
174
+ " \n",
175
+ " elif system == \"Darwin\": # macOS\n",
176
+ " print(\"Running on macOS - CPU/MPS mode\")\n",
177
+ " \n",
178
+ " machine = platform.machine()\n",
179
+ " print(f\"Architecture: {machine}\")\n",
180
+ " \n",
181
+ " if machine == \"arm64\":\n",
182
+ " print(\"✓ Apple Silicon detected - MPS acceleration available\")\n",
183
+ " else:\n",
184
+ " print(\"✓ Intel Mac detected - CPU mode\")\n",
185
+ " \n",
186
+ " try:\n",
187
+ " subprocess.run(['brew', '--version'], capture_output=True, check=True)\n",
188
+ " print(\"✓ Homebrew detected\")\n",
189
+ " \n",
190
+ " try:\n",
191
+ " subprocess.run(['colmap', '--version'], capture_output=True, check=True)\n",
192
+ " print(\"✓ COLMAP already installed\")\n",
193
+ " except (FileNotFoundError, subprocess.CalledProcessError):\n",
194
+ " print(\"Installing COLMAP via Homebrew...\")\n",
195
+ " subprocess.run(['brew', 'install', 'colmap'], check=True)\n",
196
+ " \n",
197
+ " subprocess.run(['xcode-select', '--install'], \n",
198
+ " capture_output=True, check=False)\n",
199
+ " \n",
200
+ " except (FileNotFoundError, subprocess.CalledProcessError):\n",
201
+ " print(\"Warning: Homebrew not found.\")\n",
202
+ " \n",
203
+ " # Clone repository\n",
204
+ " print(f\"\\nWorking directory: {WORK_DIR}\")\n",
205
+ " \n",
206
+ " if not WORK_DIR.exists():\n",
207
+ " print(\"Cloning Gaussian Splatting repository...\")\n",
208
+ " WORK_DIR.parent.mkdir(parents=True, exist_ok=True)\n",
209
+ " subprocess.run([\n",
210
+ " 'git', 'clone', '--recursive',\n",
211
+ " 'https://github.com/tztechno/gaussian-splatting.git',\n",
212
+ " str(WORK_DIR)\n",
213
+ " ], check=True)\n",
214
+ " else:\n",
215
+ " print(f\"Repository already exists at {WORK_DIR}\")\n",
216
+ " \n",
217
+ " os.chdir(str(WORK_DIR))\n",
218
+ " print(f\"Changed directory to: {os.getcwd()}\")\n",
219
+ " \n",
220
+ " # Install base packages\n",
221
+ " print(\"\\nInstalling base Python packages...\")\n",
222
+ " subprocess.run([\n",
223
+ " sys.executable, '-m', 'pip', 'install', '--upgrade',\n",
224
+ " 'pip', 'setuptools', 'wheel', 'ninja'\n",
225
+ " ], check=True)\n",
226
+ " \n",
227
+ " # Install PyTorch\n",
228
+ " print(\"Installing PyTorch...\")\n",
229
+ " subprocess.run([\n",
230
+ " sys.executable, '-m', 'pip', 'install',\n",
231
+ " 'torch', 'torchvision', 'torchaudio'\n",
232
+ " ], check=True)\n",
233
+ " \n",
234
+ " # Check acceleration availability\n",
235
+ " import torch\n",
236
+ " print(f\"\\n✓ PyTorch {torch.__version__} installed\")\n",
237
+ " \n",
238
+ " has_cuda = torch.cuda.is_available()\n",
239
+ " has_mps = torch.backends.mps.is_available() if hasattr(torch.backends, 'mps') else False\n",
240
+ " \n",
241
+ " if has_cuda:\n",
242
+ " device_info = f\"CUDA - {torch.cuda.get_device_name(0)}\"\n",
243
+ " device_type = \"cuda\"\n",
244
+ " elif has_mps:\n",
245
+ " device_info = \"MPS (Apple Metal)\"\n",
246
+ " device_type = \"mps\"\n",
247
+ " else:\n",
248
+ " device_info = \"CPU only\"\n",
249
+ " device_type = \"cpu\"\n",
250
+ " \n",
251
+ " print(f\"✓ Acceleration: {device_info}\")\n",
252
+ " \n",
253
+ " # Install other dependencies\n",
254
+ " print(\"\\nInstalling other dependencies...\")\n",
255
+ " subprocess.run([\n",
256
+ " sys.executable, '-m', 'pip', 'install',\n",
257
+ " 'plyfile', 'tqdm', 'opencv-python', 'pillow'\n",
258
+ " ], check=True)\n",
259
+ " \n",
260
+ " # Handle CUDA extensions\n",
261
+ " submodule_raster = WORK_DIR / 'submodules' / 'diff-gaussian-rasterization'\n",
262
+ " submodule_knn = WORK_DIR / 'submodules' / 'simple-knn'\n",
263
+ " \n",
264
+ " if has_cuda:\n",
265
+ " # Full CUDA build\n",
266
+ " print(\"\\n\" + \"=\"*60)\n",
267
+ " print(\"Building CUDA extensions (full GPU acceleration)...\")\n",
268
+ " print(\"=\"*60)\n",
269
+ " \n",
270
+ " if submodule_raster.exists():\n",
271
+ " print(\"\\nBuilding diff-gaussian-rasterization...\")\n",
272
+ " try:\n",
273
+ " subprocess.run([\n",
274
+ " sys.executable, '-m', 'pip', 'install',\n",
275
+ " '--no-build-isolation',\n",
276
+ " str(submodule_raster)\n",
277
+ " ], check=True)\n",
278
+ " print(\"✓ diff-gaussian-rasterization built\")\n",
279
+ " except subprocess.CalledProcessError:\n",
280
+ " print(\"✗ Failed to build diff-gaussian-rasterization\")\n",
281
+ " \n",
282
+ " if submodule_knn.exists():\n",
283
+ " print(\"\\nBuilding simple-knn...\")\n",
284
+ " try:\n",
285
+ " subprocess.run([\n",
286
+ " sys.executable, '-m', 'pip', 'install',\n",
287
+ " '--no-build-isolation',\n",
288
+ " str(submodule_knn)\n",
289
+ " ], check=True)\n",
290
+ " print(\"✓ simple-knn built\")\n",
291
+ " except subprocess.CalledProcessError:\n",
292
+ " print(\"✗ Failed to build simple-knn\")\n",
293
+ " \n",
294
+ " else:\n",
295
+ " # CPU/MPS mode - skip CUDA extensions\n",
296
+ " print(\"\\n\" + \"=\"*60)\n",
297
+ " print(\"CPU/MPS Mode - Skipping CUDA extensions\")\n",
298
+ " print(\"=\"*60)\n",
299
+ " print(\"\\nThe CUDA-specific extensions won't be built.\")\n",
300
+ " print(\"The script will run in CPU/MPS mode with reduced performance.\")\n",
301
+ " print(\"\\nAvailable functionality:\")\n",
302
+ " print(\" ✓ Data preparation\")\n",
303
+ " print(\" ✓ COLMAP processing\")\n",
304
+ " print(\" ✓ Visualization\")\n",
305
+ " print(\" ✓ Training (slower, CPU/MPS)\")\n",
306
+ " print(\"\\nLimited functionality:\")\n",
307
+ " print(\" ⚠ Slower training/inference\")\n",
308
+ " print(\" ⚠ Some optimizations unavailable\")\n",
309
+ " print(\"=\"*60)\n",
310
+ " \n",
311
+ " # Create a device configuration file\n",
312
+ " config_file = WORK_DIR / 'device_config.py'\n",
313
+ " with open(config_file, 'w') as f:\n",
314
+ " f.write(f\"\"\"# Auto-generated device configuration\n",
315
+ "import torch\n",
316
+ "\n",
317
+ "# Device selection\n",
318
+ "DEVICE_TYPE = '{device_type}'\n",
319
+ "HAS_CUDA = {has_cuda}\n",
320
+ "HAS_MPS = {has_mps}\n",
321
+ "\n",
322
+ "def get_device():\n",
323
+ " \\\"\\\"\\\"Get the best available device\\\"\\\"\\\"\n",
324
+ " if HAS_CUDA:\n",
325
+ " return torch.device('cuda')\n",
326
+ " elif HAS_MPS:\n",
327
+ " return torch.device('mps')\n",
328
+ " else:\n",
329
+ " return torch.device('cpu')\n",
330
+ "\n",
331
+ "# Set default device\n",
332
+ "torch.set_default_device(get_device())\n",
333
+ "print(f\"Using device: {{get_device()}}\")\n",
334
+ "\"\"\")\n",
335
+ " print(f\"\\n✓ Created device config: {config_file}\")\n",
336
+ " \n",
337
+ " print(\"\\n\" + \"=\"*60)\n",
338
+ " print(\"Setup Complete!\")\n",
339
+ " print(\"=\"*60)\n",
340
+ " print(f\"Working directory: {WORK_DIR}\")\n",
341
+ " print(f\"Device: {device_info}\")\n",
342
+ " print(f\"Mode: {'Full GPU' if has_cuda else 'CPU/MPS (partial)'}\")\n",
343
+ " print(\"=\"*60)\n",
344
+ " \n",
345
+ " if not has_cuda:\n",
346
+ " print(\"\\n💡 Tip: For faster training, use a cloud platform with CUDA:\")\n",
347
+ " print(\" • Kaggle Notebooks (free): https://www.kaggle.com/\")\n",
348
+ " print(\" • Google Colab (free): https://colab.research.google.com/\")"
349
+ ]
350
+ },
351
+ {
352
+ "cell_type": "code",
353
+ "execution_count": 19,
354
+ "id": "79bbfb5a",
355
+ "metadata": {},
356
+ "outputs": [
357
+ {
358
+ "name": "stdout",
359
+ "output_type": "stream",
360
+ "text": [
361
+ "Setting up environment...\n",
362
+ "Detected operating system: Darwin\n",
363
+ "Running on macOS - CPU/MPS mode\n",
364
+ "Architecture: arm64\n",
365
+ "✓ Apple Silicon detected - MPS acceleration available\n",
366
+ "✓ Homebrew detected\n",
367
+ "Installing COLMAP via Homebrew...\n"
368
+ ]
369
+ },
370
+ {
371
+ "name": "stderr",
372
+ "output_type": "stream",
373
+ "text": [
374
+ "Warning: colmap 3.13.0_3 is already installed and up-to-date.\n",
375
+ "To reinstall 3.13.0_3, run:\n",
376
+ " brew reinstall colmap\n"
377
+ ]
378
+ },
379
+ {
380
+ "name": "stdout",
381
+ "output_type": "stream",
382
+ "text": [
383
+ "\n",
384
+ "Working directory: /Users/shun_ishii/gaussian_splatting\n",
385
+ "Repository already exists at /Users/shun_ishii/gaussian_splatting\n",
386
+ "Changed directory to: /Users/shun_ishii/gaussian_splatting\n",
387
+ "\n",
388
+ "Installing base Python packages...\n",
389
+ "Requirement already satisfied: pip in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (25.3)\n",
390
+ "Requirement already satisfied: setuptools in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (80.9.0)\n",
391
+ "Requirement already satisfied: wheel in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (0.45.1)\n",
392
+ "Requirement already satisfied: ninja in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (1.13.0)\n",
393
+ "Installing PyTorch...\n",
394
+ "Requirement already satisfied: torch in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (2.9.1)\n",
395
+ "Requirement already satisfied: torchvision in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (0.24.1)\n",
396
+ "Requirement already satisfied: torchaudio in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (2.9.1)\n",
397
+ "Requirement already satisfied: filelock in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from torch) (3.20.1)\n",
398
+ "Requirement already satisfied: typing-extensions>=4.10.0 in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from torch) (4.15.0)\n",
399
+ "Requirement already satisfied: sympy>=1.13.3 in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from torch) (1.14.0)\n",
400
+ "Requirement already satisfied: networkx>=2.5.1 in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from torch) (3.6.1)\n",
401
+ "Requirement already satisfied: jinja2 in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from torch) (3.1.6)\n",
402
+ "Requirement already satisfied: fsspec>=0.8.5 in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from torch) (2025.12.0)\n",
403
+ "Requirement already satisfied: numpy in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from torchvision) (1.26.4)\n",
404
+ "Requirement already satisfied: pillow!=8.3.*,>=5.3.0 in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from torchvision) (12.0.0)\n",
405
+ "Requirement already satisfied: mpmath<1.4,>=1.1.0 in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from sympy>=1.13.3->torch) (1.3.0)\n",
406
+ "Requirement already satisfied: MarkupSafe>=2.0 in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from jinja2->torch) (3.0.3)\n",
407
+ "\n",
408
+ "✓ PyTorch 2.9.1 installed\n",
409
+ "✓ Acceleration: MPS (Apple Metal)\n",
410
+ "\n",
411
+ "Installing other dependencies...\n",
412
+ "Requirement already satisfied: plyfile in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (1.1.3)\n",
413
+ "Requirement already satisfied: tqdm in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (4.67.1)\n",
414
+ "Requirement already satisfied: opencv-python in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (4.12.0.88)\n",
415
+ "Requirement already satisfied: pillow in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (12.0.0)\n",
416
+ "Requirement already satisfied: numpy>=1.21 in /Users/shun_ishii/miniconda3/envs/kaggle_local_env/lib/python3.11/site-packages (from plyfile) (1.26.4)\n",
417
+ "Collecting numpy>=1.21 (from plyfile)\n",
418
+ " Using cached numpy-2.2.6-cp311-cp311-macosx_14_0_arm64.whl.metadata (62 kB)\n",
419
+ "Using cached numpy-2.2.6-cp311-cp311-macosx_14_0_arm64.whl (5.4 MB)\n",
420
+ "Installing collected packages: numpy\n",
421
+ " Attempting uninstall: numpy\n",
422
+ " Found existing installation: numpy 1.26.4\n",
423
+ " Uninstalling numpy-1.26.4:\n",
424
+ " Successfully uninstalled numpy-1.26.4\n",
425
+ "Successfully installed numpy-2.2.6\n",
426
+ "\n",
427
+ "============================================================\n",
428
+ "CPU/MPS Mode - Skipping CUDA extensions\n",
429
+ "============================================================\n",
430
+ "\n",
431
+ "The CUDA-specific extensions won't be built.\n",
432
+ "The script will run in CPU/MPS mode with reduced performance.\n",
433
+ "\n",
434
+ "Available functionality:\n",
435
+ " ✓ Data preparation\n",
436
+ " ✓ COLMAP processing\n",
437
+ " ✓ Visualization\n",
438
+ " ✓ Training (slower, CPU/MPS)\n",
439
+ "\n",
440
+ "Limited functionality:\n",
441
+ " ⚠ Slower training/inference\n",
442
+ " ⚠ Some optimizations unavailable\n",
443
+ "============================================================\n",
444
+ "\n",
445
+ "✓ Created device config: /Users/shun_ishii/gaussian_splatting/device_config.py\n",
446
+ "\n",
447
+ "============================================================\n",
448
+ "Setup Complete!\n",
449
+ "============================================================\n",
450
+ "Working directory: /Users/shun_ishii/gaussian_splatting\n",
451
+ "Device: MPS (Apple Metal)\n",
452
+ "Mode: CPU/MPS (partial)\n",
453
+ "============================================================\n",
454
+ "\n",
455
+ "💡 Tip: For faster training, use a cloud platform with CUDA:\n",
456
+ " • Kaggle Notebooks (free): https://www.kaggle.com/\n",
457
+ " • Google Colab (free): https://colab.research.google.com/\n"
458
+ ]
459
+ }
460
+ ],
461
+ "source": [
462
+ "setup_environment()"
463
+ ]
464
+ },
465
+ {
466
+ "cell_type": "code",
467
+ "execution_count": 20,
468
+ "id": "b17d066b",
469
+ "metadata": {
470
+ "execution": {
471
+ "iopub.execute_input": "2025-12-27T14:06:28.227911Z",
472
+ "iopub.status.busy": "2025-12-27T14:06:28.227522Z",
473
+ "iopub.status.idle": "2025-12-27T17:30:13.779267Z",
474
+ "shell.execute_reply": "2025-12-27T17:30:13.775012Z"
475
+ },
476
+ "papermill": {
477
+ "duration": 12225.570841,
478
+ "end_time": "2025-12-27T17:30:13.783931",
479
+ "exception": false,
480
+ "start_time": "2025-12-27T14:06:28.213090",
481
+ "status": "completed"
482
+ },
483
+ "tags": []
484
+ },
485
+ "outputs": [
486
+ {
487
+ "name": "stdout",
488
+ "output_type": "stream",
489
+ "text": [
490
+ "Detected device: mps (Apple Silicon GPU (MPS))\n",
491
+ "============================================================\n",
492
+ "Gaussian Splatting Generation (Mac MPS Support)\n",
493
+ "============================================================\n",
494
+ "Using Device: mps\n",
495
+ "============================================================\n",
496
+ "Setting up environment...\n",
497
+ "Detected device: mps\n",
498
+ "NumPy Version: 1.26.4\n",
499
+ "\n",
500
+ "======================================================================\n",
501
+ "Checking System Packages\n",
502
+ "======================================================================\n",
503
+ "\n",
504
+ "Checking COLMAP installation...\n",
505
+ "✓ COLMAP found: /opt/homebrew/bin/colmap\n",
506
+ "\n",
507
+ "======================================================================\n",
508
+ "Cloning Gaussian Splatting Repository\n",
509
+ "======================================================================\n",
510
+ "✓ Repository exists: /Users/shun_ishii/gaussian_splatting\n",
511
+ "\n",
512
+ "======================================================================\n",
513
+ "Installing Python Packages\n",
514
+ "======================================================================\n",
515
+ "✓ Installed torch\n",
516
+ "✓ Installed torchvision\n",
517
+ "✓ Installed torchaudio\n",
518
+ "✓ Installed plyfile\n",
519
+ "✓ Installed tqdm\n",
520
+ "✓ Installed opencv-python\n",
521
+ "✓ Installed pillow\n",
522
+ "✓ Installed imageio\n",
523
+ "✓ Installed imageio-ffmpeg\n",
524
+ "✓ Installed tensorboard\n",
525
+ "\n",
526
+ "======================================================================\n",
527
+ "PyTorch Device Verification\n",
528
+ "======================================================================\n",
529
+ "PyTorch: 2.9.1\n",
530
+ "CUDA Available: False\n",
531
+ "MPS Available: True\n",
532
+ "Using Device: mps\n",
533
+ "\n",
534
+ "Note: Using MPS.\n",
535
+ "CUDA extensions (diff-gaussian-rasterization) may not work on MPS.\n",
536
+ "In this case, CPU fallback will be used.\n",
537
+ "\n",
538
+ "======================================================================\n",
539
+ "Building Submodules\n",
540
+ "======================================================================\n",
541
+ "\n",
542
+ "----------------------------------------------------------------------\n",
543
+ "Building diff-gaussian-rasterization...\n",
544
+ "----------------------------------------------------------------------\n",
545
+ "Installing via pip...\n",
546
+ "⚠ Failed to install diff-gaussian-rasterization\n",
547
+ " Error: Command '['/Users/shun_ishii/miniconda3/envs/kaggle_local_env/bin/python', '-m', 'pip', 'install', '/Users/shun_ishii/gaussian_splatting/submodules/diff-gaussian-rasterization']' returned non-zero exit status 1.\n",
548
+ " Note: diff-gaussian-rasterization may not be compatible with MPS\n",
549
+ "\n",
550
+ "----------------------------------------------------------------------\n",
551
+ "Building simple-knn...\n",
552
+ "----------------------------------------------------------------------\n",
553
+ "Installing via pip...\n",
554
+ "⚠ Failed to install simple-knn\n",
555
+ " Error: Command '['/Users/shun_ishii/miniconda3/envs/kaggle_local_env/bin/python', '-m', 'pip', 'install', '/Users/shun_ishii/gaussian_splatting/submodules/simple-knn']' returned non-zero exit status 1.\n",
556
+ " Note: simple-knn may not be compatible with MPS\n",
557
+ "\n",
558
+ "======================================================================\n",
559
+ "Final Verification\n",
560
+ "======================================================================\n",
561
+ "✗ diff_gaussian_rasterization not found\n",
562
+ " Note: May not work on MPS. Please use CPU if needed.\n",
563
+ "✗ simple_knn not found\n",
564
+ "\n",
565
+ "======================================================================\n",
566
+ "⚠⚠⚠ Setup finished with warnings ⚠⚠⚠\n",
567
+ "Some modules are missing. Training may fail.\n",
568
+ "Working Directory: /Users/shun_ishii/gaussian_splatting\n",
569
+ "======================================================================\n",
570
+ "Resolved relative path to: /Users/shun_ishii/gaussian_splatting/tetsu28_frames\n",
571
+ "Looking for images in: /Users/shun_ishii/gaussian_splatting/tetsu28_frames\n",
572
+ "Absolute path: /Users/shun_ishii/gaussian_splatting/tetsu28_frames\n",
573
+ "Path exists: False\n",
574
+ "Path doesn't exist. Trying: /Users/shun_ishii/gaussian_splatting/tetsu28_frames\n",
575
+ "Error: Image folder not found: /Users/shun_ishii/gaussian_splatting/tetsu28_frames\n"
576
+ ]
577
+ },
578
+ {
579
+ "name": "stderr",
580
+ "output_type": "stream",
581
+ "text": [
582
+ "Traceback (most recent call last):\n",
583
+ " File \"/var/folders/95/y683rx814wq4p3z5srkkjb7r0000gn/T/ipykernel_67930/2734908124.py\", line 801, in main\n",
584
+ " process_frames_from_folder(IMAGE_PATH, frame_dir, max_frames=30)\n",
585
+ " File \"/var/folders/95/y683rx814wq4p3z5srkkjb7r0000gn/T/ipykernel_67930/2734908124.py\", line 307, in process_frames_from_folder\n",
586
+ " raise ValueError(f\"Image folder not found: {image_folder}\")\n",
587
+ "ValueError: Image folder not found: /Users/shun_ishii/gaussian_splatting/tetsu28_frames\n"
588
+ ]
589
+ }
590
+ ],
591
+ "source": [
592
+ "import os\n",
593
+ "import cv2\n",
594
+ "from PIL import Image\n",
595
+ "import glob\n",
596
+ "import numpy as np\n",
597
+ "import sys\n",
598
+ "import subprocess\n",
599
+ "import shutil\n",
600
+ "from pathlib import Path\n",
601
+ "import random\n",
602
+ "import torch\n",
603
+ "\n",
604
+ "# ============================================================================\n",
605
+ "# Device Detection and Setup\n",
606
+ "# ============================================================================\n",
607
+ "def detect_device():\n",
608
+ " \"\"\"Detect available device (CUDA/MPS/CPU)\"\"\"\n",
609
+ " if torch.cuda.is_available():\n",
610
+ " device = 'cuda'\n",
611
+ " device_name = torch.cuda.get_device_name(0)\n",
612
+ " elif torch.backends.mps.is_available():\n",
613
+ " device = 'mps'\n",
614
+ " device_name = 'Apple Silicon GPU (MPS)'\n",
615
+ " else:\n",
616
+ " device = 'cpu'\n",
617
+ " device_name = 'CPU'\n",
618
+ " \n",
619
+ " print(f\"Detected device: {device} ({device_name})\")\n",
620
+ " return device\n",
621
+ "\n",
622
+ "\n",
623
+ "\n",
624
+ "# Device Detection\n",
625
+ "DEVICE = detect_device()\n",
626
+ "USE_GPU = DEVICE in ['cuda', 'mps']\n",
627
+ "\n",
628
+ "# Environment variable setup (CUDA only)\n",
629
+ "if DEVICE == 'cuda':\n",
630
+ " os.environ['TORCH_CUDA_ARCH_LIST'] = '7.0;7.5;8.0;8.6'\n",
631
+ " os.environ['FORCE_CUDA'] = '1'\n",
632
+ "\n",
633
+ "\n",
634
+ "# ============================================================================\n",
635
+ "# Environment Setup Function (MPS Compatible)\n",
636
+ "# ============================================================================\n",
637
+ "def setup_environment():\n",
638
+ " \"\"\"Setup environment (Mac MPS compatible)\"\"\"\n",
639
+ " print(\"Setting up environment...\")\n",
640
+ " print(f\"Detected device: {DEVICE}\")\n",
641
+ " \n",
642
+ " # ========================================================================\n",
643
+ " # NumPy Compatibility Check\n",
644
+ " # ========================================================================\n",
645
+ " try:\n",
646
+ " import numpy\n",
647
+ " numpy_version = numpy.__version__\n",
648
+ " print(f\"NumPy Version: {numpy_version}\")\n",
649
+ " \n",
650
+ " if numpy_version.startswith('2.'):\n",
651
+ " print(\"Warning: NumPy 2.x detected. Recommend installing 1.x for compatibility.\")\n",
652
+ " response = input(\"Install NumPy 1.x? (y/n): \")\n",
653
+ " if response.lower() == 'y':\n",
654
+ " subprocess.run([sys.executable, '-m', 'pip', 'install', 'numpy<2'], check=True)\n",
655
+ " print(\"NumPy 1.x installed. Please restart the kernel.\")\n",
656
+ " except ImportError:\n",
657
+ " print(\"Installing NumPy...\")\n",
658
+ " subprocess.run([sys.executable, '-m', 'pip', 'install', 'numpy<2'], check=True)\n",
659
+ " \n",
660
+ " # ========================================================================\n",
661
+ " # System Packages\n",
662
+ " # ========================================================================\n",
663
+ " print(\"\\n\" + \"=\"*70)\n",
664
+ " print(\"Checking System Packages\")\n",
665
+ " print(\"=\"*70)\n",
666
+ " \n",
667
+ " # Check COLMAP installation\n",
668
+ " print(\"\\nChecking COLMAP installation...\")\n",
669
+ " colmap_found = False\n",
670
+ " \n",
671
+ " try:\n",
672
+ " result = subprocess.run(['which', 'colmap'], capture_output=True, text=True)\n",
673
+ " if result.returncode == 0:\n",
674
+ " colmap_path = result.stdout.strip()\n",
675
+ " print(f\"✓ COLMAP found: {colmap_path}\")\n",
676
+ " \n",
677
+ " # Check version\n",
678
+ " version_result = subprocess.run(['colmap', '--version'], \n",
679
+ " capture_output=True, text=True)\n",
680
+ " if version_result.returncode == 0:\n",
681
+ " print(f\" Version: {version_result.stdout.strip()}\")\n",
682
+ " colmap_found = True\n",
683
+ " else:\n",
684
+ " print(\"✗ COLMAP not found\")\n",
685
+ " except Exception as e:\n",
686
+ " print(f\"✗ COLMAP check error: {e}\")\n",
687
+ " \n",
688
+ " if not colmap_found:\n",
689
+ " print(\"\\n\" + \"=\"*70)\n",
690
+ " print(\"⚠️ COLMAP installation required\")\n",
691
+ " print(\"=\"*70)\n",
692
+ " print(\"\\n[Installation Methods]\")\n",
693
+ " print(\"\\n1. Mac (Homebrew):\")\n",
694
+ " print(\" brew install colmap\")\n",
695
+ " print(\"\\n2. Ubuntu:\")\n",
696
+ " print(\" sudo apt-get install colmap\")\n",
697
+ " print(\"\\n3. Conda:\")\n",
698
+ " print(\" conda install -c conda-forge colmap\")\n",
699
+ " print(\"\\n4. Build from source:\")\n",
700
+ " print(\" https://colmap.github.io/install.html\")\n",
701
+ " print(\"\\n\" + \"=\"*70)\n",
702
+ " \n",
703
+ " response = input(\"\\nContinue without COLMAP? (Warning: may fail) (y/n): \")\n",
704
+ " if response.lower() != 'y':\n",
705
+ " print(\"Please run again after installing COLMAP.\")\n",
706
+ " sys.exit(1)\n",
707
+ " print(\"⚠️ Warning: Proceeding without COLMAP\")\n",
708
+ " \n",
709
+ " # ========================================================================\n",
710
+ " # Clone Repository\n",
711
+ " # ========================================================================\n",
712
+ " print(\"\\n\" + \"=\"*70)\n",
713
+ " print(\"Cloning Gaussian Splatting Repository\")\n",
714
+ " print(\"=\"*70)\n",
715
+ " \n",
716
+ " if not os.path.exists(WORK_DIR):\n",
717
+ " print(f\"Cloning into {WORK_DIR}...\")\n",
718
+ " try:\n",
719
+ " subprocess.run([\n",
720
+ " 'git', 'clone', '--recursive',\n",
721
+ " 'https://github.com/graphdeco-inria/gaussian-splatting.git',\n",
722
+ " WORK_DIR\n",
723
+ " ], check=True)\n",
724
+ " print(\"✓ Repository cloned\")\n",
725
+ " except subprocess.CalledProcessError as e:\n",
726
+ " print(f\"✗ Clone failed: {e}\")\n",
727
+ " raise\n",
728
+ " else:\n",
729
+ " print(f\"✓ Repository exists: {WORK_DIR}\")\n",
730
+ " \n",
731
+ " # ========================================================================\n",
732
+ " # Install Python Packages\n",
733
+ " # ========================================================================\n",
734
+ " print(\"\\n\" + \"=\"*70)\n",
735
+ " print(\"Installing Python Packages\")\n",
736
+ " print(\"=\"*70)\n",
737
+ " \n",
738
+ " pip_packages = [\n",
739
+ " 'torch', 'torchvision', 'torchaudio',\n",
740
+ " 'plyfile', 'tqdm', 'opencv-python', 'pillow',\n",
741
+ " 'imageio', 'imageio-ffmpeg', 'tensorboard'\n",
742
+ " ]\n",
743
+ " \n",
744
+ " for package in pip_packages:\n",
745
+ " try:\n",
746
+ " subprocess.run([\n",
747
+ " sys.executable, '-m', 'pip', 'install', '-q', package\n",
748
+ " ], check=True, capture_output=True)\n",
749
+ " print(f\"✓ Installed {package}\")\n",
750
+ " except subprocess.CalledProcessError:\n",
751
+ " print(f\"⚠ Failed to install {package}\")\n",
752
+ " \n",
753
+ " # ========================================================================\n",
754
+ " # Device Verification\n",
755
+ " # ========================================================================\n",
756
+ " print(\"\\n\" + \"=\"*70)\n",
757
+ " print(\"PyTorch Device Verification\")\n",
758
+ " print(\"=\"*70)\n",
759
+ " \n",
760
+ " print(f\"PyTorch: {torch.__version__}\")\n",
761
+ " print(f\"CUDA Available: {torch.cuda.is_available()}\")\n",
762
+ " print(f\"MPS Available: {torch.backends.mps.is_available()}\")\n",
763
+ " print(f\"Using Device: {DEVICE}\")\n",
764
+ " \n",
765
+ " if DEVICE == 'mps':\n",
766
+ " print(\"\\nNote: Using MPS.\")\n",
767
+ " print(\"CUDA extensions (diff-gaussian-rasterization) may not work on MPS.\")\n",
768
+ " print(\"In this case, CPU fallback will be used.\")\n",
769
+ " \n",
770
+ " # ========================================================================\n",
771
+ " # Build Submodules (MPS compatible)\n",
772
+ " # ========================================================================\n",
773
+ " print(\"\\n\" + \"=\"*70)\n",
774
+ " print(\"Building Submodules\")\n",
775
+ " print(\"=\"*70)\n",
776
+ " \n",
777
+ " submodules = [\n",
778
+ " ('diff-gaussian-rasterization',\n",
779
+ " 'https://github.com/graphdeco-inria/diff-gaussian-rasterization.git'),\n",
780
+ " ('simple-knn',\n",
781
+ " 'https://github.com/camenduru/simple-knn.git')\n",
782
+ " ]\n",
783
+ " \n",
784
+ " for submodule_name, fallback_url in submodules:\n",
785
+ " print(f\"\\n{'-'*70}\")\n",
786
+ " print(f\"Building {submodule_name}...\")\n",
787
+ " print(f\"{'-'*70}\")\n",
788
+ " \n",
789
+ " submodule_dir = os.path.join(WORK_DIR, 'submodules', submodule_name)\n",
790
+ " \n",
791
+ " # Check clone\n",
792
+ " if not os.path.exists(submodule_dir) or not os.listdir(submodule_dir):\n",
793
+ " print(f\"Cloning {submodule_name}...\")\n",
794
+ " try:\n",
795
+ " subprocess.run(['git', 'clone', fallback_url, submodule_dir], check=True)\n",
796
+ " print(f\"✓ Cloned {submodule_name}\")\n",
797
+ " except subprocess.CalledProcessError:\n",
798
+ " print(f\"✗ Failed to clone {submodule_name}\")\n",
799
+ " continue\n",
800
+ " \n",
801
+ " # Install (Adjust env variables for MPS)\n",
802
+ " build_env = os.environ.copy()\n",
803
+ " if DEVICE == 'mps':\n",
804
+ " build_env.pop('FORCE_CUDA', None)\n",
805
+ " build_env.pop('TORCH_CUDA_ARCH_LIST', None)\n",
806
+ " \n",
807
+ " try:\n",
808
+ " print(f\"Installing via pip...\")\n",
809
+ " subprocess.run([\n",
810
+ " sys.executable, '-m', 'pip', 'install', submodule_dir\n",
811
+ " ], check=True, capture_output=True, env=build_env)\n",
812
+ " print(f\"✓ Installed {submodule_name}\")\n",
813
+ " except subprocess.CalledProcessError as e:\n",
814
+ " print(f\"⚠ Failed to install {submodule_name}\")\n",
815
+ " print(f\" Error: {e}\")\n",
816
+ " if DEVICE == 'mps':\n",
817
+ " print(f\" Note: {submodule_name} may not be compatible with MPS\")\n",
818
+ " \n",
819
+ " # ========================================================================\n",
820
+ " # Verification\n",
821
+ " # ========================================================================\n",
822
+ " print(\"\\n\" + \"=\"*70)\n",
823
+ " print(\"Final Verification\")\n",
824
+ " print(\"=\"*70)\n",
825
+ " \n",
826
+ " all_good = True\n",
827
+ " \n",
828
+ " try:\n",
829
+ " import diff_gaussian_rasterization\n",
830
+ " print(\"✓ diff_gaussian_rasterization is available\")\n",
831
+ " except ImportError:\n",
832
+ " print(\"✗ diff_gaussian_rasterization not found\")\n",
833
+ " all_good = False\n",
834
+ " if DEVICE == 'mps':\n",
835
+ " print(\" Note: May not work on MPS. Please use CPU if needed.\")\n",
836
+ " \n",
837
+ " try:\n",
838
+ " import simple_knn\n",
839
+ " print(\"✓ simple_knn is available\")\n",
840
+ " except ImportError:\n",
841
+ " print(\"✗ simple_knn not found\")\n",
842
+ " all_good = False\n",
843
+ " \n",
844
+ " print(\"\\n\" + \"=\"*70)\n",
845
+ " if all_good:\n",
846
+ " print(\"✓✓✓ Setup Complete - Ready to run ✓✓✓\")\n",
847
+ " else:\n",
848
+ " print(\"⚠⚠⚠ Setup finished with warnings ⚠⚠⚠\")\n",
849
+ " print(\"Some modules are missing. Training may fail.\")\n",
850
+ " print(f\"Working Directory: {WORK_DIR}\")\n",
851
+ " print(\"=\"*70)\n",
852
+ " \n",
853
+ " return WORK_DIR\n",
854
+ "\n",
855
+ "\n",
856
+ "# ============================================================================\n",
857
+ "# Frame Processing Functions\n",
858
+ "# ============================================================================\n",
859
+ "def adjust_gamma(image, gamma=1.2):\n",
860
+ " \"\"\"gamma > 1.0 brightens, gamma < 1.0 darkens\"\"\"\n",
861
+ " invGamma = 1.0 / gamma\n",
862
+ " table = (np.array([((i / 255.0) ** invGamma) * 255\n",
863
+ " for i in np.arange(0, 256)])).astype(\"uint8\")\n",
864
+ " return cv2.LUT(image, table)\n",
865
+ "\n",
866
+ "\n",
867
+ "import os\n",
868
+ "from pathlib import Path\n",
869
+ "import glob\n",
870
+ "\n",
871
+ "\n",
872
+ "def process_frames_from_folder(image_folder, output_dir, max_frames=30):\n",
873
+ " \"\"\"Process frames from a folder with improved path handling\"\"\"\n",
874
+ " \n",
875
+ " # Convert to Path object for better handling\n",
876
+ " if isinstance(image_folder, str):\n",
877
+ " image_folder = Path(image_folder)\n",
878
+ " if isinstance(output_dir, str):\n",
879
+ " output_dir = Path(output_dir)\n",
880
+ " \n",
881
+ " # Make image_folder absolute if it's relative\n",
882
+ " if not image_folder.is_absolute():\n",
883
+ " # Try relative to current working directory\n",
884
+ " image_folder = Path.cwd() / image_folder\n",
885
+ " print(f\"Resolved relative path to: {image_folder}\")\n",
886
+ " \n",
887
+ " print(f\"Looking for images in: {image_folder}\")\n",
888
+ " print(f\"Absolute path: {image_folder.absolute()}\")\n",
889
+ " print(f\"Path exists: {image_folder.exists()}\")\n",
890
+ " \n",
891
+ " if not image_folder.exists():\n",
892
+ " # Try relative to WORK_DIR\n",
893
+ " alt_path = WORK_DIR / image_folder.name\n",
894
+ " print(f\"Path doesn't exist. Trying: {alt_path}\")\n",
895
+ " if alt_path.exists():\n",
896
+ " image_folder = alt_path\n",
897
+ " else:\n",
898
+ " raise ValueError(f\"Image folder not found: {image_folder}\")\n",
899
+ " \n",
900
+ " # List all files in the directory for debugging\n",
901
+ " if image_folder.exists():\n",
902
+ " all_files = list(image_folder.iterdir())\n",
903
+ " print(f\"Found {len(all_files)} total files/folders in directory\")\n",
904
+ " if all_files:\n",
905
+ " print(\"First 5 items:\")\n",
906
+ " for item in all_files[:5]:\n",
907
+ " print(f\" - {item.name} (is_file: {item.is_file()})\")\n",
908
+ " \n",
909
+ " # Look for image files with multiple extensions\n",
910
+ " image_extensions = ['*.png', '*.jpg', '*.jpeg', '*.PNG', '*.JPG', '*.JPEG']\n",
911
+ " image_files = []\n",
912
+ " \n",
913
+ " for ext in image_extensions:\n",
914
+ " found = list(image_folder.glob(ext))\n",
915
+ " image_files.extend(found)\n",
916
+ " if found:\n",
917
+ " print(f\"Found {len(found)} {ext} files\")\n",
918
+ " \n",
919
+ " # Remove duplicates and sort\n",
920
+ " image_files = sorted(set(image_files))\n",
921
+ " \n",
922
+ " print(f\"\\nTotal image files found: {len(image_files)}\")\n",
923
+ " \n",
924
+ " if not image_files:\n",
925
+ " print(\"\\n\" + \"=\"*60)\n",
926
+ " print(\"ERROR: No image files found\")\n",
927
+ " print(\"=\"*60)\n",
928
+ " print(f\"Searched in: {image_folder}\")\n",
929
+ " print(f\"Looking for extensions: {image_extensions}\")\n",
930
+ " print(\"\\nDebugging steps:\")\n",
931
+ " print(f\"1. Check if folder exists: {image_folder.exists()}\")\n",
932
+ " print(f\"2. Check folder contents:\")\n",
933
+ " if image_folder.exists():\n",
934
+ " for item in image_folder.iterdir():\n",
935
+ " print(f\" {item.name}\")\n",
936
+ " print(\"=\"*60)\n",
937
+ " raise ValueError(f\"No image files found in: {image_folder}\")\n",
938
+ " \n",
939
+ " # Show found images\n",
940
+ " print(f\"\\nFirst few images found:\")\n",
941
+ " for img in image_files[:5]:\n",
942
+ " print(f\" - {img.name}\")\n",
943
+ " if len(image_files) > 5:\n",
944
+ " print(f\" ... and {len(image_files) - 5} more\")\n",
945
+ " \n",
946
+ " # Create output directory\n",
947
+ " output_dir.mkdir(parents=True, exist_ok=True)\n",
948
+ " \n",
949
+ " # Limit number of frames\n",
950
+ " selected_files = image_files[:max_frames]\n",
951
+ " print(f\"\\nProcessing {len(selected_files)} frames (max: {max_frames})...\")\n",
952
+ " \n",
953
+ " # Copy/process files to output directory\n",
954
+ " for i, src_file in enumerate(selected_files):\n",
955
+ " # Create sequential filename\n",
956
+ " dst_file = output_dir / f\"frame_{i:04d}{src_file.suffix}\"\n",
957
+ " \n",
958
+ " # Copy file (or process if needed)\n",
959
+ " import shutil\n",
960
+ " shutil.copy2(src_file, dst_file)\n",
961
+ " \n",
962
+ " if (i + 1) % 10 == 0:\n",
963
+ " print(f\"Processed {i + 1}/{len(selected_files)} frames\")\n",
964
+ " \n",
965
+ " print(f\"✓ Completed! {len(selected_files)} frames saved to: {output_dir}\")\n",
966
+ " return output_dir\n",
967
+ "\n",
968
+ "\n",
969
+ "# Example usage in your main function:\n",
970
+ "def main():\n",
971
+ " print(\"=\"*70)\n",
972
+ " print(\"Processing images from folder: tetsu28_frames\")\n",
973
+ " \n",
974
+ " # Define paths - use absolute path or ensure correct relative path\n",
975
+ " IMAGE_PATH = Path('tetsu28_frames') # or use absolute: Path('/full/path/to/tetsu28_frames')\n",
976
+ " frame_dir = WORK_DIR / 'data' / 'input'\n",
977
+ " \n",
978
+ " # Option 1: If images are in current directory\n",
979
+ " # IMAGE_PATH = Path.cwd() / 'tetsu28_frames'\n",
980
+ " \n",
981
+ " # Option 2: If images are in WORK_DIR\n",
982
+ " # IMAGE_PATH = WORK_DIR / 'tetsu28_frames'\n",
983
+ " \n",
984
+ " # Option 3: Absolute path\n",
985
+ " # IMAGE_PATH = Path('/Users/shun_ishii/path/to/tetsu28_frames')\n",
986
+ " \n",
987
+ " try:\n",
988
+ " process_frames_from_folder(IMAGE_PATH, frame_dir, max_frames=30)\n",
989
+ " except ValueError as e:\n",
990
+ " print(f\"\\n❌ Error: {e}\")\n",
991
+ " print(\"\\n💡 Solutions:\")\n",
992
+ " print(f\"1. Check if the folder exists: ls -la {IMAGE_PATH}\")\n",
993
+ " print(f\"2. Use absolute path: IMAGE_PATH = Path('/full/path/to/tetsu28_frames')\")\n",
994
+ " print(f\"3. Verify PNG files exist: ls {IMAGE_PATH}/*.png\")\n",
995
+ " print(f\"4. Current working directory: {Path.cwd()}\")\n",
996
+ " raise\n",
997
+ "\n",
998
+ "# ============================================================================\n",
999
+ "# COLMAP Reconstruction (MPS/CPU compatible)\n",
1000
+ "# ============================================================================\n",
1001
+ "def run_colmap_reconstruction(image_dir, colmap_dir):\n",
1002
+ " \"\"\"SfM reconstruction via COLMAP\"\"\"\n",
1003
+ " print(\"Running COLMAP SfM reconstruction...\")\n",
1004
+ " \n",
1005
+ " # Check for COLMAP command\n",
1006
+ " try:\n",
1007
+ " subprocess.run(['colmap', '--version'], capture_output=True, check=True)\n",
1008
+ " except FileNotFoundError:\n",
1009
+ " print(\"\\n\" + \"=\"*70)\n",
1010
+ " print(\"❌ Error: colmap command not found\")\n",
1011
+ " print(\"=\"*70)\n",
1012
+ " print(\"\\n[Solutions]\")\n",
1013
+ " print(\"\\n1. Mac:\")\n",
1014
+ " print(\" brew install colmap\")\n",
1015
+ " print(\"\\n2. Ubuntu:\")\n",
1016
+ " print(\" sudo apt-get update && sudo apt-get install colmap\")\n",
1017
+ " print(\"\\n3. Conda:\")\n",
1018
+ " print(\" conda install -c conda-forge colmap\")\n",
1019
+ " print(\"\\n4. Build from source:\")\n",
1020
+ " print(\" https://colmap.github.io/install.html\")\n",
1021
+ " print(\"\\nRestart kernel after installation.\")\n",
1022
+ " print(\"=\"*70)\n",
1023
+ " raise RuntimeError(\"COLMAP is not installed\")\n",
1024
+ " except subprocess.CalledProcessError:\n",
1025
+ " print(\"⚠️ Warning: COLMAP encountered an error but will try to continue\")\n",
1026
+ " \n",
1027
+ " database_path = os.path.join(colmap_dir, \"database.db\")\n",
1028
+ " sparse_dir = os.path.join(colmap_dir, \"sparse\")\n",
1029
+ " os.makedirs(sparse_dir, exist_ok=True)\n",
1030
+ " \n",
1031
+ " env = os.environ.copy()\n",
1032
+ " env['QT_QPA_PLATFORM'] = 'offscreen'\n",
1033
+ " \n",
1034
+ " # Use GPU for CUDA, CPU for others (MPS)\n",
1035
+ " use_colmap_gpu = '1' if DEVICE == 'cuda' else '0'\n",
1036
+ " \n",
1037
+ " # Feature Extraction\n",
1038
+ " print(\"1/4: Extracting features...\")\n",
1039
+ " try:\n",
1040
+ " result = subprocess.run([\n",
1041
+ " 'colmap', 'feature_extractor',\n",
1042
+ " '--database_path', database_path,\n",
1043
+ " '--image_path', image_dir,\n",
1044
+ " '--ImageReader.single_camera', '1',\n",
1045
+ " '--ImageReader.camera_model', 'OPENCV',\n",
1046
+ " '--SiftExtraction.use_gpu', use_colmap_gpu\n",
1047
+ " ], capture_output=True, text=True, env=env)\n",
1048
+ " \n",
1049
+ " if result.returncode != 0:\n",
1050
+ " print(f\"❌ Feature extraction error:\")\n",
1051
+ " print(f\"stdout: {result.stdout}\")\n",
1052
+ " print(f\"stderr: {result.stderr}\")\n",
1053
+ " raise subprocess.CalledProcessError(result.returncode, result.args)\n",
1054
+ " \n",
1055
+ " print(f\"✓ Feature extraction complete\")\n",
1056
+ " \n",
1057
+ " if os.path.exists(database_path):\n",
1058
+ " size_mb = os.path.getsize(database_path) / (1024 * 1024)\n",
1059
+ " print(f\" Database size: {size_mb:.2f} MB\")\n",
1060
+ " else:\n",
1061
+ " raise FileNotFoundError(f\"Database file not created: {database_path}\")\n",
1062
+ " \n",
1063
+ " except subprocess.CalledProcessError as e:\n",
1064
+ " print(f\"❌ COLMAP execution error: {e}\")\n",
1065
+ " raise\n",
1066
+ " \n",
1067
+ " # Feature Matching\n",
1068
+ " print(\"2/4: Matching features...\")\n",
1069
+ " try:\n",
1070
+ " result = subprocess.run([\n",
1071
+ " 'colmap', 'exhaustive_matcher',\n",
1072
+ " '--database_path', database_path,\n",
1073
+ " '--SiftMatching.use_gpu', use_colmap_gpu\n",
1074
+ " ], capture_output=True, text=True, env=env)\n",
1075
+ " \n",
1076
+ " if result.returncode != 0:\n",
1077
+ " print(f\"❌ Feature matching error\")\n",
1078
+ " raise subprocess.CalledProcessError(result.returncode, result.args)\n",
1079
+ " \n",
1080
+ " print(f\"✓ Feature matching complete\")\n",
1081
+ " except subprocess.CalledProcessError as e:\n",
1082
+ " print(f\"❌ Feature matching error: {e}\")\n",
1083
+ " raise\n",
1084
+ " \n",
1085
+ " # Sparse Reconstruction\n",
1086
+ " print(\"3/4: Sparse reconstruction...\")\n",
1087
+ " try:\n",
1088
+ " result = subprocess.run([\n",
1089
+ " 'colmap', 'mapper',\n",
1090
+ " '--database_path', database_path,\n",
1091
+ " '--image_path', image_dir,\n",
1092
+ " '--output_path', sparse_dir,\n",
1093
+ " '--Mapper.ba_global_max_num_iterations', '20',\n",
1094
+ " '--Mapper.ba_local_max_num_iterations', '10'\n",
1095
+ " ], capture_output=True, text=True, env=env)\n",
1096
+ " \n",
1097
+ " if result.returncode != 0:\n",
1098
+ " print(f\"❌ Sparse reconstruction error\")\n",
1099
+ " raise subprocess.CalledProcessError(result.returncode, result.args)\n",
1100
+ " \n",
1101
+ " print(f\"✓ Sparse reconstruction complete\")\n",
1102
+ " except subprocess.CalledProcessError as e:\n",
1103
+ " print(f\"❌ Sparse reconstruction error: {e}\")\n",
1104
+ " raise\n",
1105
+ " \n",
1106
+ " # Export as Text\n",
1107
+ " print(\"4/4: Exporting as text format...\")\n",
1108
+ " model_dir = os.path.join(sparse_dir, '0')\n",
1109
+ " if not os.path.exists(model_dir):\n",
1110
+ " subdirs = [d for d in os.listdir(sparse_dir) \n",
1111
+ " if os.path.isdir(os.path.join(sparse_dir, d))]\n",
1112
+ " if subdirs:\n",
1113
+ " model_dir = os.path.join(sparse_dir, subdirs[0])\n",
1114
+ " else:\n",
1115
+ " print(f\"❌ Error: Model directory not found\")\n",
1116
+ " raise FileNotFoundError(\"COLMAP reconstruction failed: Model directory not found\")\n",
1117
+ " \n",
1118
+ " try:\n",
1119
+ " result = subprocess.run([\n",
1120
+ " 'colmap', 'model_converter',\n",
1121
+ " '--input_path', model_dir,\n",
1122
+ " '--output_path', model_dir,\n",
1123
+ " '--output_type', 'TXT'\n",
1124
+ " ], capture_output=True, text=True, env=env)\n",
1125
+ " \n",
1126
+ " if result.returncode != 0:\n",
1127
+ " print(f\"❌ Model conversion error\")\n",
1128
+ " raise subprocess.CalledProcessError(result.returncode, result.args)\n",
1129
+ " \n",
1130
+ " print(f\"✓ Export to text complete\")\n",
1131
+ " \n",
1132
+ " required_files = ['cameras.txt', 'images.txt', 'points3D.txt']\n",
1133
+ " for filename in required_files:\n",
1134
+ " filepath = os.path.join(model_dir, filename)\n",
1135
+ " if os.path.exists(filepath):\n",
1136
+ " size_kb = os.path.getsize(filepath) / 1024\n",
1137
+ " print(f\" ✓ {filename}: {size_kb:.2f} KB\")\n",
1138
+ " else:\n",
1139
+ " print(f\" ⚠️ {filename}: Not found\")\n",
1140
+ " \n",
1141
+ " except subprocess.CalledProcessError as e:\n",
1142
+ " print(f\"❌ Model conversion error: {e}\")\n",
1143
+ " raise\n",
1144
+ " \n",
1145
+ " print(f\"✓ COLMAP reconstruction finished: {model_dir}\")\n",
1146
+ " return model_dir\n",
1147
+ "\n",
1148
+ "\n",
1149
+ "# ============================================================================\n",
1150
+ "# Camera Model Conversion\n",
1151
+ "# ============================================================================\n",
1152
+ "def convert_cameras_to_pinhole(input_file, output_file):\n",
1153
+ " \"\"\"Convert camera models to PINHOLE format\"\"\"\n",
1154
+ " print(f\"Reading camera file: {input_file}\")\n",
1155
+ " \n",
1156
+ " with open(input_file, 'r') as f:\n",
1157
+ " lines = f.readlines()\n",
1158
+ " \n",
1159
+ " converted_count = 0\n",
1160
+ " with open(output_file, 'w') as f:\n",
1161
+ " for line in lines:\n",
1162
+ " if line.startswith('#') or line.strip() == '':\n",
1163
+ " f.write(line)\n",
1164
+ " else:\n",
1165
+ " parts = line.strip().split()\n",
1166
+ " if len(parts) >= 4:\n",
1167
+ " cam_id = parts[0]\n",
1168
+ " model = parts[1]\n",
1169
+ " width = parts[2]\n",
1170
+ " height = parts[3]\n",
1171
+ " params = parts[4:]\n",
1172
+ " \n",
1173
+ " if model == \"PINHOLE\":\n",
1174
+ " f.write(line)\n",
1175
+ " elif model == \"OPENCV\":\n",
1176
+ " fx, fy, cx, cy = params[0], params[1], params[2], params[3]\n",
1177
+ " f.write(f\"{cam_id} PINHOLE {width} {height} {fx} {fy} {cx} {cy}\\n\")\n",
1178
+ " converted_count += 1\n",
1179
+ " else:\n",
1180
+ " fx = fy = max(float(width), float(height))\n",
1181
+ " cx = float(width) / 2\n",
1182
+ " cy = float(height) / 2\n",
1183
+ " f.write(f\"{cam_id} PINHOLE {width} {height} {fx} {fy} {cx} {cy}\\n\")\n",
1184
+ " converted_count += 1\n",
1185
+ " else:\n",
1186
+ " f.write(line)\n",
1187
+ " \n",
1188
+ " print(f\"Converted {converted_count} cameras to PINHOLE format\")\n",
1189
+ "\n",
1190
+ "\n",
1191
+ "def prepare_gaussian_splatting_data(image_dir, colmap_model_dir):\n",
1192
+ " \"\"\"Prepare data for Gaussian Splatting\"\"\"\n",
1193
+ " print(\"Preparing data for Gaussian Splatting...\")\n",
1194
+ " \n",
1195
+ " data_dir = f\"{WORK_DIR}/data/video\"\n",
1196
+ " os.makedirs(f\"{data_dir}/sparse/0\", exist_ok=True)\n",
1197
+ " os.makedirs(f\"{data_dir}/images\", exist_ok=True)\n",
1198
+ " \n",
1199
+ " # Copy images\n",
1200
+ " print(\"Copying images...\")\n",
1201
+ " img_count = 0\n",
1202
+ " for img_file in os.listdir(image_dir):\n",
1203
+ " if img_file.lower().endswith(('.jpg', '.jpeg', '.png')):\n",
1204
+ " shutil.copy(\n",
1205
+ " os.path.join(image_dir, img_file),\n",
1206
+ " f\"{data_dir}/images/{img_file}\"\n",
1207
+ " )\n",
1208
+ " img_count += 1\n",
1209
+ " print(f\"Copied {img_count} images\")\n",
1210
+ " \n",
1211
+ " # Convert and copy cameras\n",
1212
+ " print(\"Converting camera models to PINHOLE...\")\n",
1213
+ " convert_cameras_to_pinhole(\n",
1214
+ " os.path.join(colmap_model_dir, 'cameras.txt'),\n",
1215
+ " f\"{data_dir}/sparse/0/cameras.txt\"\n",
1216
+ " )\n",
1217
+ " \n",
1218
+ " # Copy other files\n",
1219
+ " for filename in ['images.txt', 'points3D.txt']:\n",
1220
+ " src = os.path.join(colmap_model_dir, filename)\n",
1221
+ " dst = f\"{data_dir}/sparse/0/{filename}\"\n",
1222
+ " if os.path.exists(src):\n",
1223
+ " shutil.copy(src, dst)\n",
1224
+ " print(f\"Copied {filename}\")\n",
1225
+ " else:\n",
1226
+ " print(f\"Warning: {filename} not found\")\n",
1227
+ " \n",
1228
+ " print(f\"Data preparation complete: {data_dir}\")\n",
1229
+ " return data_dir\n",
1230
+ "\n",
1231
+ "\n",
1232
+ "# ============================================================================\n",
1233
+ "# Image Size Normalization\n",
1234
+ "# ============================================================================\n",
1235
+ "def center_crop_and_resize(img, target_size):\n",
1236
+ " \"\"\"Center crop and resize image\"\"\"\n",
1237
+ " width, height = img.size\n",
1238
+ " crop_size = min(width, height)\n",
1239
+ " \n",
1240
+ " left = (width - crop_size) // 2\n",
1241
+ " top = (height - crop_size) // 2\n",
1242
+ " right = left + crop_size\n",
1243
+ " bottom = top + crop_size\n",
1244
+ " \n",
1245
+ " img_cropped = img.crop((left, top, right, bottom))\n",
1246
+ " img_resized = img_cropped.resize((target_size, target_size), Image.Resampling.LANCZOS)\n",
1247
+ " \n",
1248
+ " return img_resized\n",
1249
+ "\n",
1250
+ "\n",
1251
+ "def normalize_image_sizes(image_dir, output_dir=None, target_size=1200):\n",
1252
+ " \"\"\"Normalize image dimensions\"\"\"\n",
1253
+ " if output_dir is None:\n",
1254
+ " output_dir = image_dir\n",
1255
+ " \n",
1256
+ " os.makedirs(output_dir, exist_ok=True)\n",
1257
+ " print(f\"Normalizing image sizes to {target_size}x{target_size}...\")\n",
1258
+ " \n",
1259
+ " converted_count = 0\n",
1260
+ " \n",
1261
+ " for img_file in sorted(os.listdir(image_dir)):\n",
1262
+ " if not img_file.lower().endswith(('.jpg', '.jpeg', '.png')):\n",
1263
+ " continue\n",
1264
+ " \n",
1265
+ " input_path = os.path.join(image_dir, img_file)\n",
1266
+ " output_path = os.path.join(output_dir, img_file)\n",
1267
+ " \n",
1268
+ " try:\n",
1269
+ " img = Image.open(input_path)\n",
1270
+ " original_size = img.size\n",
1271
+ " \n",
1272
+ " img = center_crop_and_resize(img, target_size)\n",
1273
+ " img.save(output_path, quality=95)\n",
1274
+ " converted_count += 1\n",
1275
+ " \n",
1276
+ " print(f\" ✓ {img_file}: {original_size} → {target_size}x{target_size}\")\n",
1277
+ " \n",
1278
+ " except Exception as e:\n",
1279
+ " print(f\" ✗ Error processing {img_file}: {e}\")\n",
1280
+ " \n",
1281
+ " print(f\"\\nConversion complete: {converted_count} images\")\n",
1282
+ " return converted_count\n",
1283
+ "\n",
1284
+ "\n",
1285
+ "# ============================================================================\n",
1286
+ "# Training and Rendering\n",
1287
+ "# ============================================================================\n",
1288
+ "def train_gaussian_splatting(data_dir, iterations=3000):\n",
1289
+ " \"\"\"Train Gaussian Splatting model\"\"\"\n",
1290
+ " print(f\"Training Gaussian Splatting model for {iterations} iterations...\")\n",
1291
+ " \n",
1292
+ " model_path = f\"{WORK_DIR}/output/video\"\n",
1293
+ " \n",
1294
+ " cmd = [\n",
1295
+ " sys.executable, 'train.py',\n",
1296
+ " '-s', data_dir,\n",
1297
+ " '-m', model_path,\n",
1298
+ " '--iterations', str(iterations),\n",
1299
+ " '--eval'\n",
1300
+ " ]\n",
1301
+ " \n",
1302
+ " subprocess.run(cmd, cwd=WORK_DIR, check=True)\n",
1303
+ " \n",
1304
+ " return model_path\n",
1305
+ "\n",
1306
+ "\n",
1307
+ "def render_video(model_path, output_video_path, iteration=3000):\n",
1308
+ " \"\"\"Render video from trained model\"\"\"\n",
1309
+ " print(\"Rendering video...\")\n",
1310
+ " \n",
1311
+ " cmd = [\n",
1312
+ " sys.executable, 'render.py',\n",
1313
+ " '-m', model_path,\n",
1314
+ " '--iteration', str(iteration)\n",
1315
+ " ]\n",
1316
+ " \n",
1317
+ " subprocess.run(cmd, cwd=WORK_DIR, check=True)\n",
1318
+ " \n",
1319
+ " possible_dirs = [\n",
1320
+ " f\"{model_path}/test/ours_{iteration}/renders\",\n",
1321
+ " f\"{model_path}/train/ours_{iteration}/renders\",\n",
1322
+ " ]\n",
1323
+ " \n",
1324
+ " render_dir = None\n",
1325
+ " for test_dir in possible_dirs:\n",
1326
+ " if os.path.exists(test_dir):\n",
1327
+ " render_dir = test_dir\n",
1328
+ " print(f\"Render directory found: {render_dir}\")\n",
1329
+ " break\n",
1330
+ " \n",
1331
+ " if render_dir and os.path.exists(render_dir):\n",
1332
+ " render_imgs = sorted([f for f in os.listdir(render_dir) if f.endswith('.png')])\n",
1333
+ " \n",
1334
+ " if render_imgs:\n",
1335
+ " print(f\"Found {len(render_imgs)} rendered images\")\n",
1336
+ " \n",
1337
+ " subprocess.run([\n",
1338
+ " 'ffmpeg', '-y',\n",
1339
+ " '-framerate', '30',\n",
1340
+ " '-pattern_type', 'glob',\n",
1341
+ " '-i', f\"{render_dir}/*.png\",\n",
1342
+ " '-c:v', 'libx264',\n",
1343
+ " '-pix_fmt', 'yuv420p',\n",
1344
+ " '-crf', '18',\n",
1345
+ " output_video_path\n",
1346
+ " ], check=True)\n",
1347
+ " \n",
1348
+ " print(f\"Video saved: {output_video_path}\")\n",
1349
+ " return True\n",
1350
+ " \n",
1351
+ " print(\"Error: Render directory not found or no images rendered\")\n",
1352
+ " return False\n",
1353
+ "\n",
1354
+ "\n",
1355
+ "def create_gif(video_path, gif_path):\n",
1356
+ " \"\"\"Create animated GIF from MP4 video\"\"\"\n",
1357
+ " print(\"Creating animated GIF...\")\n",
1358
+ " \n",
1359
+ " subprocess.run([\n",
1360
+ " 'ffmpeg', '-y',\n",
1361
+ " '-i', video_path,\n",
1362
+ " '-vf', 'setpts=8*PTS,fps=10,scale=720:-1:flags=lanczos',\n",
1363
+ " '-loop', '0',\n",
1364
+ " gif_path\n",
1365
+ " ], check=True)\n",
1366
+ " \n",
1367
+ " if os.path.exists(gif_path):\n",
1368
+ " size_mb = os.path.getsize(gif_path) / (1024 * 1024)\n",
1369
+ " print(f\"GIF created: {gif_path} ({size_mb:.2f} MB)\")\n",
1370
+ " return True\n",
1371
+ " \n",
1372
+ " return False\n",
1373
+ "\n",
1374
+ "\n",
1375
+ "# ============================================================================\n",
1376
+ "# Main Execution Function\n",
1377
+ "# ============================================================================\n",
1378
+ "def main():\n",
1379
+ " \"\"\"Main execution flow\"\"\"\n",
1380
+ " print(\"=\"*60)\n",
1381
+ " print(\"Gaussian Splatting Generation (Mac MPS Support)\")\n",
1382
+ " print(\"=\"*60)\n",
1383
+ " print(f\"Using Device: {DEVICE}\")\n",
1384
+ " print(\"=\"*60)\n",
1385
+ " \n",
1386
+ " try:\n",
1387
+ " # Step 1: Environment Setup\n",
1388
+ " setup_environment()\n",
1389
+ " \n",
1390
+ " # Step 2: Frame Extraction\n",
1391
+ " frame_dir = f\"{COLMAP_DIR}/images\"\n",
1392
+ " process_frames_from_folder(IMAGE_PATH, frame_dir, max_frames=30)\n",
1393
+ " \n",
1394
+ " # Step 2.5: Size Normalization\n",
1395
+ " print(\"\\n\" + \"=\"*60)\n",
1396
+ " print(\"Step 2.5: Normalizing image sizes...\")\n",
1397
+ " print(\"=\"*60)\n",
1398
+ " normalize_image_sizes(frame_dir, target_size=1280)\n",
1399
+ " \n",
1400
+ " # Step 3: Estimate Camera Info via COLMAP\n",
1401
+ " colmap_model_dir = run_colmap_reconstruction(frame_dir, COLMAP_DIR)\n",
1402
+ " \n",
1403
+ " # Step 4: Prepare GS Data\n",
1404
+ " data_dir = prepare_gaussian_splatting_data(frame_dir, colmap_model_dir)\n",
1405
+ " \n",
1406
+ " # Step 5: Train Model\n",
1407
+ " # Set low iterations (60) for testing\n",
1408
+ " model_path = train_gaussian_splatting(data_dir, iterations=60)\n",
1409
+ " \n",
1410
+ " # Step 6: Render Video\n",
1411
+ " os.makedirs(OUTPUT_DIR, exist_ok=True)\n",
1412
+ " output_video = f\"{OUTPUT_DIR}/gaussian_splatting_video.mp4\"\n",
1413
+ " success = render_video(model_path, output_video, iteration=60)\n",
1414
+ " \n",
1415
+ " if success:\n",
1416
+ " print(\"=\"*60)\n",
1417
+ " print(f\"Success! Video generation complete: {output_video}\")\n",
1418
+ " print(\"=\"*60)\n",
1419
+ " \n",
1420
+ " # Create GIF\n",
1421
+ " output_gif = f\"{OUTPUT_DIR}/gaussian_splatting_video.gif\"\n",
1422
+ " create_gif(output_video, output_gif)\n",
1423
+ " \n",
1424
+ " print(f\"\\nResult Files:\")\n",
1425
+ " print(f\" Video: {output_video}\")\n",
1426
+ " print(f\" GIF: {output_gif}\")\n",
1427
+ " else:\n",
1428
+ " print(\"Warning: Rendering completed but video was not generated\")\n",
1429
+ " \n",
1430
+ " except Exception as e:\n",
1431
+ " print(f\"Error: {str(e)}\")\n",
1432
+ " import traceback\n",
1433
+ " traceback.print_exc()\n",
1434
+ "\n",
1435
+ "\n",
1436
+ "if __name__ == \"__main__\":\n",
1437
+ " main()"
1438
+ ]
1439
+ },
1440
+ {
1441
+ "cell_type": "markdown",
1442
+ "id": "55b3bfd0",
1443
+ "metadata": {
1444
+ "papermill": {
1445
+ "duration": 0.021856,
1446
+ "end_time": "2025-12-27T17:30:13.828385",
1447
+ "exception": false,
1448
+ "start_time": "2025-12-27T17:30:13.806529",
1449
+ "status": "completed"
1450
+ },
1451
+ "tags": []
1452
+ },
1453
+ "source": [
1454
+ "**Please check the result in 3D Gaussian Splat Viewer**\n",
1455
+ "\n",
1456
+ "https://splat-three.vercel.app/?url=tetsu28_frame.splat"
1457
+ ]
1458
+ }
1459
+ ],
1460
+ "metadata": {
1461
+ "kaggle": {
1462
+ "accelerator": "none",
1463
+ "dataSources": [
1464
+ {
1465
+ "datasetId": 1429416,
1466
+ "sourceId": 14308076,
1467
+ "sourceType": "datasetVersion"
1468
+ }
1469
+ ],
1470
+ "isGpuEnabled": false,
1471
+ "isInternetEnabled": true,
1472
+ "language": "python",
1473
+ "sourceType": "notebook"
1474
+ },
1475
+ "kernelspec": {
1476
+ "display_name": "kaggle_local_env",
1477
+ "language": "python",
1478
+ "name": "python3"
1479
+ },
1480
+ "language_info": {
1481
+ "codemirror_mode": {
1482
+ "name": "ipython",
1483
+ "version": 3
1484
+ },
1485
+ "file_extension": ".py",
1486
+ "mimetype": "text/x-python",
1487
+ "name": "python",
1488
+ "nbconvert_exporter": "python",
1489
+ "pygments_lexer": "ipython3",
1490
+ "version": "3.11.14"
1491
+ },
1492
+ "papermill": {
1493
+ "default_parameters": {},
1494
+ "duration": 12257.123004,
1495
+ "end_time": "2025-12-27T17:30:15.493589",
1496
+ "environment_variables": {},
1497
+ "exception": null,
1498
+ "input_path": "__notebook__.ipynb",
1499
+ "output_path": "__notebook__.ipynb",
1500
+ "parameters": {},
1501
+ "start_time": "2025-12-27T14:05:58.370585",
1502
+ "version": "2.6.0"
1503
+ }
1504
+ },
1505
+ "nbformat": 4,
1506
+ "nbformat_minor": 5
1507
+ }