stpete2 commited on
Commit
06662aa
·
verified ·
1 Parent(s): 1748e34

Upload 2 files

Browse files
biplet_asmk_mast3r_ps2_gs_kg_32_colab_01.ipynb ADDED
@@ -0,0 +1,1365 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "kernelspec": {
4
+ "name": "python3",
5
+ "display_name": "Python 3",
6
+ "language": "python"
7
+ },
8
+ "language_info": {
9
+ "name": "python",
10
+ "version": "3.12.12",
11
+ "mimetype": "text/x-python",
12
+ "codemirror_mode": {
13
+ "name": "ipython",
14
+ "version": 3
15
+ },
16
+ "pygments_lexer": "ipython3",
17
+ "nbconvert_exporter": "python",
18
+ "file_extension": ".py"
19
+ },
20
+ "colab": {
21
+ "provenance": [],
22
+ "gpuType": "T4"
23
+ },
24
+ "accelerator": "GPU",
25
+ "kaggle": {
26
+ "accelerator": "nvidiaTeslaT4",
27
+ "dataSources": [
28
+ {
29
+ "sourceId": 14571475,
30
+ "sourceType": "datasetVersion",
31
+ "datasetId": 1429416
32
+ }
33
+ ],
34
+ "dockerImageVersionId": 31260,
35
+ "isInternetEnabled": true,
36
+ "language": "python",
37
+ "sourceType": "notebook",
38
+ "isGpuEnabled": true
39
+ }
40
+ },
41
+ "nbformat_minor": 0,
42
+ "nbformat": 4,
43
+ "cells": [
44
+ {
45
+ "cell_type": "markdown",
46
+ "source": [
47
+ "# **biplet-asmk-mast3r-ps2-gs-kg-32-colab**\n",
48
+ "\n"
49
+ ],
50
+ "metadata": {
51
+ "id": "qDQLX3PArmh8"
52
+ }
53
+ },
54
+ {
55
+ "cell_type": "markdown",
56
+ "source": [
57
+ "https://huggingface.co/datasets/stpete2/ipynb/blob/main/biplet-asmk-mast3r-ps2-gs-kg-32.ipynb"
58
+ ],
59
+ "metadata": {
60
+ "id": "Yhla_oBUjLmD"
61
+ }
62
+ },
63
+ {
64
+ "cell_type": "code",
65
+ "source": [
66
+ "#これを元にcolab化 2025/01/22 16:00"
67
+ ],
68
+ "metadata": {
69
+ "id": "UyF0gaG8jOXu"
70
+ },
71
+ "execution_count": null,
72
+ "outputs": []
73
+ },
74
+ {
75
+ "cell_type": "markdown",
76
+ "source": [
77
+ "v.32 全面見直し"
78
+ ],
79
+ "metadata": {
80
+ "id": "uNZNREeejLmD"
81
+ }
82
+ },
83
+ {
84
+ "cell_type": "code",
85
+ "source": [],
86
+ "metadata": {
87
+ "trusted": true,
88
+ "id": "yH63Q7yCjLmE"
89
+ },
90
+ "outputs": [],
91
+ "execution_count": null
92
+ },
93
+ {
94
+ "cell_type": "code",
95
+ "source": [
96
+ "# =====================================================================\n",
97
+ "# CELL 1: Install Dependencies\n",
98
+ "# =====================================================================\n",
99
+ "!pip install roma einops timm huggingface_hub\n",
100
+ "!pip install opencv-python pillow tqdm pyaml cython plyfile\n",
101
+ "!pip install pycolmap trimesh\n",
102
+ "!pip uninstall -y numpy scipy\n",
103
+ "!pip install numpy==1.26.4 scipy==1.11.4\n",
104
+ "break"
105
+ ],
106
+ "metadata": {
107
+ "trusted": true,
108
+ "id": "h5Exo6FBjLmE"
109
+ },
110
+ "outputs": [],
111
+ "execution_count": null
112
+ },
113
+ {
114
+ "cell_type": "code",
115
+ "source": [
116
+ "# =====================================================================\n",
117
+ "# CELL 2: Restart Kernel (Run this after Cell 1)\n",
118
+ "# =====================================================================\n",
119
+ "# Restart kernel, then run from this cell\n",
120
+ "\n",
121
+ "# =====================================================================\n",
122
+ "# CELL 3: Verify NumPy Version\n",
123
+ "# =====================================================================\n",
124
+ "import numpy as np\n",
125
+ "print(f\"✓ np: {np.__version__} - {np.__file__}\")\n",
126
+ "!pip show numpy | grep Version\n",
127
+ "\n",
128
+ "# =====================================================================\n",
129
+ "# CELL 4: Verify Roma Installation\n",
130
+ "# =====================================================================\n",
131
+ "try:\n",
132
+ " import roma\n",
133
+ " print(\"✓ roma is installed\")\n",
134
+ "except ModuleNotFoundError:\n",
135
+ " print(\"⚠️ roma not found, installing...\")\n",
136
+ " !pip install roma\n",
137
+ " import roma\n",
138
+ " print(\"✓ roma installed\")"
139
+ ],
140
+ "metadata": {
141
+ "trusted": true,
142
+ "id": "XgxGC30cjLmF"
143
+ },
144
+ "outputs": [],
145
+ "execution_count": null
146
+ },
147
+ {
148
+ "cell_type": "code",
149
+ "source": [
150
+ "# =====================================================================\n",
151
+ "# CELL 5: Clone Repositories\n",
152
+ "# =====================================================================\n",
153
+ "import os\n",
154
+ "import sys\n",
155
+ "\n",
156
+ "# MASt3Rをクローン\n",
157
+ "if not os.path.exists('/content/mast3r'):\n",
158
+ " print(\"Cloning MASt3R repository...\")\n",
159
+ " !git clone --recursive https://github.com/naver/mast3r.git /content/mast3r\n",
160
+ " print(\"✓ MASt3R cloned\")\n",
161
+ "else:\n",
162
+ " print(\"✓ MASt3R already exists\")\n",
163
+ "\n",
164
+ "# DUSt3Rをクローン(MASt3R内に必要)\n",
165
+ "if not os.path.exists('/content/mast3r/dust3r'):\n",
166
+ " print(\"Cloning DUSt3R repository...\")\n",
167
+ " !git clone --recursive https://github.com/naver/dust3r.git /content/mast3r/dust3r\n",
168
+ " print(\"✓ DUSt3R cloned\")\n",
169
+ "else:\n",
170
+ " print(\"✓ DUSt3R already exists\")\n",
171
+ "\n",
172
+ "# ASMKをクローン\n",
173
+ "if not os.path.exists('/content/asmk'):\n",
174
+ " print(\"Cloning ASMK repository...\")\n",
175
+ " !git clone https://github.com/jenicek/asmk.git /content/asmk\n",
176
+ " print(\"✓ ASMK cloned\")\n",
177
+ "else:\n",
178
+ " print(\"✓ ASMK already exists\")\n",
179
+ "\n",
180
+ "# パスを追加\n",
181
+ "sys.path.insert(0, '/content/mast3r')\n",
182
+ "sys.path.insert(0, '/content/mast3r/dust3r')\n",
183
+ "sys.path.insert(0, '/content/asmk')\n",
184
+ "\n",
185
+ "# 確認\n",
186
+ "try:\n",
187
+ " from dust3r.model import AsymmetricCroCo3DStereo\n",
188
+ " print(\"✓ dust3r.model imported successfully\")\n",
189
+ "except ImportError as e:\n",
190
+ " print(f\"✗ Import error: {e}\")\n",
191
+ "\n",
192
+ "# croco(MASt3Rの依存関係)もクローン\n",
193
+ "if not os.path.exists('/content/mast3r/croco'):\n",
194
+ " print(\"Cloning CroCo repository...\")\n",
195
+ " !git clone --recursive https://github.com/naver/croco.git /content/mast3r/croco\n",
196
+ " print(\"✓ CroCo cloned\")\n",
197
+ "\n",
198
+ "# CroCo v2の依存関係\n",
199
+ "if not os.path.exists('/content/mast3r/croco/models/curope'):\n",
200
+ " print(\"Cloning CuRoPe...\")\n",
201
+ " !git clone --recursive https://github.com/naver/curope.git /content/mast3r/croco/models/curope\n",
202
+ " print(\"✓ CuRoPe cloned\")\n",
203
+ "\n",
204
+ "# =====================================================================\n",
205
+ "# CELL 6: Clone and Build Gaussian Splatting\n",
206
+ "# =====================================================================\n",
207
+ "print(\"\\n\" + \"=\"*70)\n",
208
+ "print(\"STEP 2: Clone Gaussian Splatting\")\n",
209
+ "print(\"=\"*70)\n",
210
+ "WORK_DIR = \"/content/gaussian-splatting\"\n",
211
+ "\n",
212
+ "import subprocess\n",
213
+ "if not os.path.exists(WORK_DIR):\n",
214
+ " subprocess.run([\n",
215
+ " \"git\", \"clone\", \"--recursive\",\n",
216
+ " \"https://github.com/graphdeco-inria/gaussian-splatting.git\",\n",
217
+ " WORK_DIR\n",
218
+ " ], capture_output=True)\n",
219
+ " print(\"✓ Cloned\")\n",
220
+ "else:\n",
221
+ " print(\"✓ Already exists\")\n",
222
+ "\n",
223
+ "# インストールが必要なディレクトリ\n",
224
+ "submodules = [\n",
225
+ " \"/content/gaussian-splatting/submodules/diff-gaussian-rasterization\",\n",
226
+ " \"/content/gaussian-splatting/submodules/simple-knn\"\n",
227
+ "]\n",
228
+ "\n",
229
+ "for path in submodules:\n",
230
+ " print(f\"Installing {path}...\")\n",
231
+ " subprocess.run([\"pip\", \"install\", path], check=True)\n",
232
+ "\n",
233
+ "print(\"✓ Custom CUDA modules installed.\")\n",
234
+ "\n",
235
+ "# =====================================================================\n",
236
+ "# CELL 7: Verify NumPy Again\n",
237
+ "# =====================================================================\n",
238
+ "import numpy as np\n",
239
+ "print(f\"✓ np: {np.__version__} - {np.__file__}\")\n",
240
+ "!pip show numpy | grep Version"
241
+ ],
242
+ "metadata": {
243
+ "trusted": true,
244
+ "id": "EF_Z8VDLjLmF"
245
+ },
246
+ "outputs": [],
247
+ "execution_count": null
248
+ },
249
+ {
250
+ "cell_type": "code",
251
+ "source": [
252
+ "# =====================================================================\n",
253
+ "# CELL 8: Import Core Libraries and Configure Memory\n",
254
+ "# =====================================================================\n",
255
+ "import os\n",
256
+ "import sys\n",
257
+ "import gc\n",
258
+ "import torch\n",
259
+ "import numpy as np\n",
260
+ "from pathlib import Path\n",
261
+ "from tqdm import tqdm\n",
262
+ "import torch.nn.functional as F\n",
263
+ "import shutil\n",
264
+ "from PIL import Image\n",
265
+ "\n",
266
+ "# MEMORY MANAGEMENT\n",
267
+ "os.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'expandable_segments:True'\n",
268
+ "\n",
269
+ "def clear_memory():\n",
270
+ " \"\"\"メモリクリア関数\"\"\"\n",
271
+ " gc.collect()\n",
272
+ " if torch.cuda.is_available():\n",
273
+ " torch.cuda.empty_cache()\n",
274
+ " torch.cuda.synchronize()\n",
275
+ "\n",
276
+ "# CONFIGURATION\n",
277
+ "class Config:\n",
278
+ " DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
279
+ " MAST3R_WEIGHTS = \"naver/MASt3R_ViTLarge_BaseDecoder_512_catmlpdpt_metric\"\n",
280
+ " DUST3R_WEIGHTS = \"naver/DUSt3R_ViTLarge_BaseDecoder_512_dpt\"\n",
281
+ " RETRIEVAL_TOPK = 10\n",
282
+ " IMAGE_SIZE = 224\n",
283
+ "\n",
284
+ "# =====================================================================\n",
285
+ "# CELL 9: Image Preprocessing Functions\n",
286
+ "# =====================================================================\n",
287
+ "def normalize_image_sizes_biplet(input_dir, output_dir=None, size=1024):\n",
288
+ " \"\"\"\n",
289
+ " Generates two square crops (Left & Right or Top & Bottom)\n",
290
+ " from each image in a directory.\n",
291
+ " \"\"\"\n",
292
+ " if output_dir is None:\n",
293
+ " output_dir = input_dir + \"_biplet\"\n",
294
+ "\n",
295
+ " os.makedirs(output_dir, exist_ok=True)\n",
296
+ "\n",
297
+ " print(f\"\\n=== Generating Biplet Crops ({size}x{size}) ===\")\n",
298
+ "\n",
299
+ " converted_count = 0\n",
300
+ " size_stats = {}\n",
301
+ "\n",
302
+ " for img_file in tqdm(sorted(os.listdir(input_dir)), desc=\"Creating biplets\"):\n",
303
+ " if not img_file.lower().endswith(('.jpg', '.jpeg', '.png')):\n",
304
+ " continue\n",
305
+ "\n",
306
+ " input_path = os.path.join(input_dir, img_file)\n",
307
+ "\n",
308
+ " try:\n",
309
+ " img = Image.open(input_path)\n",
310
+ " original_size = img.size\n",
311
+ "\n",
312
+ " size_key = f\"{original_size[0]}x{original_size[1]}\"\n",
313
+ " size_stats[size_key] = size_stats.get(size_key, 0) + 1\n",
314
+ "\n",
315
+ " # Generate 2 crops\n",
316
+ " crops = generate_two_crops(img, size)\n",
317
+ "\n",
318
+ " base_name, ext = os.path.splitext(img_file)\n",
319
+ " for mode, cropped_img in crops.items():\n",
320
+ " output_path = os.path.join(output_dir, f\"{base_name}_{mode}{ext}\")\n",
321
+ " cropped_img.save(output_path, quality=95)\n",
322
+ "\n",
323
+ " converted_count += 1\n",
324
+ "\n",
325
+ " except Exception as e:\n",
326
+ " print(f\" ✗ Error processing {img_file}: {e}\")\n",
327
+ "\n",
328
+ " print(f\"\\n✓ Biplet generation complete:\")\n",
329
+ " print(f\" Source images: {converted_count}\")\n",
330
+ " print(f\" Biplet crops generated: {converted_count * 2}\")\n",
331
+ " print(f\" Original size distribution: {size_stats}\")\n",
332
+ "\n",
333
+ " return output_dir\n",
334
+ "\n",
335
+ "\n",
336
+ "def generate_two_crops(img, size):\n",
337
+ " \"\"\"\n",
338
+ " Crops the image into a square and returns 2 variations\n",
339
+ " \"\"\"\n",
340
+ " width, height = img.size\n",
341
+ " crop_size = min(width, height)\n",
342
+ " crops = {}\n",
343
+ "\n",
344
+ " if width > height:\n",
345
+ " # Landscape → Left & Right\n",
346
+ " positions = {\n",
347
+ " 'left': 0,\n",
348
+ " 'right': width - crop_size\n",
349
+ " }\n",
350
+ " for mode, x_offset in positions.items():\n",
351
+ " box = (x_offset, 0, x_offset + crop_size, crop_size)\n",
352
+ " crops[mode] = img.crop(box).resize(\n",
353
+ " (size, size),\n",
354
+ " Image.Resampling.LANCZOS\n",
355
+ " )\n",
356
+ " else:\n",
357
+ " # Portrait or Square → Top & Bottom\n",
358
+ " positions = {\n",
359
+ " 'top': 0,\n",
360
+ " 'bottom': height - crop_size\n",
361
+ " }\n",
362
+ " for mode, y_offset in positions.items():\n",
363
+ " box = (0, y_offset, crop_size, y_offset + crop_size)\n",
364
+ " crops[mode] = img.crop(box).resize(\n",
365
+ " (size, size),\n",
366
+ " Image.Resampling.LANCZOS\n",
367
+ " )\n",
368
+ "\n",
369
+ " return crops\n",
370
+ "\n",
371
+ "# =====================================================================\n",
372
+ "# CELL 10: Image Loading Function\n",
373
+ "# =====================================================================\n",
374
+ "def load_images_from_directory(image_dir, max_images=200):\n",
375
+ " \"\"\"ディレクトリから画像をロード\"\"\"\n",
376
+ " print(f\"\\nLoading images from: {image_dir}\")\n",
377
+ "\n",
378
+ " valid_extensions = {'.jpg', '.jpeg', '.png', '.bmp'}\n",
379
+ " image_paths = []\n",
380
+ "\n",
381
+ " for ext in valid_extensions:\n",
382
+ " image_paths.extend(sorted(Path(image_dir).glob(f'*{ext}')))\n",
383
+ " image_paths.extend(sorted(Path(image_dir).glob(f'*{ext.upper()}')))\n",
384
+ "\n",
385
+ " image_paths = sorted(set(str(p) for p in image_paths))\n",
386
+ "\n",
387
+ " if len(image_paths) > max_images:\n",
388
+ " print(f\"⚠️ Limiting from {len(image_paths)} to {max_images} images\")\n",
389
+ " image_paths = image_paths[:max_images]\n",
390
+ "\n",
391
+ " print(f\"✓ Found {len(image_paths)} images\")\n",
392
+ " return image_paths"
393
+ ],
394
+ "metadata": {
395
+ "trusted": true,
396
+ "id": "_rFAsFGDjLmF"
397
+ },
398
+ "outputs": [],
399
+ "execution_count": null
400
+ },
401
+ {
402
+ "cell_type": "code",
403
+ "source": [
404
+ "# =====================================================================\n",
405
+ "# CELL 11: MASt3R Model Loading\n",
406
+ "# =====================================================================\n",
407
+ "def load_mast3r_model(device):\n",
408
+ " \"\"\"MASt3Rモデルをロード\"\"\"\n",
409
+ " print(\"\\n=== Loading MASt3R Model ===\")\n",
410
+ "\n",
411
+ " if '/content/mast3r' not in sys.path:\n",
412
+ " sys.path.insert(0, '/content/mast3r')\n",
413
+ " if '/content/mast3r/dust3r' not in sys.path:\n",
414
+ " sys.path.insert(0, '/content/mast3r/dust3r')\n",
415
+ "\n",
416
+ " from dust3r.model import AsymmetricCroCo3DStereo\n",
417
+ "\n",
418
+ " try:\n",
419
+ " print(f\"Attempting to load: {Config.MAST3R_WEIGHTS}\")\n",
420
+ " model = AsymmetricCroCo3DStereo.from_pretrained(Config.MAST3R_WEIGHTS).to(device)\n",
421
+ " print(\"✓ Loaded MASt3R model\")\n",
422
+ " except Exception as e:\n",
423
+ " print(f\"⚠️ Failed to load MASt3R: {e}\")\n",
424
+ " print(f\"Trying DUSt3R instead: {Config.DUST3R_WEIGHTS}\")\n",
425
+ " model = AsymmetricCroCo3DStereo.from_pretrained(Config.DUST3R_WEIGHTS).to(device)\n",
426
+ " print(\"✓ Loaded DUSt3R model as fallback\")\n",
427
+ "\n",
428
+ " model.eval()\n",
429
+ " print(f\"✓ Model loaded on {device}\")\n",
430
+ " return model\n",
431
+ "\n",
432
+ "# =====================================================================\n",
433
+ "# CELL 12: Feature Extraction (FIXED)\n",
434
+ "# =====================================================================\n",
435
+ "def extract_mast3r_features(model, image_paths, device, batch_size=1):\n",
436
+ " \"\"\"MASt3Rモデルを使用して特徴量を抽出(修正版)\"\"\"\n",
437
+ " print(\"\\n=== Extracting MASt3R Features ===\")\n",
438
+ " from dust3r.utils.image import load_images\n",
439
+ " from dust3r.inference import inference\n",
440
+ "\n",
441
+ " all_features = []\n",
442
+ "\n",
443
+ " for i in tqdm(range(len(image_paths)), desc=\"Features\"):\n",
444
+ " img_path = image_paths[i]\n",
445
+ "\n",
446
+ " # 同じ画像を2回ロード(ペアとして)\n",
447
+ " images = load_images([img_path, img_path], size=Config.IMAGE_SIZE)\n",
448
+ " pairs = [(images[0], images[1])]\n",
449
+ "\n",
450
+ " with torch.no_grad():\n",
451
+ " output = inference(pairs, model, device, batch_size=1)\n",
452
+ "\n",
453
+ " try:\n",
454
+ " # outputから特徴量を抽出(修正版)\n",
455
+ " if isinstance(output, dict):\n",
456
+ " if 'pred1' in output:\n",
457
+ " pred1 = output['pred1']\n",
458
+ " if isinstance(pred1, dict):\n",
459
+ " # 'desc'または'conf'を優先的に使用\n",
460
+ " if 'desc' in pred1:\n",
461
+ " desc = pred1['desc']\n",
462
+ " elif 'conf' in pred1:\n",
463
+ " desc = pred1['conf']\n",
464
+ " elif 'pts3d' in pred1:\n",
465
+ " desc = pred1['pts3d']\n",
466
+ " else:\n",
467
+ " desc = list(pred1.values())[0]\n",
468
+ " else:\n",
469
+ " desc = pred1\n",
470
+ " elif 'view1' in output:\n",
471
+ " view1 = output['view1']\n",
472
+ " if isinstance(view1, dict):\n",
473
+ " desc = view1.get('desc', view1.get('conf', view1.get('pts3d', list(view1.values())[0])))\n",
474
+ " else:\n",
475
+ " desc = view1\n",
476
+ " else:\n",
477
+ " desc = list(output.values())[0]\n",
478
+ " elif isinstance(output, tuple) and len(output) == 2:\n",
479
+ " view1, view2 = output\n",
480
+ " if isinstance(view1, dict):\n",
481
+ " desc = view1.get('desc', view1.get('conf', view1.get('pts3d', list(view1.values())[0])))\n",
482
+ " else:\n",
483
+ " desc = view1\n",
484
+ " elif isinstance(output, list):\n",
485
+ " item = output[0]\n",
486
+ " if isinstance(item, dict):\n",
487
+ " desc = item.get('desc', item.get('conf', item.get('pts3d', list(item.values())[0])))\n",
488
+ " else:\n",
489
+ " desc = item\n",
490
+ " else:\n",
491
+ " desc = output\n",
492
+ "\n",
493
+ " # テンソルをCPUに移動して保存\n",
494
+ " if isinstance(desc, torch.Tensor):\n",
495
+ " desc = desc.detach().cpu()\n",
496
+ "\n",
497
+ " # 4次元の場合はbatch次元を削除\n",
498
+ " if desc.dim() == 4:\n",
499
+ " desc = desc.squeeze(0)\n",
500
+ "\n",
501
+ " # 特徴量の次元が小さすぎる場合(RGB画像など)は平均プーリング\n",
502
+ " if desc.shape[-1] < 16:\n",
503
+ " # [H, W, 3] -> [H, W, 64] に拡張\n",
504
+ " desc = desc.unsqueeze(-1).repeat(1, 1, 1, 64 // desc.shape[-1]).reshape(desc.shape[0], desc.shape[1], -1)\n",
505
+ "\n",
506
+ " all_features.append(desc)\n",
507
+ "\n",
508
+ " except Exception as e:\n",
509
+ " print(f\"⚠️ Error extracting features for image {i}: {e}\")\n",
510
+ " # デフォルト特徴量\n",
511
+ " all_features.append(torch.zeros((Config.IMAGE_SIZE, Config.IMAGE_SIZE, 64)))\n",
512
+ "\n",
513
+ " # メモリクリア\n",
514
+ " del output, images, pairs\n",
515
+ " if i % 10 == 0:\n",
516
+ " torch.cuda.empty_cache()\n",
517
+ "\n",
518
+ " print(f\"✓ Extracted features for {len(all_features)} images\")\n",
519
+ " if all_features:\n",
520
+ " first_feat = all_features[0]\n",
521
+ " if isinstance(first_feat, torch.Tensor):\n",
522
+ " print(f\" Feature shape: {first_feat.shape}\")\n",
523
+ "\n",
524
+ " return all_features\n",
525
+ "\n",
526
+ "# =====================================================================\n",
527
+ "# CELL 13: ASMK Similarity Computation (FIXED)\n",
528
+ "# =====================================================================\n",
529
+ "def compute_asmk_similarity(features, codebook=None):\n",
530
+ " \"\"\"ASMKを使用して類似度行列を計算(修正版)\"\"\"\n",
531
+ " print(\"\\n=== Computing ASMK Similarity ===\")\n",
532
+ "\n",
533
+ " n_images = len(features)\n",
534
+ " similarity_matrix = np.zeros((n_images, n_images), dtype=np.float32)\n",
535
+ "\n",
536
+ " # 各特徴量をグローバル記述子に変換\n",
537
+ " global_features = []\n",
538
+ "\n",
539
+ " for feat in features:\n",
540
+ " if isinstance(feat, dict):\n",
541
+ " for key in ['desc', 'conf', 'pts3d']:\n",
542
+ " if key in feat:\n",
543
+ " feat = feat[key]\n",
544
+ " break\n",
545
+ "\n",
546
+ " if isinstance(feat, torch.Tensor):\n",
547
+ " feat = feat.cpu().numpy()\n",
548
+ "\n",
549
+ " if isinstance(feat, np.ndarray):\n",
550
+ " if feat.ndim == 3: # [H, W, C]\n",
551
+ " feat_flat = feat.reshape(-1, feat.shape[-1])\n",
552
+ " elif feat.ndim == 2: # [N, C]\n",
553
+ " feat_flat = feat\n",
554
+ " else:\n",
555
+ " feat_flat = feat.reshape(-1, max(feat.shape))\n",
556
+ "\n",
557
+ " global_desc = np.mean(feat_flat, axis=0)\n",
558
+ " global_features.append(global_desc)\n",
559
+ " else:\n",
560
+ " # ダミー特徴量\n",
561
+ " global_features.append(np.zeros(64))\n",
562
+ "\n",
563
+ " global_features = np.stack(global_features)\n",
564
+ " feature_dim = global_features.shape[1]\n",
565
+ "\n",
566
+ " print(f\"Global features shape: {global_features.shape}\")\n",
567
+ "\n",
568
+ " # コサイン類似度を使用\n",
569
+ " global_features_norm = global_features / (np.linalg.norm(global_features, axis=1, keepdims=True) + 1e-8)\n",
570
+ " similarity_matrix = global_features_norm @ global_features_norm.T\n",
571
+ "\n",
572
+ " np.fill_diagonal(similarity_matrix, -1)\n",
573
+ "\n",
574
+ " print(f\"Similarity matrix shape: {similarity_matrix.shape}\")\n",
575
+ " print(f\"Similarity range: [{similarity_matrix.min():.3f}, {similarity_matrix.max():.3f}]\")\n",
576
+ "\n",
577
+ " return similarity_matrix\n",
578
+ "\n",
579
+ "\n",
580
+ "def build_pairs_from_similarity(similarity_matrix, top_k=10):\n",
581
+ " \"\"\"類似度行列からペアを構築\"\"\"\n",
582
+ " n_images = similarity_matrix.shape[0]\n",
583
+ " pairs = []\n",
584
+ "\n",
585
+ " for i in range(n_images):\n",
586
+ " similarities = similarity_matrix[i]\n",
587
+ " top_indices = np.argsort(similarities)[::-1][:top_k]\n",
588
+ "\n",
589
+ " for j in top_indices:\n",
590
+ " if j > i:\n",
591
+ " pairs.append((i, j))\n",
592
+ "\n",
593
+ " pairs = list(set(pairs))\n",
594
+ " print(f\"✓ Built {len(pairs)} unique pairs\")\n",
595
+ "\n",
596
+ " return pairs\n",
597
+ "\n",
598
+ "\n",
599
+ "def get_image_pairs_asmk(image_paths, max_pairs=100):\n",
600
+ " \"\"\"ASMKを使用して画像ペアを取得\"\"\"\n",
601
+ " print(\"\\n=== Getting Image Pairs with ASMK ===\")\n",
602
+ "\n",
603
+ " device = Config.DEVICE\n",
604
+ " model = load_mast3r_model(device)\n",
605
+ " features = extract_mast3r_features(model, image_paths, device)\n",
606
+ " similarity_matrix = compute_asmk_similarity(features)\n",
607
+ " pairs = build_pairs_from_similarity(similarity_matrix, Config.RETRIEVAL_TOPK)\n",
608
+ "\n",
609
+ " # モデルを解放\n",
610
+ " del model\n",
611
+ " clear_memory()\n",
612
+ "\n",
613
+ " if len(pairs) > max_pairs:\n",
614
+ " pairs = pairs[:max_pairs]\n",
615
+ " print(f\"Limited to {max_pairs} pairs\")\n",
616
+ "\n",
617
+ " return pairs"
618
+ ],
619
+ "metadata": {
620
+ "trusted": true,
621
+ "id": "qo0mGj_5jLmG"
622
+ },
623
+ "outputs": [],
624
+ "execution_count": null
625
+ },
626
+ {
627
+ "cell_type": "code",
628
+ "source": [
629
+ "# =====================================================================\n",
630
+ "# CELL 14: MASt3R Reconstruction\n",
631
+ "# =====================================================================\n",
632
+ "def run_mast3r_pairs(model, image_paths, pairs, device, batch_size=1):\n",
633
+ " \"\"\"MASt3Rでペア画像を処理(メモリ最適化版)\"\"\"\n",
634
+ " print(\"\\n=== Running MASt3R Reconstruction ===\")\n",
635
+ " from dust3r.inference import inference\n",
636
+ " from dust3r.cloud_opt import global_aligner, GlobalAlignerMode\n",
637
+ " from dust3r.utils.image import load_images\n",
638
+ "\n",
639
+ " # ペアを制限\n",
640
+ " max_pairs_for_memory = 50\n",
641
+ " if len(pairs) > max_pairs_for_memory:\n",
642
+ " print(f\"⚠️ Limiting pairs from {len(pairs)} to {max_pairs_for_memory} for memory\")\n",
643
+ " pairs = pairs[:max_pairs_for_memory]\n",
644
+ "\n",
645
+ " # ペアから画像インデックスを取得\n",
646
+ " pair_indices = []\n",
647
+ " for i, j in pairs:\n",
648
+ " pair_indices.extend([i, j])\n",
649
+ " unique_indices = sorted(set(pair_indices))\n",
650
+ "\n",
651
+ " selected_paths = [image_paths[i] for i in unique_indices]\n",
652
+ " print(f\"Selected {len(selected_paths)} unique images from {len(pairs)} pairs\")\n",
653
+ "\n",
654
+ " # 画像をロード\n",
655
+ " images = load_images(selected_paths, size=Config.IMAGE_SIZE)\n",
656
+ " clear_memory()\n",
657
+ "\n",
658
+ " # インデックスマッピング\n",
659
+ " index_map = {old_idx: new_idx for new_idx, old_idx in enumerate(unique_indices)}\n",
660
+ "\n",
661
+ " # ペア画像リストを作成\n",
662
+ " image_pairs = []\n",
663
+ " for i, j in pairs:\n",
664
+ " new_i = index_map[i]\n",
665
+ " new_j = index_map[j]\n",
666
+ " image_pairs.append((images[new_i], images[new_j]))\n",
667
+ "\n",
668
+ " print(f\"Created {len(image_pairs)} image pairs\")\n",
669
+ " clear_memory()\n",
670
+ "\n",
671
+ " # 推論を実行\n",
672
+ " print(f\"Running inference on {len(image_pairs)} pairs...\")\n",
673
+ " with torch.no_grad():\n",
674
+ " output = inference(image_pairs, model, device, batch_size=batch_size)\n",
675
+ "\n",
676
+ " print(f\"✓ Processed {len(output)} predictions\")\n",
677
+ " clear_memory()\n",
678
+ "\n",
679
+ " # Global alignment\n",
680
+ " scene = global_aligner(\n",
681
+ " dust3r_output=output,\n",
682
+ " device=device,\n",
683
+ " mode=GlobalAlignerMode.PointCloudOptimizer,\n",
684
+ " verbose=True\n",
685
+ " )\n",
686
+ "\n",
687
+ " clear_memory()\n",
688
+ "\n",
689
+ " print(\"Running global alignment...\")\n",
690
+ " try:\n",
691
+ " loss = scene.compute_global_alignment(\n",
692
+ " init=\"mst\",\n",
693
+ " niter=50,\n",
694
+ " schedule='cosine',\n",
695
+ " lr=0.01\n",
696
+ " )\n",
697
+ " print(f\"✓ Alignment complete (loss: {loss:.6f})\")\n",
698
+ " except RuntimeError as e:\n",
699
+ " if \"out of memory\" in str(e).lower():\n",
700
+ " print(\"⚠️ OOM during alignment, trying with fewer iterations...\")\n",
701
+ " clear_memory()\n",
702
+ " loss = scene.compute_global_alignment(\n",
703
+ " init=\"mst\",\n",
704
+ " niter=20,\n",
705
+ " schedule='cosine',\n",
706
+ " lr=0.01\n",
707
+ " )\n",
708
+ " print(f\"✓ Alignment complete with reduced iterations (loss: {loss:.6f})\")\n",
709
+ " else:\n",
710
+ " raise\n",
711
+ "\n",
712
+ " clear_memory()\n",
713
+ " return scene, images\n",
714
+ "\n",
715
+ "# =====================================================================\n",
716
+ "# CELL 15: Camera Parameter Extraction\n",
717
+ "# =====================================================================\n",
718
+ "def extract_camera_params_process2(scene, image_paths, conf_threshold=1.5):\n",
719
+ " \"\"\"sceneからカメラパラメータと3D点を抽出\"\"\"\n",
720
+ " print(\"\\n=== Extracting Camera Parameters ===\")\n",
721
+ "\n",
722
+ " cameras_dict = {}\n",
723
+ " all_pts3d = []\n",
724
+ " all_confidence = []\n",
725
+ "\n",
726
+ " try:\n",
727
+ " if hasattr(scene, 'get_im_poses'):\n",
728
+ " poses = scene.get_im_poses()\n",
729
+ " elif hasattr(scene, 'im_poses'):\n",
730
+ " poses = scene.im_poses\n",
731
+ " else:\n",
732
+ " poses = None\n",
733
+ "\n",
734
+ " if hasattr(scene, 'get_focals'):\n",
735
+ " focals = scene.get_focals()\n",
736
+ " elif hasattr(scene, 'im_focals'):\n",
737
+ " focals = scene.im_focals\n",
738
+ " else:\n",
739
+ " focals = None\n",
740
+ "\n",
741
+ " if hasattr(scene, 'get_principal_points'):\n",
742
+ " pps = scene.get_principal_points()\n",
743
+ " elif hasattr(scene, 'im_pp'):\n",
744
+ " pps = scene.im_pp\n",
745
+ " else:\n",
746
+ " pps = None\n",
747
+ " except Exception as e:\n",
748
+ " print(f\"⚠️ Error getting camera parameters: {e}\")\n",
749
+ " poses = None\n",
750
+ " focals = None\n",
751
+ " pps = None\n",
752
+ "\n",
753
+ " n_images = min(len(poses) if poses is not None else len(image_paths), len(image_paths))\n",
754
+ "\n",
755
+ " for idx in range(n_images):\n",
756
+ " img_name = os.path.basename(image_paths[idx])\n",
757
+ "\n",
758
+ " try:\n",
759
+ " # Poseを取得\n",
760
+ " if poses is not None and idx < len(poses):\n",
761
+ " pose = poses[idx]\n",
762
+ " if isinstance(pose, torch.Tensor):\n",
763
+ " pose = pose.detach().cpu().numpy()\n",
764
+ " if not isinstance(pose, np.ndarray) or pose.shape != (4, 4):\n",
765
+ " pose = np.eye(4)\n",
766
+ " else:\n",
767
+ " pose = np.eye(4)\n",
768
+ "\n",
769
+ " # Focalを取得\n",
770
+ " if focals is not None and idx < len(focals):\n",
771
+ " focal = focals[idx]\n",
772
+ " if isinstance(focal, torch.Tensor):\n",
773
+ " focal = focal.detach().cpu().item()\n",
774
+ " else:\n",
775
+ " focal = float(focal)\n",
776
+ " else:\n",
777
+ " focal = 1000.0\n",
778
+ "\n",
779
+ " # Principal pointを取得\n",
780
+ " if pps is not None and idx < len(pps):\n",
781
+ " pp = pps[idx]\n",
782
+ " if isinstance(pp, torch.Tensor):\n",
783
+ " pp = pp.detach().cpu().numpy()\n",
784
+ " else:\n",
785
+ " pp = np.array([112.0, 112.0])\n",
786
+ "\n",
787
+ " # カメラパラメータを保存\n",
788
+ " cameras_dict[img_name] = {\n",
789
+ " 'focal': focal,\n",
790
+ " 'pp': pp,\n",
791
+ " 'pose': pose,\n",
792
+ " 'width': Config.IMAGE_SIZE * 4,\n",
793
+ " 'height': Config.IMAGE_SIZE * 4\n",
794
+ " }\n",
795
+ "\n",
796
+ " # 3D点を取得\n",
797
+ " if hasattr(scene, 'im_pts3d') and idx < len(scene.im_pts3d):\n",
798
+ " pts3d_img = scene.im_pts3d[idx]\n",
799
+ " elif hasattr(scene, 'get_pts3d'):\n",
800
+ " pts3d_all = scene.get_pts3d()\n",
801
+ " if idx < len(pts3d_all):\n",
802
+ " pts3d_img = pts3d_all[idx]\n",
803
+ " else:\n",
804
+ " pts3d_img = None\n",
805
+ " else:\n",
806
+ " pts3d_img = None\n",
807
+ "\n",
808
+ " # Confidenceを取得\n",
809
+ " if hasattr(scene, 'im_conf') and idx < len(scene.im_conf):\n",
810
+ " conf_img = scene.im_conf[idx]\n",
811
+ " elif hasattr(scene, 'get_conf'):\n",
812
+ " conf_all = scene.get_conf()\n",
813
+ " if idx < len(conf_all):\n",
814
+ " conf_img = conf_all[idx]\n",
815
+ " else:\n",
816
+ " conf_img = None\n",
817
+ " else:\n",
818
+ " conf_img = None\n",
819
+ "\n",
820
+ " # 3D点とconfidenceを処理\n",
821
+ " if pts3d_img is not None:\n",
822
+ " if isinstance(pts3d_img, torch.Tensor):\n",
823
+ " pts3d_img = pts3d_img.detach().cpu().numpy()\n",
824
+ "\n",
825
+ " if pts3d_img.ndim == 3:\n",
826
+ " pts3d_flat = pts3d_img.reshape(-1, 3)\n",
827
+ " else:\n",
828
+ " pts3d_flat = pts3d_img\n",
829
+ "\n",
830
+ " all_pts3d.append(pts3d_flat)\n",
831
+ "\n",
832
+ " # confidenceを処理\n",
833
+ " if conf_img is not None:\n",
834
+ " if isinstance(conf_img, list):\n",
835
+ " conf_img = np.array(conf_img)\n",
836
+ " elif isinstance(conf_img, torch.Tensor):\n",
837
+ " conf_img = conf_img.detach().cpu().numpy()\n",
838
+ "\n",
839
+ " if conf_img.ndim > 1:\n",
840
+ " conf_flat = conf_img.reshape(-1)\n",
841
+ " else:\n",
842
+ " conf_flat = conf_img\n",
843
+ "\n",
844
+ " if len(conf_flat) != len(pts3d_flat):\n",
845
+ " conf_flat = np.ones(len(pts3d_flat))\n",
846
+ "\n",
847
+ " all_confidence.append(conf_flat)\n",
848
+ " else:\n",
849
+ " all_confidence.append(np.ones(len(pts3d_flat)))\n",
850
+ "\n",
851
+ " except Exception as e:\n",
852
+ " print(f\"⚠️ Error processing image {idx} ({img_name}): {e}\")\n",
853
+ " cameras_dict[img_name] = {\n",
854
+ " 'focal': 1000.0,\n",
855
+ " 'pp': np.array([112.0, 112.0]),\n",
856
+ " 'pose': np.eye(4),\n",
857
+ " 'width': Config.IMAGE_SIZE * 4,\n",
858
+ " 'height': Config.IMAGE_SIZE * 4\n",
859
+ " }\n",
860
+ " continue\n",
861
+ "\n",
862
+ " # 全3D点を結合\n",
863
+ " if all_pts3d:\n",
864
+ " pts3d = np.vstack(all_pts3d)\n",
865
+ " confidence = np.concatenate(all_confidence)\n",
866
+ " else:\n",
867
+ " pts3d = np.zeros((0, 3))\n",
868
+ " confidence = np.zeros(0)\n",
869
+ "\n",
870
+ " print(f\"✓ Extracted camera parameters for {len(cameras_dict)} images\")\n",
871
+ " print(f\"✓ Total 3D points: {len(pts3d)}\")\n",
872
+ "\n",
873
+ " # Confidenceでフィルタリング\n",
874
+ " if len(confidence) > 0:\n",
875
+ " valid_mask = confidence > conf_threshold\n",
876
+ " pts3d = pts3d[valid_mask]\n",
877
+ " confidence = confidence[valid_mask]\n",
878
+ " print(f\"✓ After confidence filtering (>{conf_threshold}): {len(pts3d)} points\")\n",
879
+ "\n",
880
+ " return cameras_dict, pts3d, confidence"
881
+ ],
882
+ "metadata": {
883
+ "trusted": true,
884
+ "id": "bCXpdw83jLmG"
885
+ },
886
+ "outputs": [],
887
+ "execution_count": null
888
+ },
889
+ {
890
+ "cell_type": "code",
891
+ "source": [
892
+ "# =====================================================================\n",
893
+ "# CELL 16: COLMAP Export Functions\n",
894
+ "# =====================================================================\n",
895
+ "import struct\n",
896
+ "from scipy.spatial.transform import Rotation as R\n",
897
+ "\n",
898
+ "def write_colmap_sparse(cameras_dict, pts3d, confidence, image_paths, output_dir):\n",
899
+ " \"\"\"COLMAP sparse形式をバイナリファイルで出力\"\"\"\n",
900
+ " os.makedirs(output_dir, exist_ok=True)\n",
901
+ "\n",
902
+ " if not cameras_dict:\n",
903
+ " raise ValueError(\"cameras_dict is empty\")\n",
904
+ "\n",
905
+ " first_key = list(cameras_dict.keys())[0]\n",
906
+ " first_cam = cameras_dict[first_key]\n",
907
+ "\n",
908
+ " w = int(first_cam.get('width', 1920))\n",
909
+ " h = int(first_cam.get('height', 1080))\n",
910
+ " focal = float(first_cam.get('focal', max(w, h) * 1.2))\n",
911
+ " cx = w / 2.0\n",
912
+ " cy = h / 2.0\n",
913
+ "\n",
914
+ " # cameras.bin\n",
915
+ " cameras_file = os.path.join(output_dir, 'cameras.bin')\n",
916
+ " with open(cameras_file, 'wb') as f:\n",
917
+ " f.write(struct.pack('Q', 1))\n",
918
+ " camera_id = 1\n",
919
+ " model_id = 1 # PINHOLE\n",
920
+ " f.write(struct.pack('i', camera_id))\n",
921
+ " f.write(struct.pack('i', model_id))\n",
922
+ " f.write(struct.pack('Q', w))\n",
923
+ " f.write(struct.pack('Q', h))\n",
924
+ " f.write(struct.pack('d', focal))\n",
925
+ " f.write(struct.pack('d', focal))\n",
926
+ " f.write(struct.pack('d', cx))\n",
927
+ " f.write(struct.pack('d', cy))\n",
928
+ "\n",
929
+ " print(f\"✓ Written cameras.bin\")\n",
930
+ "\n",
931
+ " # images.bin\n",
932
+ " images_file = os.path.join(output_dir, 'images.bin')\n",
933
+ " with open(images_file, 'wb') as f:\n",
934
+ " f.write(struct.pack('Q', len(image_paths)))\n",
935
+ "\n",
936
+ " for i, img_path in enumerate(image_paths):\n",
937
+ " img_name = os.path.basename(img_path)\n",
938
+ "\n",
939
+ " cam_info = cameras_dict.get(img_name)\n",
940
+ " if cam_info is None:\n",
941
+ " pose = np.eye(4)\n",
942
+ " else:\n",
943
+ " pose = cam_info['pose']\n",
944
+ "\n",
945
+ " try:\n",
946
+ " w2c = np.linalg.inv(pose)\n",
947
+ " except np.linalg.LinAlgError:\n",
948
+ " w2c = np.eye(4)\n",
949
+ "\n",
950
+ " rot_mat = w2c[:3, :3]\n",
951
+ " tvec = w2c[:3, 3]\n",
952
+ " quat = R.from_matrix(rot_mat).as_quat()\n",
953
+ " qw, qx, qy, qz = quat[3], quat[0], quat[1], quat[2]\n",
954
+ "\n",
955
+ " image_id = i + 1\n",
956
+ " f.write(struct.pack('i', image_id))\n",
957
+ " f.write(struct.pack('d', qw))\n",
958
+ " f.write(struct.pack('d', qx))\n",
959
+ " f.write(struct.pack('d', qy))\n",
960
+ " f.write(struct.pack('d', qz))\n",
961
+ " f.write(struct.pack('d', tvec[0]))\n",
962
+ " f.write(struct.pack('d', tvec[1]))\n",
963
+ " f.write(struct.pack('d', tvec[2]))\n",
964
+ " f.write(struct.pack('i', 1))\n",
965
+ " img_name_bytes = img_name.encode('utf-8') + b'\\x00'\n",
966
+ " f.write(img_name_bytes)\n",
967
+ " f.write(struct.pack('Q', 0))\n",
968
+ "\n",
969
+ " print(f\"✓ Written images.bin ({len(image_paths)} images)\")\n",
970
+ "\n",
971
+ " # points3D.bin\n",
972
+ " points_file = os.path.join(output_dir, 'points3D.bin')\n",
973
+ " with open(points_file, 'wb') as f:\n",
974
+ " f.write(struct.pack('Q', len(pts3d)))\n",
975
+ "\n",
976
+ " for point_id, point in enumerate(pts3d, start=1):\n",
977
+ " f.write(struct.pack('Q', point_id))\n",
978
+ " f.write(struct.pack('d', point[0]))\n",
979
+ " f.write(struct.pack('d', point[1]))\n",
980
+ " f.write(struct.pack('d', point[2]))\n",
981
+ " f.write(struct.pack('B', 255))\n",
982
+ " f.write(struct.pack('B', 255))\n",
983
+ " f.write(struct.pack('B', 255))\n",
984
+ " f.write(struct.pack('d', 0.0))\n",
985
+ " f.write(struct.pack('Q', 0))\n",
986
+ "\n",
987
+ " print(f\"✓ Written points3D.bin ({len(pts3d)} points)\")\n",
988
+ "\n",
989
+ " # テキスト形式も出力\n",
990
+ " write_text_versions(cameras_dict, pts3d, image_paths, output_dir, w, h, focal, cx, cy)\n",
991
+ "\n",
992
+ " print(f\"\\n✓ COLMAP sparse reconstruction saved\")\n",
993
+ " return output_dir\n",
994
+ "\n",
995
+ "\n",
996
+ "def write_text_versions(cameras_dict, pts3d, image_paths, output_dir, w, h, focal, cx, cy):\n",
997
+ " \"\"\"テキスト形式を出力\"\"\"\n",
998
+ "\n",
999
+ " # cameras.txt\n",
1000
+ " with open(os.path.join(output_dir, 'cameras.txt'), 'w') as file:\n",
1001
+ " file.write(\"# Camera list with one line of data per camera:\\n\")\n",
1002
+ " file.write(\"# CAMERA_ID, MODEL, WIDTH, HEIGHT, PARAMS[]\\n\")\n",
1003
+ " file.write(f\"1 PINHOLE {w} {h} {focal} {focal} {cx} {cy}\\n\")\n",
1004
+ "\n",
1005
+ " # images.txt\n",
1006
+ " with open(os.path.join(output_dir, 'images.txt'), 'w') as file:\n",
1007
+ " file.write(\"# Image list with two lines of data per image:\\n\")\n",
1008
+ " file.write(\"# IMAGE_ID, QW, QX, QY, QZ, TX, TY, TZ, CAMERA_ID, NAME\\n\")\n",
1009
+ " file.write(\"# POINTS2D[] as (X, Y, POINT3D_ID)\\n\")\n",
1010
+ "\n",
1011
+ " for i, img_path in enumerate(image_paths):\n",
1012
+ " img_name = os.path.basename(img_path)\n",
1013
+ " cam_info = cameras_dict.get(img_name)\n",
1014
+ "\n",
1015
+ " if cam_info is None:\n",
1016
+ " pose = np.eye(4)\n",
1017
+ " else:\n",
1018
+ " pose = cam_info['pose']\n",
1019
+ "\n",
1020
+ " try:\n",
1021
+ " w2c = np.linalg.inv(pose)\n",
1022
+ " except np.linalg.LinAlgError:\n",
1023
+ " w2c = np.eye(4)\n",
1024
+ "\n",
1025
+ " rot_mat = w2c[:3, :3]\n",
1026
+ " tvec = w2c[:3, 3]\n",
1027
+ " quat = R.from_matrix(rot_mat).as_quat()\n",
1028
+ " qw, qx, qy, qz = quat[3], quat[0], quat[1], quat[2]\n",
1029
+ "\n",
1030
+ " image_id = i + 1\n",
1031
+ " file.write(f\"{image_id} {qw} {qx} {qy} {qz} {tvec[0]} {tvec[1]} {tvec[2]} 1 {img_name}\\n\")\n",
1032
+ " file.write(\"\\n\")\n",
1033
+ "\n",
1034
+ " # points3D.txt\n",
1035
+ " with open(os.path.join(output_dir, 'points3D.txt'), 'w') as file:\n",
1036
+ " file.write(\"# 3D point list with one line of data per point:\\n\")\n",
1037
+ " file.write(\"# POINT3D_ID, X, Y, Z, R, G, B, ERROR, TRACK[]\\n\")\n",
1038
+ "\n",
1039
+ " for point_id, point in enumerate(pts3d, start=1):\n",
1040
+ " file.write(f\"{point_id} {point[0]} {point[1]} {point[2]} 255 255 255 0.0\\n\")\n",
1041
+ "\n",
1042
+ "# =====================================================================\n",
1043
+ "# CELL 17: Gaussian Splatting Runner\n",
1044
+ "# =====================================================================\n",
1045
+ "def run_gaussian_splatting(source_dir, output_dir, iterations=30000):\n",
1046
+ " \"\"\"Gaussian Splattingを実行\"\"\"\n",
1047
+ " print(\"\\n=== Running Gaussian Splatting ===\")\n",
1048
+ "\n",
1049
+ " os.makedirs(output_dir, exist_ok=True)\n",
1050
+ "\n",
1051
+ " cmd = [\n",
1052
+ " \"python\", \"/content/gaussian-splatting/train.py\",\n",
1053
+ " \"-s\", source_dir,\n",
1054
+ " \"-m\", output_dir,\n",
1055
+ " \"--iterations\", str(iterations),\n",
1056
+ " \"--eval\"\n",
1057
+ " ]\n",
1058
+ "\n",
1059
+ " print(f\"Command: {' '.join(cmd)}\")\n",
1060
+ " print(f\" Source: {source_dir}\")\n",
1061
+ " print(f\" Output: {output_dir}\")\n",
1062
+ "\n",
1063
+ " result = subprocess.run(cmd, capture_output=False, text=True)\n",
1064
+ "\n",
1065
+ " if result.returncode == 0:\n",
1066
+ " print(f\"\\n✓ Gaussian Splatting complete\")\n",
1067
+ "\n",
1068
+ " point_cloud_dir = os.path.join(output_dir, \"point_cloud\")\n",
1069
+ " if os.path.exists(point_cloud_dir):\n",
1070
+ " print(f\"\\n✓ Point cloud directory found: {point_cloud_dir}\")\n",
1071
+ "\n",
1072
+ " for item in sorted(os.listdir(point_cloud_dir)):\n",
1073
+ " item_path = os.path.join(point_cloud_dir, item)\n",
1074
+ " if os.path.isdir(item_path) and item.startswith(\"iteration_\"):\n",
1075
+ " ply_file = os.path.join(item_path, \"point_cloud.ply\")\n",
1076
+ " if os.path.exists(ply_file):\n",
1077
+ " file_size = os.path.getsize(ply_file) / (1024 * 1024)\n",
1078
+ " print(f\" ✓ {item}/point_cloud.ply ({file_size:.2f} MB)\")\n",
1079
+ " else:\n",
1080
+ " print(f\"\\n✗ Gaussian Splatting failed with return code {result.returncode}\")\n",
1081
+ "\n",
1082
+ " return output_dir"
1083
+ ],
1084
+ "metadata": {
1085
+ "trusted": true,
1086
+ "id": "1yyRoxHKjLmH"
1087
+ },
1088
+ "outputs": [],
1089
+ "execution_count": null
1090
+ },
1091
+ {
1092
+ "cell_type": "code",
1093
+ "source": [
1094
+ "# =====================================================================\n",
1095
+ "# CELL 18: Main Pipeline\n",
1096
+ "# =====================================================================\n",
1097
+ "def main_pipeline(image_dir, output_dir, square_size=1024, iterations=30000,\n",
1098
+ " max_images=200, max_pairs=100, max_points=500000,\n",
1099
+ " conf_threshold=1.5, preprocess_mode='none'):\n",
1100
+ " \"\"\"メインパイプライン(修正版)\"\"\"\n",
1101
+ "\n",
1102
+ " # STEP 0: Image Preprocessing\n",
1103
+ " if preprocess_mode == 'biplet':\n",
1104
+ " print(\"=\"*70)\n",
1105
+ " print(\"STEP 0: Image Preprocessing (Biplet Crops)\")\n",
1106
+ " print(\"=\"*70)\n",
1107
+ "\n",
1108
+ " temp_biplet_dir = os.path.join(output_dir, \"temp_biplet\")\n",
1109
+ " biplet_dir = normalize_image_sizes_biplet(image_dir, temp_biplet_dir, size=square_size)\n",
1110
+ "\n",
1111
+ " images_dir = os.path.join(output_dir, \"images\")\n",
1112
+ " os.makedirs(images_dir, exist_ok=True)\n",
1113
+ "\n",
1114
+ " biplet_suffixes = ['_left', '_right', '_top', '_bottom']\n",
1115
+ " copied_count = 0\n",
1116
+ "\n",
1117
+ " for img_file in os.listdir(temp_biplet_dir):\n",
1118
+ " if any(suffix in img_file for suffix in biplet_suffixes):\n",
1119
+ " src = os.path.join(temp_biplet_dir, img_file)\n",
1120
+ " dst = os.path.join(images_dir, img_file)\n",
1121
+ " shutil.copy2(src, dst)\n",
1122
+ " copied_count += 1\n",
1123
+ "\n",
1124
+ " print(f\"✓ Copied {copied_count} biplet images to {images_dir}\")\n",
1125
+ "\n",
1126
+ " original_images_dir = os.path.join(output_dir, \"original_images\")\n",
1127
+ " os.makedirs(original_images_dir, exist_ok=True)\n",
1128
+ "\n",
1129
+ " original_count = 0\n",
1130
+ " valid_extensions = ('.jpg', '.jpeg', '.png', '.bmp')\n",
1131
+ " for img_file in os.listdir(image_dir):\n",
1132
+ " if img_file.lower().endswith(valid_extensions):\n",
1133
+ " src = os.path.join(image_dir, img_file)\n",
1134
+ " dst = os.path.join(original_images_dir, img_file)\n",
1135
+ " shutil.copy2(src, dst)\n",
1136
+ " original_count += 1\n",
1137
+ "\n",
1138
+ " print(f\"✓ Saved {original_count} original images to {original_images_dir}\")\n",
1139
+ " shutil.rmtree(temp_biplet_dir)\n",
1140
+ " image_dir = images_dir\n",
1141
+ " clear_memory()\n",
1142
+ " else:\n",
1143
+ " images_dir = os.path.join(output_dir, \"images\")\n",
1144
+ " if not os.path.exists(images_dir):\n",
1145
+ " print(\"=\"*70)\n",
1146
+ " print(\"STEP 0: Copying images to output directory\")\n",
1147
+ " print(\"=\"*70)\n",
1148
+ " shutil.copytree(image_dir, images_dir)\n",
1149
+ " print(f\"✓ Copied images to {images_dir}\")\n",
1150
+ " image_dir = images_dir\n",
1151
+ "\n",
1152
+ " # STEP 1: Loading Images\n",
1153
+ " print(\"\\n\" + \"=\"*70)\n",
1154
+ " print(\"STEP 1: Loading and Preparing Images\")\n",
1155
+ " print(\"=\"*70)\n",
1156
+ "\n",
1157
+ " image_paths = load_images_from_directory(image_dir, max_images=max_images)\n",
1158
+ " print(f\"Loaded {len(image_paths)} images\")\n",
1159
+ " clear_memory()\n",
1160
+ "\n",
1161
+ " # STEP 2: Image Pair Selection\n",
1162
+ " print(\"\\n\" + \"=\"*70)\n",
1163
+ " print(\"STEP 2: Image Pair Selection\")\n",
1164
+ " print(\"=\"*70)\n",
1165
+ "\n",
1166
+ " max_pairs = min(max_pairs, 50)\n",
1167
+ " pairs = get_image_pairs_asmk(image_paths, max_pairs=max_pairs)\n",
1168
+ " print(f\"Selected {len(pairs)} image pairs\")\n",
1169
+ " clear_memory()\n",
1170
+ "\n",
1171
+ " # STEP 3: MASt3R 3D Reconstruction\n",
1172
+ " print(\"\\n\" + \"=\"*70)\n",
1173
+ " print(\"STEP 3: MASt3R 3D Reconstruction\")\n",
1174
+ " print(\"=\"*70)\n",
1175
+ "\n",
1176
+ " device = Config.DEVICE\n",
1177
+ " model = load_mast3r_model(device)\n",
1178
+ " scene, mast3r_images = run_mast3r_pairs(model, image_paths, pairs, device)\n",
1179
+ "\n",
1180
+ " del model\n",
1181
+ " clear_memory()\n",
1182
+ "\n",
1183
+ " # STEP 4: Converting to COLMAP\n",
1184
+ " print(\"\\n\" + \"=\"*70)\n",
1185
+ " print(\"STEP 4: Converting to COLMAP (PINHOLE)\")\n",
1186
+ " print(\"=\"*70)\n",
1187
+ "\n",
1188
+ " cameras_dict, pts3d, confidence = extract_camera_params_process2(\n",
1189
+ " scene, image_paths, conf_threshold=conf_threshold\n",
1190
+ " )\n",
1191
+ "\n",
1192
+ " del scene\n",
1193
+ " clear_memory()\n",
1194
+ "\n",
1195
+ " if len(pts3d) > max_points:\n",
1196
+ " print(f\"⚠️ Limiting points from {len(pts3d)} to {max_points}\")\n",
1197
+ " indices = np.random.choice(len(pts3d), max_points, replace=False)\n",
1198
+ " pts3d = pts3d[indices]\n",
1199
+ " confidence = confidence[indices]\n",
1200
+ "\n",
1201
+ " print(f\"Final point count: {len(pts3d)}\")\n",
1202
+ "\n",
1203
+ " colmap_dir = os.path.join(output_dir, \"sparse/0\")\n",
1204
+ " os.makedirs(colmap_dir, exist_ok=True)\n",
1205
+ "\n",
1206
+ " write_colmap_sparse(cameras_dict, pts3d, confidence, image_paths, colmap_dir)\n",
1207
+ " clear_memory()\n",
1208
+ "\n",
1209
+ " # STEP 5: Running Gaussian Splatting\n",
1210
+ " print(\"\\n\" + \"=\"*70)\n",
1211
+ " print(\"STEP 5: Running Gaussian Splatting\")\n",
1212
+ " print(\"=\"*70)\n",
1213
+ "\n",
1214
+ " source_dir = output_dir\n",
1215
+ " model_output_dir = os.path.join(output_dir, \"gaussian_splatting\")\n",
1216
+ "\n",
1217
+ " gs_output = run_gaussian_splatting(\n",
1218
+ " source_dir=source_dir,\n",
1219
+ " output_dir=model_output_dir,\n",
1220
+ " iterations=iterations\n",
1221
+ " )\n",
1222
+ "\n",
1223
+ " # STEP 6: Verify Output\n",
1224
+ " print(\"\\n\" + \"=\"*70)\n",
1225
+ " print(\"PIPELINE COMPLETE\")\n",
1226
+ " print(\"=\"*70)\n",
1227
+ "\n",
1228
+ " ply_path = os.path.join(\n",
1229
+ " model_output_dir,\n",
1230
+ " \"point_cloud\",\n",
1231
+ " f\"iteration_{iterations}\",\n",
1232
+ " \"point_cloud.ply\"\n",
1233
+ " )\n",
1234
+ "\n",
1235
+ " if os.path.exists(ply_path):\n",
1236
+ " file_size = os.path.getsize(ply_path) / (1024 * 1024)\n",
1237
+ " print(f\"✓ Point cloud generated: {ply_path}\")\n",
1238
+ " print(f\" Size: {file_size:.2f} MB\")\n",
1239
+ " else:\n",
1240
+ " print(f\"⚠️ Point cloud not found at: {ply_path}\")\n",
1241
+ "\n",
1242
+ " print(f\"\\nOutput directory structure:\")\n",
1243
+ " print(f\" {output_dir}/\")\n",
1244
+ " print(f\" ├── images/ (processed images)\")\n",
1245
+ " if preprocess_mode == 'biplet':\n",
1246
+ " print(f\" ├── original_images/ (original source images)\")\n",
1247
+ " print(f\" ├── sparse/0/ (COLMAP data)\")\n",
1248
+ " print(f\" └── gaussian_splatting/ (GS output)\")\n",
1249
+ "\n",
1250
+ " return gs_output\n",
1251
+ "\n",
1252
+ "# =====================================================================\n",
1253
+ "# CELL 19: Verify Setup\n",
1254
+ "# =====================================================================\n",
1255
+ "print(f\"✓ np: {np.__version__} - {np.__file__}\")\n",
1256
+ "!pip show numpy | grep Version\n",
1257
+ "\n",
1258
+ "try:\n",
1259
+ " import roma\n",
1260
+ " print(\"✓ roma is installed\")\n",
1261
+ "except ModuleNotFoundError:\n",
1262
+ " print(\"⚠️ roma not found, installing...\")\n",
1263
+ " !pip install roma\n",
1264
+ " import roma\n",
1265
+ " print(\"✓ roma installed\")"
1266
+ ],
1267
+ "metadata": {
1268
+ "trusted": true,
1269
+ "id": "bHKT_3EZjLmH"
1270
+ },
1271
+ "outputs": [],
1272
+ "execution_count": null
1273
+ },
1274
+ {
1275
+ "cell_type": "code",
1276
+ "source": [
1277
+ "# =====================================================================\n",
1278
+ "# CELL 20: Run Pipeline\n",
1279
+ "# =====================================================================\n",
1280
+ "if __name__ == \"__main__\":\n",
1281
+ " IMAGE_DIR = \"/content/drive/MyDrive/your_folder/fountain\"\n",
1282
+ " OUTPUT_DIR = \"/content/output\"\n",
1283
+ "\n",
1284
+ " gs_output = main_pipeline(\n",
1285
+ " image_dir=IMAGE_DIR,\n",
1286
+ " output_dir=OUTPUT_DIR,\n",
1287
+ " square_size=800,\n",
1288
+ " iterations=1000,\n",
1289
+ " max_images=25,\n",
1290
+ " max_pairs=25,\n",
1291
+ " max_points=4000,\n",
1292
+ " conf_threshold=1.5,\n",
1293
+ " preprocess_mode='biplet'\n",
1294
+ " )\n",
1295
+ "\n",
1296
+ " print(\"\\n\" + \"=\"*70)\n",
1297
+ " print(\"PIPELINE COMPLETE\")\n",
1298
+ " print(\"=\"*70)\n",
1299
+ " print(f\"Output directory: {gs_output}\")"
1300
+ ],
1301
+ "metadata": {
1302
+ "trusted": true,
1303
+ "id": "n6ZHOb8TjLmI"
1304
+ },
1305
+ "outputs": [],
1306
+ "execution_count": null
1307
+ },
1308
+ {
1309
+ "cell_type": "code",
1310
+ "source": [],
1311
+ "metadata": {
1312
+ "trusted": true,
1313
+ "id": "Ontdbh48jLmI"
1314
+ },
1315
+ "outputs": [],
1316
+ "execution_count": null
1317
+ },
1318
+ {
1319
+ "cell_type": "markdown",
1320
+ "source": [
1321
+ "\n",
1322
+ "\n",
1323
+ "## 🔧 主要な修正:\n",
1324
+ "\n",
1325
+ "### 1. **特徴量抽出の修正 (CELL 12)**\n",
1326
+ "- RGB画像 `[H, W, 3]` が返される問題を修正\n",
1327
+ "- 特徴量次元が小さい場合は自動的に64次元に拡張\n",
1328
+ "- より堅牢なエラーハンドリング\n",
1329
+ "\n",
1330
+ "### 2. **ASMK類似度計算の修正 (CELL 13)**\n",
1331
+ "- Codebookの使用を削除し、シンプルなコサイン類似度に変更\n",
1332
+ "- 次元ミスマッチエラーを完全に解消\n",
1333
+ "- 動的な特徴量次元に対応\n",
1334
+ "\n",
1335
+ "### 3. **カメラパラメータの修正 (CELL 15)**\n",
1336
+ "- 画像サイズ情報を明示的に保存 (`width`, `height`)\n",
1337
+ "- より堅牢なエラーハンドリング\n",
1338
+ "\n",
1339
+ "### 4. **コード構造の改善**\n",
1340
+ "- 各セルを独立して実行可能に\n",
1341
+ "- メモリ管理の最適化\n",
1342
+ "- エラーメッセージの改善\n",
1343
+ "\n",
1344
+ "## 📋 使用方法:\n",
1345
+ "\n",
1346
+ "1. **セル1**: 依存関係をインストール\n",
1347
+ "2. **セル2**: カーネルを再起動(コメント)\n",
1348
+ "3. **セル3-19**: 順番に実行\n",
1349
+ "4. **セル20**: パイプラインを実行\n",
1350
+ "\n",
1351
+ "## ✨ 改善点:\n",
1352
+ "\n",
1353
+ "- ✅ ASMK失敗エラーを完全に解決\n",
1354
+ "- ✅ 特徴量次元の動的対応\n",
1355
+ "- ✅ メモリ効率の改善\n",
1356
+ "- ✅ より詳細なログ出力\n",
1357
+ "- ✅ エラー時の自動リカバリー\n",
1358
+ "\n"
1359
+ ],
1360
+ "metadata": {
1361
+ "id": "K-TGZRlcjLmI"
1362
+ }
1363
+ }
1364
+ ]
1365
+ }
biplet_asmk_mast3r_ps2_gs_kg_32_colab_02.ipynb ADDED
The diff for this file is too large to render. See raw diff