stpete2 commited on
Commit
b2f332b
·
verified ·
1 Parent(s): f617d4b

Upload Images_3D_Reconst_MASt3R_SfM_colab0407.ipynb

Browse files
Images_3D_Reconst_MASt3R_SfM_colab0407.ipynb ADDED
@@ -0,0 +1,2163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "kernelspec": {
4
+ "display_name": "Python 3",
5
+ "name": "python3"
6
+ },
7
+ "language_info": {
8
+ "codemirror_mode": {
9
+ "name": "ipython",
10
+ "version": 3
11
+ },
12
+ "file_extension": ".py",
13
+ "mimetype": "text/x-python",
14
+ "name": "python",
15
+ "nbconvert_exporter": "python",
16
+ "pygments_lexer": "ipython3",
17
+ "version": "3.12.12"
18
+ },
19
+ "kaggle": {
20
+ "accelerator": "none",
21
+ "dataSources": [
22
+ {
23
+ "sourceType": "datasetVersion",
24
+ "sourceId": 15538872,
25
+ "datasetId": 1429416,
26
+ "databundleVersionId": 16467233
27
+ }
28
+ ],
29
+ "dockerImageVersionId": 31260,
30
+ "isInternetEnabled": true,
31
+ "language": "python",
32
+ "sourceType": "notebook",
33
+ "isGpuEnabled": false
34
+ },
35
+ "papermill": {
36
+ "default_parameters": {},
37
+ "duration": 297.567631,
38
+ "end_time": "2026-03-26T13:00:56.861265",
39
+ "environment_variables": {},
40
+ "exception": true,
41
+ "input_path": "__notebook__.ipynb",
42
+ "output_path": "__notebook__.ipynb",
43
+ "parameters": {},
44
+ "start_time": "2026-03-26T12:55:59.293634",
45
+ "version": "2.6.0"
46
+ },
47
+ "colab": {
48
+ "provenance": [],
49
+ "machine_shape": "hm",
50
+ "gpuType": "L4"
51
+ },
52
+ "accelerator": "GPU"
53
+ },
54
+ "nbformat_minor": 0,
55
+ "nbformat": 4,
56
+ "cells": [
57
+ {
58
+ "source": [
59
+ "from google.colab import drive\n",
60
+ "drive.mount('/content/drive')\n"
61
+ ],
62
+ "metadata": {
63
+ "id": "G8HLekEKMlOW",
64
+ "colab": {
65
+ "base_uri": "https://localhost:8080/"
66
+ },
67
+ "outputId": "f301cbf6-4389-4b71-937c-3a331a92183b"
68
+ },
69
+ "cell_type": "code",
70
+ "outputs": [
71
+ {
72
+ "output_type": "stream",
73
+ "name": "stdout",
74
+ "text": [
75
+ "Mounted at /content/drive\n"
76
+ ]
77
+ }
78
+ ],
79
+ "execution_count": 1
80
+ },
81
+ {
82
+ "cell_type": "markdown",
83
+ "source": [
84
+ "# **3D Reconstruction with MASt3R-SfM**"
85
+ ],
86
+ "metadata": {
87
+ "papermill": {
88
+ "duration": 0.001826,
89
+ "end_time": "2026-03-26T12:56:02.330517",
90
+ "exception": false,
91
+ "start_time": "2026-03-26T12:56:02.328691",
92
+ "status": "completed"
93
+ },
94
+ "tags": [],
95
+ "id": "IFhi2v_hMlOZ"
96
+ }
97
+ },
98
+ {
99
+ "cell_type": "markdown",
100
+ "source": [
101
+ "### **w/biplet**"
102
+ ],
103
+ "metadata": {
104
+ "id": "bzVezppvTTVe"
105
+ }
106
+ },
107
+ {
108
+ "cell_type": "code",
109
+ "source": [
110
+ "!pip uninstall numpy -y\n",
111
+ "!pip install \"numpy==1.26.4\" \"scipy>=1.12\" --quiet\n",
112
+ "break"
113
+ ],
114
+ "metadata": {
115
+ "trusted": true,
116
+ "id": "rxX5nRu4MlOa",
117
+ "colab": {
118
+ "base_uri": "https://localhost:8080/",
119
+ "height": 431
120
+ },
121
+ "outputId": "a6b3ce41-2165-41df-f3c7-1955616d3b25"
122
+ },
123
+ "outputs": [
124
+ {
125
+ "output_type": "stream",
126
+ "name": "stdout",
127
+ "text": [
128
+ "Found existing installation: numpy 2.0.2\n",
129
+ "Uninstalling numpy-2.0.2:\n",
130
+ " Successfully uninstalled numpy-2.0.2\n",
131
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m61.0/61.0 kB\u001b[0m \u001b[31m6.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
132
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m18.0/18.0 MB\u001b[0m \u001b[31m123.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
133
+ "\u001b[?25h\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",
134
+ "shap 0.51.0 requires numpy>=2, but you have numpy 1.26.4 which is incompatible.\n",
135
+ "opencv-python 4.13.0.92 requires numpy>=2; python_version >= \"3.9\", but you have numpy 1.26.4 which is incompatible.\n",
136
+ "rasterio 1.5.0 requires numpy>=2, but you have numpy 1.26.4 which is incompatible.\n",
137
+ "jax 0.7.2 requires numpy>=2.0, but you have numpy 1.26.4 which is incompatible.\n",
138
+ "pytensor 2.38.2 requires numpy>=2.0, but you have numpy 1.26.4 which is incompatible.\n",
139
+ "cupy-cuda12x 14.0.1 requires numpy<2.6,>=2.0, but you have numpy 1.26.4 which is incompatible.\n",
140
+ "opencv-python-headless 4.13.0.92 requires numpy>=2; python_version >= \"3.9\", but you have numpy 1.26.4 which is incompatible.\n",
141
+ "xarray-einstats 0.10.0 requires numpy>=2.0, but you have numpy 1.26.4 which is incompatible.\n",
142
+ "opencv-contrib-python 4.13.0.92 requires numpy>=2; python_version >= \"3.9\", but you have numpy 1.26.4 which is incompatible.\n",
143
+ "tobler 0.13.0 requires numpy>=2.0, but you have numpy 1.26.4 which is incompatible.\n",
144
+ "jaxlib 0.7.2 requires numpy>=2.0, but you have numpy 1.26.4 which is incompatible.\u001b[0m\u001b[31m\n",
145
+ "\u001b[0m"
146
+ ]
147
+ },
148
+ {
149
+ "output_type": "error",
150
+ "ename": "SyntaxError",
151
+ "evalue": "'break' outside loop (1398352102.py, line 3)",
152
+ "traceback": [
153
+ "\u001b[0;36m File \u001b[0;32m\"/tmp/ipykernel_10964/1398352102.py\"\u001b[0;36m, line \u001b[0;32m3\u001b[0m\n\u001b[0;31m break\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m 'break' outside loop\n"
154
+ ]
155
+ }
156
+ ],
157
+ "execution_count": 2
158
+ },
159
+ {
160
+ "cell_type": "markdown",
161
+ "source": [
162
+ "---"
163
+ ],
164
+ "metadata": {
165
+ "id": "rE9GmNNcMlOb"
166
+ }
167
+ },
168
+ {
169
+ "cell_type": "code",
170
+ "source": [
171
+ "# restart, run after"
172
+ ],
173
+ "metadata": {
174
+ "trusted": true,
175
+ "execution": {
176
+ "iopub.status.busy": "2026-04-06T17:49:20.119493Z",
177
+ "iopub.execute_input": "2026-04-06T17:49:20.119783Z",
178
+ "iopub.status.idle": "2026-04-06T17:49:20.124291Z",
179
+ "shell.execute_reply.started": "2026-04-06T17:49:20.119757Z",
180
+ "shell.execute_reply": "2026-04-06T17:49:20.123517Z"
181
+ },
182
+ "id": "LjWh_q2jMlOb"
183
+ },
184
+ "outputs": [],
185
+ "execution_count": 1
186
+ },
187
+ {
188
+ "cell_type": "code",
189
+ "source": [],
190
+ "metadata": {
191
+ "id": "vSrsSqRpUGWz"
192
+ },
193
+ "execution_count": 1,
194
+ "outputs": []
195
+ },
196
+ {
197
+ "cell_type": "code",
198
+ "source": [
199
+ "!pip show numpy | grep Version:"
200
+ ],
201
+ "metadata": {
202
+ "trusted": true,
203
+ "execution": {
204
+ "iopub.status.busy": "2026-04-06T17:49:20.125646Z",
205
+ "iopub.execute_input": "2026-04-06T17:49:20.126379Z",
206
+ "iopub.status.idle": "2026-04-06T17:49:22.32856Z",
207
+ "shell.execute_reply.started": "2026-04-06T17:49:20.126347Z",
208
+ "shell.execute_reply": "2026-04-06T17:49:22.327891Z"
209
+ },
210
+ "id": "YlKV_7vgMlOb",
211
+ "colab": {
212
+ "base_uri": "https://localhost:8080/"
213
+ },
214
+ "outputId": "ac624797-b3e6-4bec-bc61-ec4faedaf3c4"
215
+ },
216
+ "outputs": [
217
+ {
218
+ "output_type": "stream",
219
+ "name": "stdout",
220
+ "text": [
221
+ "Version: 1.26.4\n"
222
+ ]
223
+ }
224
+ ],
225
+ "execution_count": 2
226
+ },
227
+ {
228
+ "cell_type": "code",
229
+ "source": [
230
+ "!pip install gputil\n",
231
+ "import psutil\n",
232
+ "import time\n",
233
+ "import threading\n",
234
+ "import os\n",
235
+ "import numpy as np\n",
236
+ "\n",
237
+ "class MultiResourceLogger:\n",
238
+ " def __init__(self, interval=60.0, time_limit=None):\n",
239
+ " self.interval = interval\n",
240
+ " self.time_limit = time_limit\n",
241
+ " self.stop_flag = False\n",
242
+ " self.start_time = time.time()\n",
243
+ "\n",
244
+ " self.thread = threading.Thread(target=self._log_loop, daemon=True)\n",
245
+ "\n",
246
+ " if self.time_limit is not None:\n",
247
+ " self.timeout_thread = threading.Thread(\n",
248
+ " target=self._timeout_loop, daemon=True\n",
249
+ " )\n",
250
+ "\n",
251
+ " def _get_gpu_usage(self):\n",
252
+ " try:\n",
253
+ " import GPUtil\n",
254
+ " gpus = GPUtil.getGPUs()\n",
255
+ " stats = []\n",
256
+ " for i, gpu in enumerate(gpus):\n",
257
+ " stats.append(\n",
258
+ " (i, gpu.load * 100, gpu.memoryUtil * 100)\n",
259
+ " )\n",
260
+ " return stats\n",
261
+ " except:\n",
262
+ " return []\n",
263
+ "\n",
264
+ " def _timeout_loop(self):\n",
265
+ " while True:\n",
266
+ " elapsed = time.time() - self.start_time\n",
267
+ " if elapsed > self.time_limit:\n",
268
+ " print(\"\\n⏰ TIME LIMIT REACHED\")\n",
269
+ " print(\"💣 Force stopping entire notebook...\")\n",
270
+ " os._exit(0)\n",
271
+ " time.sleep(1)\n",
272
+ "\n",
273
+ " def _format_time(self, t):\n",
274
+ " if t is None:\n",
275
+ " return \"∞\"\n",
276
+ " m = int(t // 60)\n",
277
+ " s = int(t % 60)\n",
278
+ " return f\"{m:02d}:{s:02d}\"\n",
279
+ "\n",
280
+ " def _log_loop(self):\n",
281
+ " psutil.cpu_percent(None)\n",
282
+ "\n",
283
+ " while not self.stop_flag:\n",
284
+ " elapsed = time.time() - self.start_time\n",
285
+ " remain = None\n",
286
+ " if self.time_limit is not None:\n",
287
+ " remain = self.time_limit - elapsed\n",
288
+ "\n",
289
+ " cpu = psutil.cpu_percent(None)\n",
290
+ " mem = psutil.virtual_memory().percent\n",
291
+ " gpu_stats = self._get_gpu_usage()\n",
292
+ "\n",
293
+ " msg = (\n",
294
+ " f\"⏱️ elapsed={self._format_time(elapsed)} \"\n",
295
+ " f\"⏳ remain={self._format_time(remain)} | \"\n",
296
+ " f\"🔥 CPU={cpu:5.1f}% \"\n",
297
+ " f\"💾 RAM={mem:5.1f}%\"\n",
298
+ " )\n",
299
+ "\n",
300
+ " for idx, gpu, vram in gpu_stats:\n",
301
+ " msg += f\" | 🧠 GPU{idx}={gpu:5.1f}% 🎮 VRAM{idx}={vram:5.1f}%\"\n",
302
+ "\n",
303
+ " print(msg)\n",
304
+ "\n",
305
+ " time.sleep(self.interval)\n",
306
+ "\n",
307
+ " def start(self):\n",
308
+ " self.thread.start()\n",
309
+ " if self.time_limit is not None:\n",
310
+ " self.timeout_thread.start()\n",
311
+ "\n",
312
+ " def stop(self):\n",
313
+ " self.stop_flag = True\n",
314
+ "\n",
315
+ "\n",
316
+ "\n",
317
+ "logger = MultiResourceLogger(\n",
318
+ " interval=60*3,\n",
319
+ " time_limit=60*240\n",
320
+ ")\n",
321
+ "\n",
322
+ "logger.start()\n",
323
+ "#logger.stop()"
324
+ ],
325
+ "metadata": {
326
+ "trusted": true,
327
+ "execution": {
328
+ "iopub.status.busy": "2026-04-06T17:49:22.329626Z",
329
+ "iopub.execute_input": "2026-04-06T17:49:22.329849Z",
330
+ "iopub.status.idle": "2026-04-06T17:49:27.764878Z",
331
+ "shell.execute_reply.started": "2026-04-06T17:49:22.329824Z",
332
+ "shell.execute_reply": "2026-04-06T17:49:27.763955Z"
333
+ },
334
+ "id": "YtsBCdK_MlOb",
335
+ "colab": {
336
+ "base_uri": "https://localhost:8080/"
337
+ },
338
+ "outputId": "6b41e6cd-0a61-4bdc-c603-95a59db853df"
339
+ },
340
+ "outputs": [
341
+ {
342
+ "output_type": "stream",
343
+ "name": "stdout",
344
+ "text": [
345
+ "Collecting gputil\n",
346
+ " Downloading GPUtil-1.4.0.tar.gz (5.5 kB)\n",
347
+ " Preparing metadata (setup.py) ... \u001b[?25l\u001b[?25hdone\n",
348
+ "Building wheels for collected packages: gputil\n",
349
+ " Building wheel for gputil (setup.py) ... \u001b[?25l\u001b[?25hdone\n",
350
+ " Created wheel for gputil: filename=GPUtil-1.4.0-py3-none-any.whl size=7392 sha256=a560d51f35cfce46b8a8fdb123279f19b1c8320bca4c1ccf0126954103913000\n",
351
+ " Stored in directory: /root/.cache/pip/wheels/92/a8/b7/d8a067c31a74de9ca252bbe53dea5f896faabd25d55f541037\n",
352
+ "Successfully built gputil\n",
353
+ "Installing collected packages: gputil\n",
354
+ "Successfully installed gputil-1.4.0\n"
355
+ ]
356
+ }
357
+ ],
358
+ "execution_count": 3
359
+ },
360
+ {
361
+ "cell_type": "code",
362
+ "source": [
363
+ "# =============================================================================\n",
364
+ "# 3D Reconstruction with MASt3R-SfM (sparse_global_alignment)\n",
365
+ "# Based on: https://github.com/naver/mast3r\n",
366
+ "# Replaces DUSt3R global_aligner with MASt3R-SfM sparse_global_alignment\n",
367
+ "# =============================================================================\n",
368
+ "\n",
369
+ "import os\n",
370
+ "import sys\n",
371
+ "import gc\n",
372
+ "import numpy as np\n",
373
+ "import torch\n",
374
+ "import torch.nn.functional as F\n",
375
+ "from pathlib import Path\n",
376
+ "import subprocess\n",
377
+ "from PIL import Image\n",
378
+ "import struct\n",
379
+ "import base64\n",
380
+ "\n",
381
+ "\n",
382
+ "# ============================================================================\n",
383
+ "# Config\n",
384
+ "# ============================================================================\n",
385
+ "\n",
386
+ "class Config:\n",
387
+ " MAST3R_MODEL = \"/content/mast3r/checkpoints/MASt3R_ViTLarge_BaseDecoder_512_catmlpdpt_metric.pth\"\n",
388
+ " RETRIEVAL_MODEL = (\n",
389
+ " \"/content/mast3r/checkpoints/\"\n",
390
+ " \"MASt3R_ViTLarge_BaseDecoder_512_catmlpdpt_metric_retrieval_trainingfree.pth\"\n",
391
+ " )\n",
392
+ "\n",
393
+ " MAST3R_IMAGE_SIZE = 512 #512 # 512 recommended for SfM (prioritize accuracy)\n",
394
+ " SCENE_GRAPH = 'retrieval-10-15' #'retrieval-10-15' # 'retrieval' | 'swin-5' | 'complete'\n",
395
+ " LR1 = 0.07 # Coarse LR\n",
396
+ " NITER1 = 300 # Coarse iterations ###\n",
397
+ " LR2 = 0.01 # Fine LR\n",
398
+ " NITER2 = 300 # Fine iterations ###\n",
399
+ " OPT_DEPTH = True # Also optimize depth maps\n",
400
+ " SHARED_INTRINSICS = False # Different intrinsic parameters per camera\n",
401
+ "\n",
402
+ " MIN_CONF_THR = 1.5 # Confidence threshold for 3D points ###\n",
403
+ "\n",
404
+ " SQUARE_SIZE = 1024 # Size after Biplet normalization\n",
405
+ "\n",
406
+ " DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
407
+ "\n",
408
+ "\n",
409
+ "# ============================================================================\n",
410
+ "# Memory Utilities\n",
411
+ "# ============================================================================\n",
412
+ "\n",
413
+ "def clear_memory():\n",
414
+ " gc.collect()\n",
415
+ " if torch.cuda.is_available():\n",
416
+ " torch.cuda.empty_cache()\n",
417
+ " torch.cuda.synchronize()\n",
418
+ "\n",
419
+ "\n",
420
+ "def get_memory_info():\n",
421
+ " if torch.cuda.is_available():\n",
422
+ " alloc = torch.cuda.memory_allocated() / 1024**3\n",
423
+ " reserv = torch.cuda.memory_reserved() / 1024**3\n",
424
+ " print(f\" GPU - Allocated: {alloc:.2f} GB, Reserved: {reserv:.2f} GB\")\n",
425
+ " import psutil\n",
426
+ " cpu = psutil.virtual_memory().percent\n",
427
+ " print(f\" CPU - Usage: {cpu:.1f}%\")\n",
428
+ "\n",
429
+ "\n",
430
+ "# ============================================================================\n",
431
+ "# Environment Setup\n",
432
+ "# ============================================================================\n",
433
+ "\n",
434
+ "def run_cmd(cmd, check=True):\n",
435
+ " print(f\" $ {' '.join(cmd)}\")\n",
436
+ " r = subprocess.run(cmd, text=True, check=False)\n",
437
+ " if check and r.returncode != 0:\n",
438
+ " print(f\" [WARN] exit code {r.returncode}\")\n",
439
+ " return r\n",
440
+ "\n",
441
+ "\n",
442
+ "def setup_base_environment():\n",
443
+ " print(\"\\n\" + \"=\"*60)\n",
444
+ " print(\"Step 0-A: Base Environment Setup\")\n",
445
+ " print(\"=\"*60)\n",
446
+ "\n",
447
+ " run_cmd([sys.executable, \"-m\", \"pip\", \"uninstall\", \"-y\", \"numpy\"])\n",
448
+ " run_cmd([sys.executable, \"-m\", \"pip\", \"install\", \"numpy==1.26.4\"])\n",
449
+ " run_cmd([sys.executable, \"-m\", \"pip\", \"install\",\n",
450
+ " \"torch\", \"torchvision\", \"torchaudio\"])\n",
451
+ " run_cmd([sys.executable, \"-m\", \"pip\", \"install\",\n",
452
+ " \"opencv-python\", \"pillow\", \"imageio\", \"imageio-ffmpeg\",\n",
453
+ " \"plyfile\", \"tqdm\", \"scipy\", \"psutil\", \"roma\", \"trimesh\", \"matplotlib\"])\n",
454
+ " run_cmd([sys.executable, \"-m\", \"pip\", \"install\", \"transformers==4.40.0\"])\n",
455
+ " run_cmd([sys.executable, \"-m\", \"pip\", \"install\", \"pycolmap\"])\n",
456
+ " print(\"✓ Base environment ready\")\n",
457
+ "\n",
458
+ "\n",
459
+ "def setup_mast3r():\n",
460
+ " print(\"\\n\" + \"=\"*60)\n",
461
+ " print(\"Step 0-B: MASt3R Setup\")\n",
462
+ " print(\"=\"*60)\n",
463
+ "\n",
464
+ " os.chdir('/content')\n",
465
+ " if os.path.exists('mast3r'):\n",
466
+ " os.system('rm -rf mast3r')\n",
467
+ "\n",
468
+ " os.system('git clone --recursive https://github.com/naver/mast3r')\n",
469
+ " os.chdir('/content/mast3r')\n",
470
+ " os.system('pip install -e dust3r/')\n",
471
+ " os.system('pip install -r requirements.txt')\n",
472
+ "\n",
473
+ " os.makedirs('checkpoints', exist_ok=True)\n",
474
+ "\n",
475
+ " # MASt3R Main Checkpoint\n",
476
+ " os.system(\n",
477
+ " 'wget -nc -P checkpoints/ '\n",
478
+ " 'https://download.europe.naverlabs.com/ComputerVision/MASt3R/'\n",
479
+ " 'MASt3R_ViTLarge_BaseDecoder_512_catmlpdpt_metric.pth'\n",
480
+ " )\n",
481
+ "\n",
482
+ " # Retrieval Checkpoint (for MASt3R-SfM)\n",
483
+ " os.system(\n",
484
+ " 'wget -nc -P checkpoints/ '\n",
485
+ " 'https://download.europe.naverlabs.com/ComputerVision/MASt3R/'\n",
486
+ " 'MASt3R_ViTLarge_BaseDecoder_512_catmlpdpt_metric_retrieval_trainingfree.pth'\n",
487
+ " )\n",
488
+ " os.system(\n",
489
+ " 'wget -nc -P checkpoints/ '\n",
490
+ " 'https://download.europe.naverlabs.com/ComputerVision/MASt3R/'\n",
491
+ " 'MASt3R_ViTLarge_BaseDecoder_512_catmlpdpt_metric_retrieval_codebook.pkl'\n",
492
+ " )\n",
493
+ "\n",
494
+ " sys.path.insert(0, '/content/mast3r')\n",
495
+ " sys.path.insert(0, '/content/mast3r/dust3r')\n",
496
+ "\n",
497
+ " try:\n",
498
+ " from mast3r.model import AsymmetricMASt3R\n",
499
+ " print(\" ✓ MASt3R import OK\")\n",
500
+ " except Exception as e:\n",
501
+ " print(f\" ✗ MASt3R import failed: {e}\")\n",
502
+ " raise\n",
503
+ " print(\"✓ MASt3R ready\")\n",
504
+ "\n",
505
+ "\n",
506
+ "def setup_asmk():\n",
507
+ " \"\"\"\n",
508
+ " ASMK: Required for MASt3R-SfM retrieval pair selection.\n",
509
+ " Can be skipped if using scene_graph='swin-*'.\n",
510
+ " \"\"\"\n",
511
+ " print(\"\\n\" + \"=\"*60)\n",
512
+ " print(\"Step 0-C: ASMK Setup (for retrieval pair selection)\")\n",
513
+ " print(\"=\"*60)\n",
514
+ "\n",
515
+ " os.chdir('/content')\n",
516
+ " run_cmd([sys.executable, \"-m\", \"pip\", \"install\", \"cython\"])\n",
517
+ "\n",
518
+ " if not os.path.exists('asmk'):\n",
519
+ " os.system('git clone https://github.com/jenicek/asmk')\n",
520
+ "\n",
521
+ " os.chdir('/content/asmk/cython')\n",
522
+ " r = os.system('cythonize *.pyx')\n",
523
+ " if r != 0:\n",
524
+ " print(\" [WARN] cythonize failed — switching to swin graph\")\n",
525
+ " os.chdir('/content')\n",
526
+ " return False\n",
527
+ "\n",
528
+ " os.chdir('/content/asmk')\n",
529
+ " os.system('pip install .')\n",
530
+ " os.chdir('/content')\n",
531
+ "\n",
532
+ " try:\n",
533
+ " import asmk\n",
534
+ " print(\" ✓ ASMK import OK\")\n",
535
+ " return True\n",
536
+ " except Exception as e:\n",
537
+ " print(f\" [WARN] ASMK not importable: {e}\")\n",
538
+ " return False"
539
+ ],
540
+ "metadata": {
541
+ "execution": {
542
+ "iopub.status.busy": "2026-04-06T17:49:27.76611Z",
543
+ "iopub.execute_input": "2026-04-06T17:49:27.766315Z",
544
+ "iopub.status.idle": "2026-04-06T17:49:32.016967Z",
545
+ "shell.execute_reply.started": "2026-04-06T17:49:27.766292Z",
546
+ "shell.execute_reply": "2026-04-06T17:49:32.01614Z"
547
+ },
548
+ "papermill": {
549
+ "duration": 4.734022,
550
+ "end_time": "2026-03-26T12:56:07.070258",
551
+ "exception": false,
552
+ "start_time": "2026-03-26T12:56:02.336236",
553
+ "status": "completed"
554
+ },
555
+ "tags": [],
556
+ "trusted": true,
557
+ "id": "3iBUlgpsMlOc",
558
+ "colab": {
559
+ "base_uri": "https://localhost:8080/"
560
+ },
561
+ "outputId": "721a1d15-9dd7-489e-b41c-48811ac2ef20"
562
+ },
563
+ "outputs": [
564
+ {
565
+ "output_type": "stream",
566
+ "name": "stdout",
567
+ "text": [
568
+ "⏱️ elapsed=00:00 ⏳ remain=239:59 | 🔥 CPU= 0.0% 💾 RAM= 3.3% | 🧠 GPU0= 0.0% 🎮 VRAM0= 0.0%\n"
569
+ ]
570
+ }
571
+ ],
572
+ "execution_count": 4
573
+ },
574
+ {
575
+ "cell_type": "code",
576
+ "source": [
577
+ "!pip show numpy | grep Version:"
578
+ ],
579
+ "metadata": {
580
+ "trusted": true,
581
+ "execution": {
582
+ "iopub.status.busy": "2026-04-06T17:49:32.018877Z",
583
+ "iopub.execute_input": "2026-04-06T17:49:32.019295Z",
584
+ "iopub.status.idle": "2026-04-06T17:49:34.084649Z",
585
+ "shell.execute_reply.started": "2026-04-06T17:49:32.01927Z",
586
+ "shell.execute_reply": "2026-04-06T17:49:34.083987Z"
587
+ },
588
+ "id": "BIOZt3qJMlOc",
589
+ "colab": {
590
+ "base_uri": "https://localhost:8080/"
591
+ },
592
+ "outputId": "19b7bed7-1c60-49a5-d208-381427d63a45"
593
+ },
594
+ "outputs": [
595
+ {
596
+ "output_type": "stream",
597
+ "name": "stdout",
598
+ "text": [
599
+ "Version: 1.26.4\n"
600
+ ]
601
+ }
602
+ ],
603
+ "execution_count": 5
604
+ },
605
+ {
606
+ "cell_type": "code",
607
+ "source": [
608
+ "# ============================================================================\n",
609
+ "# Step 1: Biplet-Square Normalization\n",
610
+ "# ============================================================================\n",
611
+ "\n",
612
+ "def generate_two_crops(img, size):\n",
613
+ " if isinstance(size, (tuple, list)):\n",
614
+ " size = size[0]\n",
615
+ " width, height = img.size\n",
616
+ " crops = {}\n",
617
+ " if width >= height:\n",
618
+ " crops['left'] = img.crop((0, 0, height, height)).resize((size, size), Image.LANCZOS)\n",
619
+ " crops['right'] = img.crop((width-height,0, width, height)).resize((size, size), Image.LANCZOS)\n",
620
+ " else:\n",
621
+ " crops['top'] = img.crop((0, 0, width, width )).resize((size, size), Image.LANCZOS)\n",
622
+ " crops['bottom'] = img.crop((0, height-width, width, height )).resize((size, size), Image.LANCZOS)\n",
623
+ " return crops\n",
624
+ "\n",
625
+ "\n",
626
+ "def normalize_image_sizes_biplet(input_dir, output_dir, size=512):\n",
627
+ " print(\"\\n\" + \"=\"*60)\n",
628
+ " print(\"Step 1: Biplet-Square Normalization\")\n",
629
+ " print(\"=\"*60)\n",
630
+ " os.makedirs(output_dir, exist_ok=True)\n",
631
+ " count = 0\n",
632
+ " for fname in sorted(os.listdir(input_dir)):\n",
633
+ " if not fname.lower().endswith(('.jpg', '.jpeg', '.png')):\n",
634
+ " continue\n",
635
+ " img = Image.open(os.path.join(input_dir, fname))\n",
636
+ " crops = generate_two_crops(img, size)\n",
637
+ " base, ext = os.path.splitext(fname)\n",
638
+ " for mode, crop in crops.items():\n",
639
+ " crop.save(os.path.join(output_dir, f\"{base}_{mode}{ext}\"), quality=95)\n",
640
+ " print(f\" ✓ {fname}: {img.size} → 2 crops\")\n",
641
+ " count += 1\n",
642
+ " print(f\" Total: {count} images → {count*2} crops\")\n",
643
+ " return count"
644
+ ],
645
+ "metadata": {
646
+ "execution": {
647
+ "iopub.status.busy": "2026-04-06T17:49:34.085756Z",
648
+ "iopub.execute_input": "2026-04-06T17:49:34.086081Z",
649
+ "iopub.status.idle": "2026-04-06T17:49:34.100391Z",
650
+ "shell.execute_reply.started": "2026-04-06T17:49:34.086046Z",
651
+ "shell.execute_reply": "2026-04-06T17:49:34.099586Z"
652
+ },
653
+ "papermill": {
654
+ "duration": 0.013469,
655
+ "end_time": "2026-03-26T12:56:07.085932",
656
+ "exception": false,
657
+ "start_time": "2026-03-26T12:56:07.072463",
658
+ "status": "completed"
659
+ },
660
+ "tags": [],
661
+ "trusted": true,
662
+ "id": "B0rFsg0vMlOc"
663
+ },
664
+ "outputs": [],
665
+ "execution_count": 6
666
+ },
667
+ {
668
+ "cell_type": "code",
669
+ "source": [
670
+ "# ============================================================================\n",
671
+ "# Step 2: MASt3R-SfM (sparse_global_alignment)\n",
672
+ "# ============================================================================\n",
673
+ "\n",
674
+ "def load_mast3r_model():\n",
675
+ " from mast3r.model import AsymmetricMASt3R\n",
676
+ " model = AsymmetricMASt3R.from_pretrained(Config.MAST3R_MODEL).to(Config.DEVICE)\n",
677
+ " model.eval()\n",
678
+ " print(f\" ✓ MASt3R loaded on {Config.DEVICE}\")\n",
679
+ " return model"
680
+ ],
681
+ "metadata": {
682
+ "execution": {
683
+ "iopub.status.busy": "2026-04-06T17:49:34.101477Z",
684
+ "iopub.execute_input": "2026-04-06T17:49:34.101998Z",
685
+ "iopub.status.idle": "2026-04-06T17:49:34.28427Z",
686
+ "shell.execute_reply.started": "2026-04-06T17:49:34.101969Z",
687
+ "shell.execute_reply": "2026-04-06T17:49:34.2832Z"
688
+ },
689
+ "papermill": {
690
+ "duration": 0.039919,
691
+ "end_time": "2026-03-26T12:56:07.127924",
692
+ "exception": false,
693
+ "start_time": "2026-03-26T12:56:07.088005",
694
+ "status": "completed"
695
+ },
696
+ "tags": [],
697
+ "trusted": true,
698
+ "id": "uL0rE-HeMlOd"
699
+ },
700
+ "outputs": [],
701
+ "execution_count": 7
702
+ },
703
+ {
704
+ "cell_type": "code",
705
+ "source": [
706
+ "def run_mast3r_sfm(model, image_paths, cache_dir, asmk_available=True):\n",
707
+ " \"\"\"\n",
708
+ " MASt3R-SfM Core Pipeline:\n",
709
+ " make_pairs → sparse_global_alignment\n",
710
+ " Completely replaces the old method (inference + global_aligner).\n",
711
+ " \"\"\"\n",
712
+ " print(\"\\n\" + \"=\"*60)\n",
713
+ " print(\"Step 2: MASt3R-SfM (sparse_global_alignment)\")\n",
714
+ " print(\"=\"*60)\n",
715
+ " from mast3r.cloud_opt.sparse_ga import sparse_global_alignment\n",
716
+ " from mast3r.image_pairs import make_pairs\n",
717
+ " from dust3r.utils.image import load_images\n",
718
+ "\n",
719
+ " os.makedirs(cache_dir, exist_ok=True)\n",
720
+ "\n",
721
+ " # -- 2-A: Load Images --\n",
722
+ " print(f\" Loading {len(image_paths)} images at size={Config.MAST3R_IMAGE_SIZE}…\")\n",
723
+ " imgs = load_images(image_paths, size=Config.MAST3R_IMAGE_SIZE, verbose=False)\n",
724
+ " print(f\" Loaded {len(imgs)} images\")\n",
725
+ "\n",
726
+ " # -- 2-B: Pair Selection --\n",
727
+ " # 'retrieval-Na-k' : ASMK retrieval (requires sim_mat)\n",
728
+ " # 'logwin-5' : Log window — good for unordered images ← default fallback\n",
729
+ " # 'swin-5' : Sliding window — good for sequential images\n",
730
+ " # 'complete' : All pairs (small scenes only)\n",
731
+ " scene_graph = Config.SCENE_GRAPH\n",
732
+ "\n",
733
+ " # retrieval mode requires ASMK + sim_mat; fall back if unavailable\n",
734
+ " if scene_graph.startswith('retrieval') and not asmk_available:\n",
735
+ " print(f\" [WARN] ASMK not available → falling back to scene_graph='logwin-5'\")\n",
736
+ " scene_graph = 'logwin-5'\n",
737
+ "\n",
738
+ " print(f\" scene_graph = '{scene_graph}'\")\n",
739
+ "\n",
740
+ " # -- 2-C: Build sim_mat for retrieval mode --\n",
741
+ " sim_mat = None\n",
742
+ " if scene_graph.startswith('retrieval'):\n",
743
+ " try:\n",
744
+ " from mast3r.retrieval.processor import Retriever\n",
745
+ " retriever = Retriever(model, device=Config.DEVICE)\n",
746
+ " sim_mat = retriever.get_similarity_matrix(imgs)\n",
747
+ " print(f\" ✓ sim_mat built: shape={sim_mat.shape}\")\n",
748
+ " except Exception as e:\n",
749
+ " print(f\" [WARN] sim_mat construction failed ({e}) → falling back to 'logwin-5'\")\n",
750
+ " scene_graph = 'logwin-5'\n",
751
+ " sim_mat = None\n",
752
+ "\n",
753
+ " # -- 2-D: Make Pairs --\n",
754
+ " pairs = make_pairs(\n",
755
+ " imgs,\n",
756
+ " scene_graph=scene_graph,\n",
757
+ " prefilter=None,\n",
758
+ " symmetrize=True,\n",
759
+ " sim_mat=sim_mat, # None is safe for non-retrieval graphs\n",
760
+ " )\n",
761
+ " print(f\" ✓ make_pairs: {len(pairs)} pairs selected\")\n",
762
+ "\n",
763
+ " # -- 2-E: sparse_global_alignment --\n",
764
+ " print(\" Running sparse_global_alignment…\")\n",
765
+ " print(\" Memory before alignment:\")\n",
766
+ " get_memory_info()\n",
767
+ "\n",
768
+ " scene = sparse_global_alignment(\n",
769
+ " image_paths,\n",
770
+ " pairs,\n",
771
+ " cache_dir,\n",
772
+ " model,\n",
773
+ " lr1=Config.LR1,\n",
774
+ " niter1=Config.NITER1,\n",
775
+ " lr2=Config.LR2,\n",
776
+ " niter2=Config.NITER2,\n",
777
+ " device=Config.DEVICE,\n",
778
+ " opt_depth=Config.OPT_DEPTH,\n",
779
+ " shared_intrinsics=Config.SHARED_INTRINSICS,\n",
780
+ " matching_conf_thr=3.0,\n",
781
+ " )\n",
782
+ "\n",
783
+ " print(\" ✓ sparse_global_alignment done\")\n",
784
+ " print(\" Memory after alignment:\")\n",
785
+ " get_memory_info()\n",
786
+ " return scene"
787
+ ],
788
+ "metadata": {
789
+ "trusted": true,
790
+ "execution": {
791
+ "iopub.status.busy": "2026-04-06T17:49:34.285711Z",
792
+ "iopub.execute_input": "2026-04-06T17:49:34.286086Z",
793
+ "iopub.status.idle": "2026-04-06T17:49:34.363298Z",
794
+ "shell.execute_reply.started": "2026-04-06T17:49:34.286048Z",
795
+ "shell.execute_reply": "2026-04-06T17:49:34.362738Z"
796
+ },
797
+ "id": "REV-5F9JMlOd"
798
+ },
799
+ "outputs": [],
800
+ "execution_count": 8
801
+ },
802
+ {
803
+ "cell_type": "code",
804
+ "source": [
805
+ "# ============================================================================\n",
806
+ "# Step 3: COLMAP Conversion Utility\n",
807
+ "# ============================================================================\n",
808
+ "\n",
809
+ "def write_next_bytes(fid, data, fmt):\n",
810
+ " if isinstance(data, (list, tuple, np.ndarray)):\n",
811
+ " fid.write(struct.pack(\"<\" + fmt, *data))\n",
812
+ " else:\n",
813
+ " fid.write(struct.pack(\"<\" + fmt, data))\n",
814
+ "\n",
815
+ "\n",
816
+ "def matrix_to_qvec_tvec(matrix):\n",
817
+ " from scipy.spatial.transform import Rotation\n",
818
+ " R = matrix[:3, :3]\n",
819
+ " t = matrix[:3, 3]\n",
820
+ " q = Rotation.from_matrix(R).as_quat() # [x,y,z,w]\n",
821
+ " qvec = np.array([q[3], q[0], q[1], q[2]])\n",
822
+ " return qvec, t\n",
823
+ "\n",
824
+ "\n",
825
+ "def write_cameras_binary(cameras, path):\n",
826
+ " with open(path, \"wb\") as f:\n",
827
+ " write_next_bytes(f, len(cameras), \"Q\")\n",
828
+ " for cam_id, cam in cameras.items():\n",
829
+ " write_next_bytes(f, cam_id, \"I\")\n",
830
+ " write_next_bytes(f, 1, \"I\") # PINHOLE\n",
831
+ " write_next_bytes(f, cam['width'], \"Q\")\n",
832
+ " write_next_bytes(f, cam['height'], \"Q\")\n",
833
+ " for p in cam['params']:\n",
834
+ " write_next_bytes(f, float(p), \"d\")\n",
835
+ "\n",
836
+ "\n",
837
+ "def write_images_binary(images, path):\n",
838
+ " with open(path, \"wb\") as f:\n",
839
+ " write_next_bytes(f, len(images), \"Q\")\n",
840
+ " for img_id, img in images.items():\n",
841
+ " write_next_bytes(f, img_id, \"I\")\n",
842
+ " write_next_bytes(f, img['qvec'], \"dddd\")\n",
843
+ " write_next_bytes(f, img['tvec'], \"ddd\")\n",
844
+ " write_next_bytes(f, img['camera_id'],\"I\")\n",
845
+ " for ch in img['name']:\n",
846
+ " write_next_bytes(f, ch.encode(\"utf-8\"), \"c\")\n",
847
+ " write_next_bytes(f, b\"\\x00\", \"c\")\n",
848
+ " write_next_bytes(f, 0, \"Q\") # no 2D points\n",
849
+ "\n",
850
+ "\n",
851
+ "def write_points3d_binary(points3D, path):\n",
852
+ " with open(path, \"wb\") as f:\n",
853
+ " write_next_bytes(f, len(points3D), \"Q\")\n",
854
+ " for pid, pt in enumerate(points3D):\n",
855
+ " write_next_bytes(f, pid, \"Q\")\n",
856
+ " write_next_bytes(f, pt['xyz'], \"ddd\")\n",
857
+ " write_next_bytes(f, pt['rgb'], \"BBB\")\n",
858
+ " write_next_bytes(f, pt['error'], \"d\")\n",
859
+ " write_next_bytes(f, 0, \"Q\") # empty track"
860
+ ],
861
+ "metadata": {
862
+ "execution": {
863
+ "iopub.status.busy": "2026-04-06T17:49:34.36426Z",
864
+ "iopub.execute_input": "2026-04-06T17:49:34.364569Z",
865
+ "iopub.status.idle": "2026-04-06T17:49:34.379605Z",
866
+ "shell.execute_reply.started": "2026-04-06T17:49:34.364548Z",
867
+ "shell.execute_reply": "2026-04-06T17:49:34.378966Z"
868
+ },
869
+ "papermill": {
870
+ "duration": 0.039919,
871
+ "end_time": "2026-03-26T12:56:07.127924",
872
+ "exception": false,
873
+ "start_time": "2026-03-26T12:56:07.088005",
874
+ "status": "completed"
875
+ },
876
+ "tags": [],
877
+ "trusted": true,
878
+ "id": "35gWY1vIMlOd"
879
+ },
880
+ "outputs": [],
881
+ "execution_count": 9
882
+ },
883
+ {
884
+ "cell_type": "code",
885
+ "source": [
886
+ "# ============================================================================\n",
887
+ "# Step 3: Extract scene → COLMAP ----------- fix 2026/03/28 20:00\n",
888
+ "# ============================================================================\n",
889
+ "\n",
890
+ "def extract_scene_data(scene, verbose=True):\n",
891
+ " cameras = {}\n",
892
+ " images_data = {}\n",
893
+ " points3D = []\n",
894
+ "\n",
895
+ " if verbose:\n",
896
+ " print(\"\\n Extracting scene data…\")\n",
897
+ "\n",
898
+ " num_views = scene.n_imgs\n",
899
+ " if verbose:\n",
900
+ " print(f\" Views: {num_views}\")\n",
901
+ "\n",
902
+ " # ---- Camera + Pose ----\n",
903
+ " focals = scene.get_focals().detach().cpu().numpy()\n",
904
+ " pps = scene.get_principal_points().detach().cpu().numpy()\n",
905
+ " poses = scene.get_im_poses().detach().cpu().numpy()\n",
906
+ "\n",
907
+ " for idx in range(num_views):\n",
908
+ " img = scene.imgs[idx]\n",
909
+ " h, w = img.shape[:2]\n",
910
+ " fx = fy = float(focals[idx])\n",
911
+ " cx, cy = float(pps[idx][0]), float(pps[idx][1])\n",
912
+ " cameras[idx] = {\n",
913
+ " 'model': 'PINHOLE', 'width': w, 'height': h,\n",
914
+ " 'params': [fx, fy, cx, cy],\n",
915
+ " }\n",
916
+ " p = poses[idx]\n",
917
+ " qvec, tvec = (matrix_to_qvec_tvec(np.linalg.inv(p))\n",
918
+ " if abs(np.linalg.det(p)) > 1e-10\n",
919
+ " else (np.array([1., 0., 0., 0.]), np.zeros(3)))\n",
920
+ " images_data[idx + 1] = {\n",
921
+ " 'qvec': qvec, 'tvec': tvec,\n",
922
+ " 'camera_id': idx,\n",
923
+ " 'name': f'image_{idx:04d}.jpg',\n",
924
+ " 'xys': np.array([]), 'point3D_ids': np.array([]),\n",
925
+ " }\n",
926
+ "\n",
927
+ " # ---- 3D Point Cloud ----\n",
928
+ " def to_numpy(x):\n",
929
+ " if hasattr(x, 'detach'):\n",
930
+ " return x.detach().cpu().numpy()\n",
931
+ " elif isinstance(x, list):\n",
932
+ " if x and hasattr(x[0], 'detach'):\n",
933
+ " return torch.stack(x).detach().cpu().numpy()\n",
934
+ " return np.array(x)\n",
935
+ " return np.asarray(x)\n",
936
+ "\n",
937
+ " def unwrap_pts(raw, V):\n",
938
+ " \"\"\"→ (V, N, 3) の numpy配列に正規化\"\"\"\n",
939
+ " if isinstance(raw, (list, tuple)):\n",
940
+ " if len(raw) == V:\n",
941
+ " # per-view リスト\n",
942
+ " return np.stack([to_numpy(r).reshape(-1, 3) for r in raw])\n",
943
+ " else:\n",
944
+ " arr = to_numpy(raw[0])\n",
945
+ " else:\n",
946
+ " arr = to_numpy(raw)\n",
947
+ " if arr.ndim == 4: # (V, H, W, 3)\n",
948
+ " arr = arr.reshape(V, -1, 3)\n",
949
+ " elif arr.ndim == 3 and arr.shape[-1] == 3:\n",
950
+ " if arr.shape[0] != V: # (N, ?, 3) → reshape\n",
951
+ " arr = arr.reshape(V, -1, 3)\n",
952
+ " return arr # (V, N, 3)\n",
953
+ "\n",
954
+ " def unwrap_masks(raw, V, N):\n",
955
+ " \"\"\"→ (V, N) の bool numpy配列に正規化\"\"\"\n",
956
+ " # per-view リスト\n",
957
+ " if isinstance(raw, (list, tuple)) and len(raw) == V:\n",
958
+ " try:\n",
959
+ " arrs = [to_numpy(m).reshape(-1).astype(bool) for m in raw]\n",
960
+ " if all(len(a) == N for a in arrs):\n",
961
+ " return np.stack(arrs)\n",
962
+ " except Exception:\n",
963
+ " pass\n",
964
+ "\n",
965
+ " # 1要素リスト (stacked)\n",
966
+ " if isinstance(raw, (list, tuple)) and len(raw) == 1:\n",
967
+ " try:\n",
968
+ " arr = to_numpy(raw[0]).astype(bool).reshape(V, -1)\n",
969
+ " if arr.shape[1] == N:\n",
970
+ " return arr\n",
971
+ " except Exception:\n",
972
+ " pass\n",
973
+ "\n",
974
+ " # Tensor直接\n",
975
+ " if hasattr(raw, 'detach'):\n",
976
+ " try:\n",
977
+ " arr = raw.detach().cpu().numpy().astype(bool)\n",
978
+ " if arr.shape == (V, N):\n",
979
+ " return arr\n",
980
+ " return arr.reshape(V, N)\n",
981
+ " except Exception:\n",
982
+ " pass\n",
983
+ "\n",
984
+ " # object配列 (shape=()) → .item() で中身を取り出す\n",
985
+ " arr = np.asarray(raw)\n",
986
+ " if arr.dtype == object:\n",
987
+ " try:\n",
988
+ " inner = arr.item() # Python list や tuple が出てくる想定\n",
989
+ " return unwrap_masks(inner, V, N)\n",
990
+ " except Exception:\n",
991
+ " pass\n",
992
+ "\n",
993
+ " if verbose:\n",
994
+ " print(f\" [WARN] Could not parse masks, using all-True\")\n",
995
+ " return np.ones((V, N), dtype=bool)\n",
996
+ "\n",
997
+ " if verbose:\n",
998
+ " print(\" Extracting 3D points…\")\n",
999
+ "\n",
1000
+ " try:\n",
1001
+ " pts3d_raw = scene.get_dense_pts3d(clean_depth=False)\n",
1002
+ " masks_raw = scene.get_masks()\n",
1003
+ "\n",
1004
+ " pts_vn3 = unwrap_pts(pts3d_raw, num_views) # (V, N, 3)\n",
1005
+ " N = pts_vn3.shape[1]\n",
1006
+ " masks_vn = unwrap_masks(masks_raw, num_views, N) # (V, N)\n",
1007
+ "\n",
1008
+ " if verbose:\n",
1009
+ " print(f\" [DEBUG] pts_vn3 shape={pts_vn3.shape}\")\n",
1010
+ " print(f\" [DEBUG] masks_vn shape={masks_vn.shape}\")\n",
1011
+ "\n",
1012
+ " all_pts, all_cols = [], []\n",
1013
+ "\n",
1014
+ " for idx in range(num_views):\n",
1015
+ " pts_flat = pts_vn3[idx] # (N, 3)\n",
1016
+ " mask_flat = masks_vn[idx] # (N,) bool\n",
1017
+ "\n",
1018
+ " valid_pts = pts_flat[mask_flat]\n",
1019
+ " if len(valid_pts) == 0:\n",
1020
+ " continue\n",
1021
+ "\n",
1022
+ " # 色\n",
1023
+ " img = to_numpy(scene.imgs[idx])\n",
1024
+ " if img.ndim == 3 and img.shape[0] in (1, 3, 4):\n",
1025
+ " img = np.transpose(img, (1, 2, 0))\n",
1026
+ " img_flat = img.reshape(-1, 3)\n",
1027
+ "\n",
1028
+ " if len(img_flat) == N:\n",
1029
+ " valid_col = img_flat[mask_flat]\n",
1030
+ " else:\n",
1031
+ " # サイズ不一致の場合は有効点数分を切り出す\n",
1032
+ " valid_col = img_flat[:len(valid_pts)]\n",
1033
+ "\n",
1034
+ " if valid_col.size == 0:\n",
1035
+ " valid_col = np.zeros((len(valid_pts), 3), dtype=np.uint8)\n",
1036
+ " elif valid_col.max() <= 1.0:\n",
1037
+ " valid_col = (valid_col * 255).clip(0, 255).astype(np.uint8)\n",
1038
+ " else:\n",
1039
+ " valid_col = valid_col.clip(0, 255).astype(np.uint8)\n",
1040
+ "\n",
1041
+ " all_pts.append(valid_pts)\n",
1042
+ " all_cols.append(valid_col)\n",
1043
+ "\n",
1044
+ " if all_pts:\n",
1045
+ " pts_all = np.vstack(all_pts)\n",
1046
+ " cols_all = np.vstack(all_cols)\n",
1047
+ "\n",
1048
+ " valid = np.all(np.isfinite(pts_all), axis=1)\n",
1049
+ " pts_all, cols_all = pts_all[valid], cols_all[valid]\n",
1050
+ "\n",
1051
+ " MAX_PTS = 5_000_000\n",
1052
+ " if len(pts_all) > MAX_PTS:\n",
1053
+ " idx_s = np.random.choice(len(pts_all), MAX_PTS, replace=False)\n",
1054
+ " pts_all, cols_all = pts_all[idx_s], cols_all[idx_s]\n",
1055
+ "\n",
1056
+ " points3D = [\n",
1057
+ " {'xyz': pt, 'rgb': col, 'error': 0.0,\n",
1058
+ " 'image_ids': np.array([]), 'point2D_idxs': np.array([])}\n",
1059
+ " for pt, col in zip(pts_all, cols_all)\n",
1060
+ " ]\n",
1061
+ " if verbose:\n",
1062
+ " print(f\" ✓ Points: {len(points3D):,}\")\n",
1063
+ " else:\n",
1064
+ " if verbose:\n",
1065
+ " print(\" [WARN] all_pts is empty — no valid masked points\")\n",
1066
+ "\n",
1067
+ " except Exception as e:\n",
1068
+ " import traceback\n",
1069
+ " if verbose:\n",
1070
+ " print(f\" [ERROR] 3D point extraction failed: {e}\")\n",
1071
+ " traceback.print_exc()\n",
1072
+ "\n",
1073
+ " if verbose:\n",
1074
+ " print(f\" Summary: {len(cameras)} cams, {len(images_data)} imgs, {len(points3D):,} pts\")\n",
1075
+ "\n",
1076
+ " return cameras, images_data, points3D"
1077
+ ],
1078
+ "metadata": {
1079
+ "trusted": true,
1080
+ "execution": {
1081
+ "iopub.status.busy": "2026-04-06T17:49:34.380564Z",
1082
+ "iopub.execute_input": "2026-04-06T17:49:34.380787Z",
1083
+ "iopub.status.idle": "2026-04-06T17:49:34.403327Z",
1084
+ "shell.execute_reply.started": "2026-04-06T17:49:34.380768Z",
1085
+ "shell.execute_reply": "2026-04-06T17:49:34.402685Z"
1086
+ },
1087
+ "id": "jvuZQ7HiMlOd"
1088
+ },
1089
+ "outputs": [],
1090
+ "execution_count": 10
1091
+ },
1092
+ {
1093
+ "cell_type": "code",
1094
+ "source": [],
1095
+ "metadata": {
1096
+ "trusted": true,
1097
+ "id": "sUcx-aMAMlOd"
1098
+ },
1099
+ "outputs": [],
1100
+ "execution_count": 10
1101
+ },
1102
+ {
1103
+ "cell_type": "code",
1104
+ "source": [
1105
+ "def save_images(scene, images_dir, processed_image_paths=None):\n",
1106
+ " images_dir = Path(images_dir)\n",
1107
+ " images_dir.mkdir(parents=True, exist_ok=True)\n",
1108
+ " num_views = len(scene.imgs) if hasattr(scene, 'imgs') else len(scene.views)\n",
1109
+ " imgs_src = scene.imgs if hasattr(scene, 'imgs') else scene.views\n",
1110
+ "\n",
1111
+ " import shutil\n",
1112
+ " if processed_image_paths:\n",
1113
+ " for idx, src in enumerate(processed_image_paths[:num_views]):\n",
1114
+ " shutil.copy2(src, images_dir / f'image_{idx:04d}.jpg')\n",
1115
+ " else:\n",
1116
+ " for idx in range(num_views):\n",
1117
+ " img = imgs_src[idx]\n",
1118
+ " if isinstance(img, torch.Tensor):\n",
1119
+ " img = img.detach().cpu().numpy()\n",
1120
+ " if img.ndim == 3 and img.shape[0] in (1, 3, 4):\n",
1121
+ " img = np.transpose(img, (1, 2, 0))\n",
1122
+ " if img.max() <= 1.0:\n",
1123
+ " img = (img * 255).astype(np.uint8)\n",
1124
+ " if img.ndim == 2:\n",
1125
+ " img = np.stack([img]*3, axis=-1)\n",
1126
+ " Image.fromarray(img).save(images_dir / f'image_{idx:04d}.jpg')\n",
1127
+ "\n",
1128
+ "\n",
1129
+ "def save_depth_maps(scene, depth_dir):\n",
1130
+ " depth_dir = Path(depth_dir)\n",
1131
+ " depth_dir.mkdir(parents=True, exist_ok=True)\n",
1132
+ " try:\n",
1133
+ " depthmaps = scene.get_depthmaps()\n",
1134
+ " if depthmaps is None:\n",
1135
+ " return\n",
1136
+ " for idx, d in enumerate(depthmaps):\n",
1137
+ " if isinstance(d, torch.Tensor):\n",
1138
+ " d = d.detach().cpu().numpy()\n",
1139
+ " np.save(depth_dir / f'depth_{idx:04d}.npy', d)\n",
1140
+ " print(f\" Saved {len(depthmaps)} depth maps → {depth_dir}\")\n",
1141
+ " except Exception as e:\n",
1142
+ " print(f\" [WARN] depth maps: {e}\")\n",
1143
+ "\n",
1144
+ "\n",
1145
+ "def convert_scene_to_colmap(scene, output_dir, processed_image_paths=None, verbose=True):\n",
1146
+ " output_dir = Path(output_dir)\n",
1147
+ " sparse_dir = output_dir / \"sparse\" / \"0\"\n",
1148
+ " images_dir = output_dir / \"images\"\n",
1149
+ " depth_dir = output_dir / \"depth\"\n",
1150
+ " sparse_dir.mkdir(parents=True, exist_ok=True)\n",
1151
+ "\n",
1152
+ " if verbose:\n",
1153
+ " print(\"\\n\" + \"=\"*60)\n",
1154
+ " print(\"Step 3: Converting to COLMAP format\")\n",
1155
+ " print(\"=\"*60)\n",
1156
+ " print(f\" Output: {output_dir}\")\n",
1157
+ "\n",
1158
+ " cameras, images_data, points3D = extract_scene_data(scene, verbose=verbose)\n",
1159
+ "\n",
1160
+ " save_images(scene, images_dir, processed_image_paths)\n",
1161
+ " save_depth_maps(scene, depth_dir)\n",
1162
+ "\n",
1163
+ " write_cameras_binary(cameras, sparse_dir / \"cameras.bin\")\n",
1164
+ " write_images_binary(images_data, sparse_dir / \"images.bin\")\n",
1165
+ " write_points3d_binary(points3D, sparse_dir / \"points3D.bin\")\n",
1166
+ "\n",
1167
+ " if verbose:\n",
1168
+ " print(f\" ✓ cameras.bin ({len(cameras)} cameras)\")\n",
1169
+ " print(f\" ✓ images.bin ({len(images_data)} images)\")\n",
1170
+ " print(f\" ✓ points3D.bin ({len(points3D)} points)\")\n",
1171
+ " print(\"✓ COLMAP conversion complete\")\n",
1172
+ "\n",
1173
+ " return output_dir\n",
1174
+ "\n",
1175
+ "\n",
1176
+ "# ============================================================================\n",
1177
+ "# Step 4: PLY Conversion\n",
1178
+ "# ============================================================================\n",
1179
+ "\n",
1180
+ "def convert_colmap_to_ply(sparse_dir, ply_path):\n",
1181
+ " import pycolmap\n",
1182
+ " from plyfile import PlyData, PlyElement\n",
1183
+ "\n",
1184
+ " print(\"\\n\" + \"=\"*60)\n",
1185
+ " print(\"Step 4: COLMAP bin → PLY\")\n",
1186
+ " print(\"=\"*60)\n",
1187
+ "\n",
1188
+ " recon = pycolmap.Reconstruction(str(sparse_dir))\n",
1189
+ " print(f\" Cameras: {len(recon.cameras)}\")\n",
1190
+ " print(f\" Images: {len(recon.images)}\")\n",
1191
+ " print(f\" Points: {len(recon.points3D)}\")\n",
1192
+ "\n",
1193
+ " if len(recon.points3D) == 0:\n",
1194
+ " print(\" [WARN] No 3D points found\")\n",
1195
+ " return 0\n",
1196
+ "\n",
1197
+ " pts = np.array([p.xyz for p in recon.points3D.values()])\n",
1198
+ " cols = np.array([p.color for p in recon.points3D.values()])\n",
1199
+ "\n",
1200
+ " print(f\" X: [{pts[:,0].min():.3f}, {pts[:,0].max():.3f}]\")\n",
1201
+ " print(f\" Y: [{pts[:,1].min():.3f}, {pts[:,1].max():.3f}]\")\n",
1202
+ " print(f\" Z: [{pts[:,2].min():.3f}, {pts[:,2].max():.3f}]\")\n",
1203
+ "\n",
1204
+ " verts = np.array(\n",
1205
+ " [(p[0], p[1], p[2], c[0], c[1], c[2]) for p, c in zip(pts, cols)],\n",
1206
+ " dtype=[('x','f4'),('y','f4'),('z','f4'),\n",
1207
+ " ('red','u1'),('green','u1'),('blue','u1')]\n",
1208
+ " )\n",
1209
+ " PlyData([PlyElement.describe(verts, 'vertex')]).write(ply_path)\n",
1210
+ " print(f\" ✓ PLY saved → {ply_path}\")\n",
1211
+ " return len(pts)"
1212
+ ],
1213
+ "metadata": {
1214
+ "execution": {
1215
+ "iopub.status.busy": "2026-04-06T17:49:34.404201Z",
1216
+ "iopub.execute_input": "2026-04-06T17:49:34.404464Z",
1217
+ "iopub.status.idle": "2026-04-06T17:49:34.419441Z",
1218
+ "shell.execute_reply.started": "2026-04-06T17:49:34.404444Z",
1219
+ "shell.execute_reply": "2026-04-06T17:49:34.418818Z"
1220
+ },
1221
+ "papermill": {
1222
+ "duration": 0.039919,
1223
+ "end_time": "2026-03-26T12:56:07.127924",
1224
+ "exception": false,
1225
+ "start_time": "2026-03-26T12:56:07.088005",
1226
+ "status": "completed"
1227
+ },
1228
+ "tags": [],
1229
+ "trusted": true,
1230
+ "id": "AK3jlVkLMlOd"
1231
+ },
1232
+ "outputs": [],
1233
+ "execution_count": 11
1234
+ },
1235
+ {
1236
+ "cell_type": "code",
1237
+ "source": [
1238
+ "# ============================================================================\n",
1239
+ "# Step 5: PLY Viewer (for Kaggle Notebook)\n",
1240
+ "# ============================================================================\n",
1241
+ "\n",
1242
+ "def display_ply_viewer(ply_file_path):\n",
1243
+ " from IPython.display import HTML, display as ipy_display\n",
1244
+ "\n",
1245
+ " with open(ply_file_path, 'rb') as f:\n",
1246
+ " ply_b64 = base64.b64encode(f.read()).decode('utf-8')\n",
1247
+ "\n",
1248
+ " html = f\"\"\"\n",
1249
+ " <div id=\"ply-container\" style=\"width:100%;height:600px;position:relative;background:#1a1a1a;\">\n",
1250
+ " <div id=\"ply-info\" style=\"position:absolute;top:10px;left:10px;\n",
1251
+ " background:rgba(0,0,0,.7);color:#fff;padding:10px;\n",
1252
+ " border-radius:5px;font-size:12px;z-index:100;\">Loading…</div>\n",
1253
+ " <button onclick=\"resetView()\" style=\"position:absolute;top:10px;right:10px;\n",
1254
+ " background:#4CAF50;color:#fff;border:none;padding:8px 14px;\n",
1255
+ " border-radius:4px;cursor:pointer;z-index:100;\">Reset View</button>\n",
1256
+ " </div>\n",
1257
+ " <script type=\"importmap\">\n",
1258
+ " {{\"imports\":{{\n",
1259
+ " \"three\":\"https://unpkg.com/three@0.160.0/build/three.module.js\",\n",
1260
+ " \"three/examples/jsm/loaders/PLYLoader.js\":\"https://unpkg.com/three@0.160.0/examples/jsm/loaders/PLYLoader.js\",\n",
1261
+ " \"three/examples/jsm/controls/OrbitControls.js\":\"https://unpkg.com/three@0.160.0/examples/jsm/controls/OrbitControls.js\"\n",
1262
+ " }}}}\n",
1263
+ " </script>\n",
1264
+ " <script type=\"module\">\n",
1265
+ " import * as THREE from 'three';\n",
1266
+ " import {{ PLYLoader }} from 'three/examples/jsm/loaders/PLYLoader.js';\n",
1267
+ " import {{ OrbitControls }} from 'three/examples/jsm/controls/OrbitControls.js';\n",
1268
+ "\n",
1269
+ " const container = document.getElementById('ply-container');\n",
1270
+ " const scene = new THREE.Scene();\n",
1271
+ " scene.background = new THREE.Color(0x1a1a1a);\n",
1272
+ "\n",
1273
+ " const camera = new THREE.PerspectiveCamera(60,\n",
1274
+ " container.clientWidth / container.clientHeight, 0.001, 10000);\n",
1275
+ " const renderer = new THREE.WebGLRenderer({{antialias:true}});\n",
1276
+ " renderer.setSize(container.clientWidth, container.clientHeight);\n",
1277
+ " container.appendChild(renderer.domElement);\n",
1278
+ "\n",
1279
+ " const controls = new OrbitControls(camera, renderer.domElement);\n",
1280
+ " controls.enableDamping = true;\n",
1281
+ "\n",
1282
+ " scene.add(new THREE.GridHelper(100,50,0x444444,0x222222));\n",
1283
+ "\n",
1284
+ " let cloud = null;\n",
1285
+ " window.resetView = function() {{\n",
1286
+ " if (!cloud) return;\n",
1287
+ " cloud.geometry.computeBoundingBox();\n",
1288
+ " const bb = cloud.geometry.boundingBox;\n",
1289
+ " const center = new THREE.Vector3(); bb.getCenter(center);\n",
1290
+ " const size = new THREE.Vector3(); bb.getSize(size);\n",
1291
+ " const d = Math.max(size.x,size.y,size.z) / Math.tan(camera.fov*Math.PI/360) * 1.2;\n",
1292
+ " camera.position.set(center.x+d, center.y+d*0.6, center.z+d);\n",
1293
+ " controls.target.copy(center); controls.update();\n",
1294
+ " }};\n",
1295
+ "\n",
1296
+ " // decode base64 PLY\n",
1297
+ " const b64 = '{ply_b64}';\n",
1298
+ " const bin = atob(b64);\n",
1299
+ " const buf = new Uint8Array(bin.length);\n",
1300
+ " for(let i=0;i<bin.length;i++) buf[i]=bin.charCodeAt(i);\n",
1301
+ "\n",
1302
+ " new PLYLoader().parse(buf.buffer, geo => {{\n",
1303
+ " const mat = new THREE.PointsMaterial({{\n",
1304
+ " size: 0.003, vertexColors: geo.attributes.color !== undefined,\n",
1305
+ " sizeAttenuation: true\n",
1306
+ " }});\n",
1307
+ " if (!geo.attributes.color) mat.color = new THREE.Color(0x00aaff);\n",
1308
+ " cloud = new THREE.Points(geo, mat);\n",
1309
+ " scene.add(cloud);\n",
1310
+ " window.resetView();\n",
1311
+ " const n = geo.attributes.position.count;\n",
1312
+ " geo.computeBoundingBox();\n",
1313
+ " const s = new THREE.Vector3(); geo.boundingBox.getSize(s);\n",
1314
+ " document.getElementById('ply-info').innerHTML =\n",
1315
+ " '<b>Point Cloud</b><br>Points: '+n.toLocaleString()+\n",
1316
+ " '<br>Size: ('+s.x.toFixed(2)+', '+s.y.toFixed(2)+', '+s.z.toFixed(2)+')';\n",
1317
+ " }});\n",
1318
+ "\n",
1319
+ " (function animate(){{ requestAnimationFrame(animate); controls.update(); renderer.render(scene,camera); }})();\n",
1320
+ " </script>\n",
1321
+ " \"\"\"\n",
1322
+ " ipy_display(HTML(html))"
1323
+ ],
1324
+ "metadata": {
1325
+ "execution": {
1326
+ "iopub.status.busy": "2026-04-06T17:49:34.420203Z",
1327
+ "iopub.execute_input": "2026-04-06T17:49:34.420438Z",
1328
+ "iopub.status.idle": "2026-04-06T17:49:34.436357Z",
1329
+ "shell.execute_reply.started": "2026-04-06T17:49:34.420417Z",
1330
+ "shell.execute_reply": "2026-04-06T17:49:34.435779Z"
1331
+ },
1332
+ "papermill": {
1333
+ "duration": 0.009872,
1334
+ "end_time": "2026-03-26T12:56:07.140176",
1335
+ "exception": false,
1336
+ "start_time": "2026-03-26T12:56:07.130304",
1337
+ "status": "completed"
1338
+ },
1339
+ "tags": [],
1340
+ "trusted": true,
1341
+ "id": "sZM_vDJHMlOd"
1342
+ },
1343
+ "outputs": [],
1344
+ "execution_count": 12
1345
+ },
1346
+ {
1347
+ "cell_type": "code",
1348
+ "source": [
1349
+ "!pip show numpy | grep Version:"
1350
+ ],
1351
+ "metadata": {
1352
+ "trusted": true,
1353
+ "execution": {
1354
+ "iopub.status.busy": "2026-04-06T17:49:34.437222Z",
1355
+ "iopub.execute_input": "2026-04-06T17:49:34.437774Z",
1356
+ "iopub.status.idle": "2026-04-06T17:49:36.524893Z",
1357
+ "shell.execute_reply.started": "2026-04-06T17:49:34.437752Z",
1358
+ "shell.execute_reply": "2026-04-06T17:49:36.52421Z"
1359
+ },
1360
+ "id": "WvyH2N7iMlOe",
1361
+ "colab": {
1362
+ "base_uri": "https://localhost:8080/"
1363
+ },
1364
+ "outputId": "8b8b7781-29cf-4460-daf7-d0f84c9c3670"
1365
+ },
1366
+ "outputs": [
1367
+ {
1368
+ "output_type": "stream",
1369
+ "name": "stdout",
1370
+ "text": [
1371
+ "Version: 1.26.4\n"
1372
+ ]
1373
+ }
1374
+ ],
1375
+ "execution_count": 13
1376
+ },
1377
+ {
1378
+ "cell_type": "code",
1379
+ "source": [
1380
+ "# ============================================================================\n",
1381
+ "# MAIN PIPELINE\n",
1382
+ "# ============================================================================\n",
1383
+ "\n",
1384
+ "# ---------- Path Settings ----------\n",
1385
+ "IMAGE_DIR = \"/content/drive/MyDrive/your_folder/fountain40\"\n",
1386
+ "OUTPUT_DIR = \"/content/output\"\n",
1387
+ "CACHE_DIR = os.path.join(OUTPUT_DIR, \"sfm_cache\")\n",
1388
+ "COLMAP_DIR = os.path.join(OUTPUT_DIR, \"colmap\")\n",
1389
+ "PLY_PATH = os.path.join(COLMAP_DIR, \"point_cloud.ply\")\n",
1390
+ "SQUARE_DIR = os.path.join(OUTPUT_DIR, \"processed_images\")\n",
1391
+ "\n",
1392
+ "os.makedirs(OUTPUT_DIR, exist_ok=True)"
1393
+ ],
1394
+ "metadata": {
1395
+ "execution": {
1396
+ "iopub.status.busy": "2026-04-06T17:49:36.527948Z",
1397
+ "iopub.execute_input": "2026-04-06T17:49:36.528175Z",
1398
+ "iopub.status.idle": "2026-04-06T17:49:36.533197Z",
1399
+ "shell.execute_reply.started": "2026-04-06T17:49:36.528152Z",
1400
+ "shell.execute_reply": "2026-04-06T17:49:36.532589Z"
1401
+ },
1402
+ "papermill": {
1403
+ "duration": 274.479691,
1404
+ "end_time": "2026-03-26T13:00:41.621869",
1405
+ "exception": false,
1406
+ "start_time": "2026-03-26T12:56:07.142178",
1407
+ "status": "completed"
1408
+ },
1409
+ "tags": [],
1410
+ "trusted": true,
1411
+ "id": "WX3MLZIcMlOe"
1412
+ },
1413
+ "outputs": [],
1414
+ "execution_count": 14
1415
+ },
1416
+ {
1417
+ "cell_type": "code",
1418
+ "source": [
1419
+ "# ---------- 0. Environment Setup ----------\n",
1420
+ "setup_base_environment()\n",
1421
+ "clear_memory()"
1422
+ ],
1423
+ "metadata": {
1424
+ "trusted": true,
1425
+ "_kg_hide-output": true,
1426
+ "execution": {
1427
+ "iopub.status.busy": "2026-04-06T17:49:36.534034Z",
1428
+ "iopub.execute_input": "2026-04-06T17:49:36.534309Z",
1429
+ "iopub.status.idle": "2026-04-06T17:50:09.924118Z",
1430
+ "shell.execute_reply.started": "2026-04-06T17:49:36.534278Z",
1431
+ "shell.execute_reply": "2026-04-06T17:50:09.923456Z"
1432
+ },
1433
+ "id": "lcXem-fiMlOe",
1434
+ "colab": {
1435
+ "base_uri": "https://localhost:8080/"
1436
+ },
1437
+ "outputId": "e094627e-ae44-4c17-8ff8-396d21e28d1f"
1438
+ },
1439
+ "outputs": [
1440
+ {
1441
+ "output_type": "stream",
1442
+ "name": "stdout",
1443
+ "text": [
1444
+ "\n",
1445
+ "============================================================\n",
1446
+ "Step 0-A: Base Environment Setup\n",
1447
+ "============================================================\n",
1448
+ " $ /usr/bin/python3 -m pip uninstall -y numpy\n",
1449
+ " $ /usr/bin/python3 -m pip install numpy==1.26.4\n",
1450
+ " $ /usr/bin/python3 -m pip install torch torchvision torchaudio\n",
1451
+ " $ /usr/bin/python3 -m pip install opencv-python pillow imageio imageio-ffmpeg plyfile tqdm scipy psutil roma trimesh matplotlib\n",
1452
+ " $ /usr/bin/python3 -m pip install transformers==4.40.0\n",
1453
+ " $ /usr/bin/python3 -m pip install pycolmap\n",
1454
+ "✓ Base environment ready\n"
1455
+ ]
1456
+ }
1457
+ ],
1458
+ "execution_count": 15
1459
+ },
1460
+ {
1461
+ "cell_type": "code",
1462
+ "source": [
1463
+ "!pip show numpy | grep Version:"
1464
+ ],
1465
+ "metadata": {
1466
+ "trusted": true,
1467
+ "execution": {
1468
+ "iopub.status.busy": "2026-04-06T17:50:09.924978Z",
1469
+ "iopub.execute_input": "2026-04-06T17:50:09.925249Z",
1470
+ "iopub.status.idle": "2026-04-06T17:50:12.066269Z",
1471
+ "shell.execute_reply.started": "2026-04-06T17:50:09.925222Z",
1472
+ "shell.execute_reply": "2026-04-06T17:50:12.065517Z"
1473
+ },
1474
+ "id": "RBQp_Ih6MlOe",
1475
+ "colab": {
1476
+ "base_uri": "https://localhost:8080/"
1477
+ },
1478
+ "outputId": "698ded1a-82f5-4256-f2bc-a99aa166ae71"
1479
+ },
1480
+ "outputs": [
1481
+ {
1482
+ "output_type": "stream",
1483
+ "name": "stdout",
1484
+ "text": [
1485
+ "Version: 2.4.4\n"
1486
+ ]
1487
+ }
1488
+ ],
1489
+ "execution_count": 16
1490
+ },
1491
+ {
1492
+ "cell_type": "code",
1493
+ "source": [
1494
+ "setup_mast3r()"
1495
+ ],
1496
+ "metadata": {
1497
+ "trusted": true,
1498
+ "execution": {
1499
+ "iopub.status.busy": "2026-04-06T17:50:12.067628Z",
1500
+ "iopub.execute_input": "2026-04-06T17:50:12.067907Z",
1501
+ "iopub.status.idle": "2026-04-06T17:52:25.400382Z",
1502
+ "shell.execute_reply.started": "2026-04-06T17:50:12.06788Z",
1503
+ "shell.execute_reply": "2026-04-06T17:52:25.399751Z"
1504
+ },
1505
+ "_kg_hide-output": true,
1506
+ "id": "WcuV-k58MlOe",
1507
+ "colab": {
1508
+ "base_uri": "https://localhost:8080/"
1509
+ },
1510
+ "outputId": "713b4d7b-fbc1-44d1-eb5e-9d4b2f2c47dc"
1511
+ },
1512
+ "outputs": [
1513
+ {
1514
+ "output_type": "stream",
1515
+ "name": "stdout",
1516
+ "text": [
1517
+ "\n",
1518
+ "============================================================\n",
1519
+ "Step 0-B: MASt3R Setup\n",
1520
+ "============================================================\n",
1521
+ "⏱️ elapsed=03:00 ⏳ remain=236:59 | 🔥 CPU= 7.3% 💾 RAM= 4.0% | 🧠 GPU0= 0.0% 🎮 VRAM0= 0.8%\n",
1522
+ "Warning, cannot find cuda-compiled version of RoPE2D, using a slow pytorch version instead\n",
1523
+ " ✓ MASt3R import OK\n",
1524
+ "✓ MASt3R ready\n"
1525
+ ]
1526
+ }
1527
+ ],
1528
+ "execution_count": 17
1529
+ },
1530
+ {
1531
+ "cell_type": "code",
1532
+ "source": [
1533
+ "# ASMK (Fallback to swin if setup fails)\n",
1534
+ "asmk_ok = setup_asmk()\n",
1535
+ "clear_memory()"
1536
+ ],
1537
+ "metadata": {
1538
+ "execution": {
1539
+ "iopub.status.busy": "2026-04-06T17:52:25.401238Z",
1540
+ "iopub.execute_input": "2026-04-06T17:52:25.401601Z",
1541
+ "iopub.status.idle": "2026-04-06T17:52:41.5606Z",
1542
+ "shell.execute_reply.started": "2026-04-06T17:52:25.401578Z",
1543
+ "shell.execute_reply": "2026-04-06T17:52:41.559803Z"
1544
+ },
1545
+ "papermill": {
1546
+ "duration": 274.479691,
1547
+ "end_time": "2026-03-26T13:00:41.621869",
1548
+ "exception": false,
1549
+ "start_time": "2026-03-26T12:56:07.142178",
1550
+ "status": "completed"
1551
+ },
1552
+ "tags": [],
1553
+ "trusted": true,
1554
+ "id": "AUuPsrrvMlOe",
1555
+ "colab": {
1556
+ "base_uri": "https://localhost:8080/"
1557
+ },
1558
+ "outputId": "46c89fb0-07c2-4cd0-f775-fe92fbd71ade"
1559
+ },
1560
+ "outputs": [
1561
+ {
1562
+ "output_type": "stream",
1563
+ "name": "stdout",
1564
+ "text": [
1565
+ "\n",
1566
+ "============================================================\n",
1567
+ "Step 0-C: ASMK Setup (for retrieval pair selection)\n",
1568
+ "============================================================\n",
1569
+ " $ /usr/bin/python3 -m pip install cython\n",
1570
+ " ✓ ASMK import OK\n"
1571
+ ]
1572
+ }
1573
+ ],
1574
+ "execution_count": 18
1575
+ },
1576
+ {
1577
+ "cell_type": "code",
1578
+ "source": [
1579
+ "!pip show numpy | grep Version:\n",
1580
+ "\n",
1581
+ "!pip uninstall numpy -y\n",
1582
+ "!pip install \"numpy==1.26.4\" \"scipy>=1.12\" --quiet\n",
1583
+ "\n",
1584
+ "!pip show numpy | grep Version:"
1585
+ ],
1586
+ "metadata": {
1587
+ "trusted": true,
1588
+ "execution": {
1589
+ "iopub.status.busy": "2026-04-06T17:52:41.561633Z",
1590
+ "iopub.execute_input": "2026-04-06T17:52:41.561965Z",
1591
+ "iopub.status.idle": "2026-04-06T17:52:52.421496Z",
1592
+ "shell.execute_reply.started": "2026-04-06T17:52:41.561919Z",
1593
+ "shell.execute_reply": "2026-04-06T17:52:52.420529Z"
1594
+ },
1595
+ "id": "-q6AjUb2MlOe",
1596
+ "colab": {
1597
+ "base_uri": "https://localhost:8080/"
1598
+ },
1599
+ "outputId": "9c0fdf01-b7e5-453e-cf2e-c667bdd7c194"
1600
+ },
1601
+ "outputs": [
1602
+ {
1603
+ "output_type": "stream",
1604
+ "name": "stdout",
1605
+ "text": [
1606
+ "Version: 2.4.4\n",
1607
+ "Found existing installation: numpy 2.4.4\n",
1608
+ "Uninstalling numpy-2.4.4:\n",
1609
+ " Successfully uninstalled numpy-2.4.4\n",
1610
+ "\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",
1611
+ "shap 0.51.0 requires numpy>=2, but you have numpy 1.26.4 which is incompatible.\n",
1612
+ "opencv-python 4.13.0.92 requires numpy>=2; python_version >= \"3.9\", but you have numpy 1.26.4 which is incompatible.\n",
1613
+ "rasterio 1.5.0 requires numpy>=2, but you have numpy 1.26.4 which is incompatible.\n",
1614
+ "jax 0.7.2 requires numpy>=2.0, but you have numpy 1.26.4 which is incompatible.\n",
1615
+ "pytensor 2.38.2 requires numpy>=2.0, but you have numpy 1.26.4 which is incompatible.\n",
1616
+ "cupy-cuda12x 14.0.1 requires numpy<2.6,>=2.0, but you have numpy 1.26.4 which is incompatible.\n",
1617
+ "opencv-python-headless 4.13.0.92 requires numpy>=2; python_version >= \"3.9\", but you have numpy 1.26.4 which is incompatible.\n",
1618
+ "xarray-einstats 0.10.0 requires numpy>=2.0, but you have numpy 1.26.4 which is incompatible.\n",
1619
+ "opencv-contrib-python 4.13.0.92 requires numpy>=2; python_version >= \"3.9\", but you have numpy 1.26.4 which is incompatible.\n",
1620
+ "sentence-transformers 5.3.0 requires transformers<6.0.0,>=4.41.0, but you have transformers 4.40.0 which is incompatible.\n",
1621
+ "tobler 0.13.0 requires numpy>=2.0, but you have numpy 1.26.4 which is incompatible.\n",
1622
+ "jaxlib 0.7.2 requires numpy>=2.0, but you have numpy 1.26.4 which is incompatible.\u001b[0m\u001b[31m\n",
1623
+ "\u001b[0mVersion: 1.26.4\n"
1624
+ ]
1625
+ }
1626
+ ],
1627
+ "execution_count": 19
1628
+ },
1629
+ {
1630
+ "cell_type": "code",
1631
+ "source": [
1632
+ "# ---------- 1. Biplet Normalization ----------\n",
1633
+ "normalize_image_sizes_biplet(IMAGE_DIR, SQUARE_DIR, size=Config.SQUARE_SIZE)\n",
1634
+ "\n",
1635
+ "image_paths = sorted([\n",
1636
+ " os.path.join(SQUARE_DIR, f)\n",
1637
+ " for f in os.listdir(SQUARE_DIR)\n",
1638
+ " if f.lower().endswith(('.jpg', '.jpeg', '.png'))\n",
1639
+ "])\n",
1640
+ "print(f\"\\n📸 {len(image_paths)} images ready\")"
1641
+ ],
1642
+ "metadata": {
1643
+ "execution": {
1644
+ "iopub.status.busy": "2026-04-06T17:52:52.422971Z",
1645
+ "iopub.execute_input": "2026-04-06T17:52:52.423248Z",
1646
+ "iopub.status.idle": "2026-04-06T17:52:58.038813Z",
1647
+ "shell.execute_reply.started": "2026-04-06T17:52:52.42322Z",
1648
+ "shell.execute_reply": "2026-04-06T17:52:58.038003Z"
1649
+ },
1650
+ "papermill": {
1651
+ "duration": 12.082868,
1652
+ "end_time": "2026-03-26T13:00:53.831242",
1653
+ "exception": true,
1654
+ "start_time": "2026-03-26T13:00:41.748374",
1655
+ "status": "failed"
1656
+ },
1657
+ "tags": [],
1658
+ "trusted": true,
1659
+ "id": "CgJu6DrgMlOe",
1660
+ "colab": {
1661
+ "base_uri": "https://localhost:8080/"
1662
+ },
1663
+ "outputId": "5ee64aab-07f4-45d6-8b38-39fe4b64751d"
1664
+ },
1665
+ "outputs": [
1666
+ {
1667
+ "output_type": "stream",
1668
+ "name": "stdout",
1669
+ "text": [
1670
+ "\n",
1671
+ "============================================================\n",
1672
+ "Step 1: Biplet-Square Normalization\n",
1673
+ "============================================================\n",
1674
+ " ✓ image_001.jpeg: (1440, 1920) → 2 crops\n",
1675
+ " ✓ image_002.jpeg: (1440, 1920) → 2 crops\n",
1676
+ " ✓ image_003.jpeg: (1440, 1920) → 2 crops\n",
1677
+ " ✓ image_004.jpeg: (1440, 1920) → 2 crops\n",
1678
+ " ✓ image_005.jpeg: (1440, 1920) → 2 crops\n",
1679
+ " ✓ image_006.jpeg: (1440, 1920) → 2 crops\n",
1680
+ " ✓ image_007.jpeg: (1440, 1920) → 2 crops\n",
1681
+ " ✓ image_008.jpeg: (1440, 1920) → 2 crops\n",
1682
+ " ✓ image_009.jpeg: (1440, 1920) → 2 crops\n",
1683
+ " ✓ image_010.jpeg: (1440, 1920) → 2 crops\n",
1684
+ " ✓ image_011.jpeg: (1440, 1920) → 2 crops\n",
1685
+ " ✓ image_012.jpeg: (1440, 1920) → 2 crops\n",
1686
+ " ✓ image_013.jpeg: (1440, 1920) → 2 crops\n",
1687
+ " ✓ image_014.jpeg: (1440, 1920) → 2 crops\n",
1688
+ " ✓ image_015.jpeg: (1440, 1920) → 2 crops\n",
1689
+ " ✓ image_016.jpeg: (1440, 1920) → 2 crops\n",
1690
+ " ✓ image_017.jpeg: (1440, 1920) → 2 crops\n",
1691
+ " ✓ image_018.jpeg: (1440, 1920) → 2 crops\n",
1692
+ " ✓ image_019.jpeg: (1440, 1920) → 2 crops\n",
1693
+ " ✓ image_020.jpeg: (1440, 1920) → 2 crops\n",
1694
+ " ✓ image_021.jpeg: (1440, 1920) → 2 crops\n",
1695
+ " ✓ image_022.jpeg: (1440, 1920) → 2 crops\n",
1696
+ " ✓ image_023.jpeg: (1440, 1920) → 2 crops\n",
1697
+ " ✓ image_024.jpeg: (1440, 1920) → 2 crops\n",
1698
+ " ✓ image_025.jpeg: (1440, 1920) → 2 crops\n",
1699
+ " ✓ image_026.jpeg: (1440, 1920) → 2 crops\n",
1700
+ " ✓ image_027.jpeg: (1440, 1920) → 2 crops\n",
1701
+ " ✓ image_028.jpeg: (1440, 1920) → 2 crops\n",
1702
+ " ✓ image_029.jpeg: (1440, 1920) → 2 crops\n",
1703
+ " ✓ image_030.jpeg: (1440, 1920) → 2 crops\n",
1704
+ " ✓ image_031.jpeg: (1440, 1920) → 2 crops\n",
1705
+ " ✓ image_032.jpeg: (1440, 1920) → 2 crops\n",
1706
+ " ✓ image_033.jpeg: (1440, 1920) → 2 crops\n",
1707
+ " ✓ image_034.jpeg: (1440, 1920) → 2 crops\n",
1708
+ " ✓ image_035.jpeg: (1440, 1920) → 2 crops\n",
1709
+ " ✓ image_036.jpeg: (1440, 1920) → 2 crops\n",
1710
+ " ✓ image_037.jpeg: (1440, 1920) → 2 crops\n",
1711
+ " ✓ image_038.jpeg: (1440, 1920) → 2 crops\n",
1712
+ " ✓ image_039.jpeg: (1440, 1920) → 2 crops\n",
1713
+ " ✓ image_040.jpeg: (1440, 1920) → 2 crops\n",
1714
+ " Total: 40 images → 80 crops\n",
1715
+ "\n",
1716
+ "📸 80 images ready\n"
1717
+ ]
1718
+ }
1719
+ ],
1720
+ "execution_count": 20
1721
+ },
1722
+ {
1723
+ "cell_type": "code",
1724
+ "source": [
1725
+ "!pip show numpy | grep Version:"
1726
+ ],
1727
+ "metadata": {
1728
+ "trusted": true,
1729
+ "execution": {
1730
+ "iopub.status.busy": "2026-04-06T17:52:58.040056Z",
1731
+ "iopub.execute_input": "2026-04-06T17:52:58.040398Z",
1732
+ "iopub.status.idle": "2026-04-06T17:53:00.13663Z",
1733
+ "shell.execute_reply.started": "2026-04-06T17:52:58.040365Z",
1734
+ "shell.execute_reply": "2026-04-06T17:53:00.135711Z"
1735
+ },
1736
+ "id": "wNVD6s0cMlOe",
1737
+ "colab": {
1738
+ "base_uri": "https://localhost:8080/"
1739
+ },
1740
+ "outputId": "afedfff3-66a9-413e-cb2e-73d81e2b83d9"
1741
+ },
1742
+ "outputs": [
1743
+ {
1744
+ "output_type": "stream",
1745
+ "name": "stdout",
1746
+ "text": [
1747
+ "Version: 1.26.4\n"
1748
+ ]
1749
+ }
1750
+ ],
1751
+ "execution_count": 21
1752
+ },
1753
+ {
1754
+ "cell_type": "code",
1755
+ "source": [
1756
+ "# ---------- 2. MASt3R-SfM ----------\n",
1757
+ "model = load_mast3r_model()\n",
1758
+ "\n",
1759
+ "scene = run_mast3r_sfm(\n",
1760
+ " model,\n",
1761
+ " image_paths,\n",
1762
+ " cache_dir=CACHE_DIR,\n",
1763
+ " asmk_available=asmk_ok,\n",
1764
+ ")\n",
1765
+ "\n",
1766
+ "del model\n",
1767
+ "clear_memory()"
1768
+ ],
1769
+ "metadata": {
1770
+ "execution": {
1771
+ "iopub.status.busy": "2026-04-06T17:53:00.137978Z",
1772
+ "iopub.execute_input": "2026-04-06T17:53:00.1383Z",
1773
+ "iopub.status.idle": "2026-04-06T18:08:48.305441Z",
1774
+ "shell.execute_reply.started": "2026-04-06T17:53:00.138264Z",
1775
+ "shell.execute_reply": "2026-04-06T18:08:48.304688Z"
1776
+ },
1777
+ "papermill": {
1778
+ "duration": 12.082868,
1779
+ "end_time": "2026-03-26T13:00:53.831242",
1780
+ "exception": true,
1781
+ "start_time": "2026-03-26T13:00:41.748374",
1782
+ "status": "failed"
1783
+ },
1784
+ "tags": [],
1785
+ "trusted": true,
1786
+ "id": "EHyN5OqZMlOe",
1787
+ "colab": {
1788
+ "base_uri": "https://localhost:8080/"
1789
+ },
1790
+ "outputId": "e4b0b168-2ae6-41d5-a97f-725ae00953f2"
1791
+ },
1792
+ "outputs": [
1793
+ {
1794
+ "output_type": "stream",
1795
+ "name": "stdout",
1796
+ "text": [
1797
+ "... loading model from /content/mast3r/checkpoints/MASt3R_ViTLarge_BaseDecoder_512_catmlpdpt_metric.pth\n",
1798
+ "instantiating : AsymmetricMASt3R(enc_depth=24, dec_depth=12, enc_embed_dim=1024, dec_embed_dim=768, enc_num_heads=16, dec_num_heads=12, pos_embed='RoPE100',img_size=(512, 512), head_type='catmlp+dpt', output_mode='pts3d+desc24', depth_mode=('exp', -inf, inf), conf_mode=('exp', 1, inf), patch_embed_cls='PatchEmbedDust3R', two_confs=True, desc_conf_mode=('exp', 0, inf), landscape_only=False)\n",
1799
+ "<All keys matched successfully>\n",
1800
+ " ✓ MASt3R loaded on cuda\n",
1801
+ "\n",
1802
+ "============================================================\n",
1803
+ "Step 2: MASt3R-SfM (sparse_global_alignment)\n",
1804
+ "============================================================\n"
1805
+ ]
1806
+ },
1807
+ {
1808
+ "output_type": "stream",
1809
+ "name": "stderr",
1810
+ "text": [
1811
+ "/content/mast3r/dust3r/dust3r/cloud_opt/base_opt.py:275: FutureWarning: `torch.cuda.amp.autocast(args...)` is deprecated. Please use `torch.amp.autocast('cuda', args...)` instead.\n",
1812
+ " @torch.cuda.amp.autocast(enabled=False)\n"
1813
+ ]
1814
+ },
1815
+ {
1816
+ "output_type": "stream",
1817
+ "name": "stdout",
1818
+ "text": [
1819
+ " Loading 80 images at size=512…\n",
1820
+ " Loaded 80 images\n",
1821
+ " scene_graph = 'retrieval-10-15'\n",
1822
+ " [WARN] sim_mat construction failed (No module named 'faiss') → falling back to 'logwin-5'\n",
1823
+ " ✓ make_pairs: 800 pairs selected\n",
1824
+ " Running sparse_global_alignment…\n",
1825
+ " Memory before alignment:\n",
1826
+ " GPU - Allocated: 2.58 GB, Reserved: 2.68 GB\n",
1827
+ " CPU - Usage: 8.3%\n"
1828
+ ]
1829
+ },
1830
+ {
1831
+ "output_type": "stream",
1832
+ "name": "stderr",
1833
+ "text": [
1834
+ "\r 0%| | 0/800 [00:00<?, ?it/s]/content/mast3r/mast3r/cloud_opt/sparse_ga.py:620: FutureWarning: `torch.cuda.amp.autocast(args...)` is deprecated. Please use `torch.amp.autocast('cuda', args...)` instead.\n",
1835
+ " with torch.cuda.amp.autocast(enabled=False):\n",
1836
+ " 6%|▋ | 50/800 [00:50<12:57, 1.04s/it]"
1837
+ ]
1838
+ },
1839
+ {
1840
+ "output_type": "stream",
1841
+ "name": "stdout",
1842
+ "text": [
1843
+ "⏱️ elapsed=06:00 ⏳ remain=233:59 | 🔥 CPU= 8.8% 💾 RAM= 8.3% | 🧠 GPU0= 49.0% 🎮 VRAM0= 21.8%\n"
1844
+ ]
1845
+ },
1846
+ {
1847
+ "output_type": "stream",
1848
+ "name": "stderr",
1849
+ "text": [
1850
+ "\r 6%|▋ | 51/800 [00:51<12:29, 1.00s/it]/content/mast3r/mast3r/cloud_opt/sparse_ga.py:620: FutureWarning: `torch.cuda.amp.autocast(args...)` is deprecated. Please use `torch.amp.autocast('cuda', args...)` instead.\n",
1851
+ " with torch.cuda.amp.autocast(enabled=False):\n",
1852
+ " 29%|██▉ | 235/800 [03:50<09:24, 1.00it/s]"
1853
+ ]
1854
+ },
1855
+ {
1856
+ "output_type": "stream",
1857
+ "name": "stdout",
1858
+ "text": [
1859
+ "⏱️ elapsed=09:00 ⏳ remain=230:59 | 🔥 CPU= 11.2% 💾 RAM= 8.3% | 🧠 GPU0= 67.0% 🎮 VRAM0= 22.9%\n"
1860
+ ]
1861
+ },
1862
+ {
1863
+ "output_type": "stream",
1864
+ "name": "stderr",
1865
+ "text": [
1866
+ "\r 30%|██▉ | 236/800 [03:51<08:56, 1.05it/s]/content/mast3r/mast3r/cloud_opt/sparse_ga.py:620: FutureWarning: `torch.cuda.amp.autocast(args...)` is deprecated. Please use `torch.amp.autocast('cuda', args...)` instead.\n",
1867
+ " with torch.cuda.amp.autocast(enabled=False):\n",
1868
+ "100%|██████████| 800/800 [06:33<00:00, 2.03it/s] \n",
1869
+ "100%|██████████| 80/80 [00:09<00:00, 8.02it/s]\n"
1870
+ ]
1871
+ },
1872
+ {
1873
+ "output_type": "stream",
1874
+ "name": "stdout",
1875
+ "text": [
1876
+ "init focals = [460.99475 442.9157 480.44702 455.24722 459.86887 477.10223 461.1392\n",
1877
+ " 474.9273 462.6865 491.26227 455.02667 489.85712 444.27496 485.3484\n",
1878
+ " 439.21164 492.6651 450.99872 519.3947 453.8241 515.585 458.11752\n",
1879
+ " 527.97186 458.20883 525.85455 452.67862 532.2186 453.0267 527.71814\n",
1880
+ " 456.25797 528.11005 459.404 542.64844 450.9108 529.36285 453.1492\n",
1881
+ " 530.49567 452.48782 518.0516 456.59747 505.25287 465.35846 540.5645\n",
1882
+ " 479.32074 527.3381 480.63675 515. 474.00424 507.94147 490.95197\n",
1883
+ " 525.7926 497.64835 517.86285 497.49414 513.20996 491.776 506.54996\n",
1884
+ " 477.41492 505.2047 487.5938 510.6259 489.7721 518.26135 491.88153\n",
1885
+ " 507.51852 475.5734 506.14023 481.36337 514.8018 484.54388 503.91534\n",
1886
+ " 475.57227 512.20294 466.67865 508.99518 457.25 506.96512 460.95297\n",
1887
+ " 494.95407 458.2521 471.0948 ]\n"
1888
+ ]
1889
+ },
1890
+ {
1891
+ "output_type": "stream",
1892
+ "name": "stderr",
1893
+ "text": [
1894
+ " 0%| | 0/300 [00:00<?, ?it/s]/content/mast3r/mast3r/cloud_opt/sparse_ga.py:457: UserWarning: Converting a tensor with requires_grad=True to a scalar may lead to unexpected behavior.\n",
1895
+ "Consider using tensor.detach() first. (Triggered internally at /pytorch/torch/csrc/autograd/generated/python_variable_methods.cpp:836.)\n",
1896
+ " loss = float(loss)\n",
1897
+ " 9%|▊ | 26/300 [00:06<01:05, 4.20it/s, lr=0.0688, loss=0.289]"
1898
+ ]
1899
+ },
1900
+ {
1901
+ "output_type": "stream",
1902
+ "name": "stdout",
1903
+ "text": [
1904
+ "⏱️ elapsed=12:00 ⏳ remain=227:59 | 🔥 CPU= 11.3% 💾 RAM= 8.6% | 🧠 GPU0= 18.0% 🎮 VRAM0= 23.2%\n"
1905
+ ]
1906
+ },
1907
+ {
1908
+ "output_type": "stream",
1909
+ "name": "stderr",
1910
+ "text": [
1911
+ "100%|██████████| 300/300 [01:12<00:00, 4.16it/s, lr=0.0000, loss=0.135]\n"
1912
+ ]
1913
+ },
1914
+ {
1915
+ "output_type": "stream",
1916
+ "name": "stdout",
1917
+ "text": [
1918
+ ">> final loss = 0.13503803312778473\n"
1919
+ ]
1920
+ },
1921
+ {
1922
+ "output_type": "stream",
1923
+ "name": "stderr",
1924
+ "text": [
1925
+ " 97%|█████████▋| 290/300 [01:54<00:03, 2.53it/s, lr=0.0000, loss=0.573]"
1926
+ ]
1927
+ },
1928
+ {
1929
+ "output_type": "stream",
1930
+ "name": "stdout",
1931
+ "text": [
1932
+ "⏱️ elapsed=15:00 ⏳ remain=224:59 | 🔥 CPU= 11.0% 💾 RAM= 8.7% | 🧠 GPU0= 25.0% 🎮 VRAM0= 24.5%\n"
1933
+ ]
1934
+ },
1935
+ {
1936
+ "output_type": "stream",
1937
+ "name": "stderr",
1938
+ "text": [
1939
+ "100%|██████████| 300/300 [01:58<00:00, 2.53it/s, lr=0.0000, loss=0.568]\n"
1940
+ ]
1941
+ },
1942
+ {
1943
+ "output_type": "stream",
1944
+ "name": "stdout",
1945
+ "text": [
1946
+ ">> final loss = 0.5675967931747437\n",
1947
+ "Final focals = [527.1656 542.53357 524.326 541.3448 517.9595 546.69037 515.5983\n",
1948
+ " 551.5943 514.54095 555.28784 513.928 556.96246 511.2091 556.24615\n",
1949
+ " 510.22964 554.66754 508.0994 556.95636 508.20773 554.1811 510.2956\n",
1950
+ " 552.1906 514.2344 548.94104 513.96497 549.1159 513.6511 553.3412\n",
1951
+ " 512.40155 555.99207 508.48114 560.3865 509.8687 559.085 509.86774\n",
1952
+ " 557.7523 512.30994 557.3793 507.42514 560.2667 507.77997 563.32434\n",
1953
+ " 509.42593 563.9998 516.51715 563.178 521.0214 562.3778 520.2069\n",
1954
+ " 567.1606 521.47626 564.6666 522.8941 562.8961 522.62036 560.45996\n",
1955
+ " 520.80084 561.34174 518.98224 562.2094 519.7321 562.429 519.5602\n",
1956
+ " 560.76685 516.54425 564.60767 516.94464 563.5815 519.1268 563.6148\n",
1957
+ " 519.5324 564.416 520.44116 568.58813 523.83795 569.6674 528.67975\n",
1958
+ " 568.74 531.5526 565.7716 ]\n",
1959
+ " ✓ sparse_global_alignment done\n",
1960
+ " Memory after alignment:\n",
1961
+ " GPU - Allocated: 2.67 GB, Reserved: 5.26 GB\n",
1962
+ " CPU - Usage: 8.7%\n"
1963
+ ]
1964
+ }
1965
+ ],
1966
+ "execution_count": 22
1967
+ },
1968
+ {
1969
+ "cell_type": "code",
1970
+ "source": [
1971
+ "# ---------- 3. COLMAP Conversion ----------\n",
1972
+ "convert_scene_to_colmap(\n",
1973
+ " scene,\n",
1974
+ " output_dir=COLMAP_DIR,\n",
1975
+ " processed_image_paths=image_paths,\n",
1976
+ " verbose=True,\n",
1977
+ ")"
1978
+ ],
1979
+ "metadata": {
1980
+ "papermill": {
1981
+ "duration": 12.082868,
1982
+ "end_time": "2026-03-26T13:00:53.831242",
1983
+ "exception": true,
1984
+ "start_time": "2026-03-26T13:00:41.748374",
1985
+ "status": "failed"
1986
+ },
1987
+ "tags": [],
1988
+ "trusted": true,
1989
+ "execution": {
1990
+ "iopub.status.busy": "2026-04-06T18:08:48.306539Z",
1991
+ "iopub.execute_input": "2026-04-06T18:08:48.307162Z",
1992
+ "iopub.status.idle": "2026-04-06T18:09:27.185975Z",
1993
+ "shell.execute_reply.started": "2026-04-06T18:08:48.307136Z",
1994
+ "shell.execute_reply": "2026-04-06T18:09:27.18532Z"
1995
+ },
1996
+ "id": "IZGowCelMlOe",
1997
+ "colab": {
1998
+ "base_uri": "https://localhost:8080/"
1999
+ },
2000
+ "outputId": "36f311a7-9c53-4597-f03f-c345c46b748e"
2001
+ },
2002
+ "outputs": [
2003
+ {
2004
+ "output_type": "stream",
2005
+ "name": "stdout",
2006
+ "text": [
2007
+ "\n",
2008
+ "============================================================\n",
2009
+ "Step 3: Converting to COLMAP format\n",
2010
+ "============================================================\n",
2011
+ " Output: /content/output/colmap\n",
2012
+ "\n",
2013
+ " Extracting scene data…\n",
2014
+ " Views: 80\n",
2015
+ " Extracting 3D points…\n",
2016
+ " [WARN] Could not parse masks, using all-True\n",
2017
+ " [DEBUG] pts_vn3 shape=(80, 196608, 3)\n",
2018
+ " [DEBUG] masks_vn shape=(80, 196608)\n",
2019
+ " ✓ Points: 5,000,000\n",
2020
+ " Summary: 80 cams, 80 imgs, 5,000,000 pts\n",
2021
+ " Saved 80 depth maps → /content/output/colmap/depth\n",
2022
+ " ✓ cameras.bin (80 cameras)\n",
2023
+ " ✓ images.bin (80 images)\n",
2024
+ " ✓ points3D.bin (5000000 points)\n",
2025
+ "✓ COLMAP conversion complete\n"
2026
+ ]
2027
+ },
2028
+ {
2029
+ "output_type": "execute_result",
2030
+ "data": {
2031
+ "text/plain": [
2032
+ "PosixPath('/content/output/colmap')"
2033
+ ]
2034
+ },
2035
+ "metadata": {},
2036
+ "execution_count": 23
2037
+ }
2038
+ ],
2039
+ "execution_count": 23
2040
+ },
2041
+ {
2042
+ "cell_type": "code",
2043
+ "source": [
2044
+ "!pip show numpy | grep Version:"
2045
+ ],
2046
+ "metadata": {
2047
+ "trusted": true,
2048
+ "execution": {
2049
+ "iopub.status.busy": "2026-04-06T18:09:27.187348Z",
2050
+ "iopub.execute_input": "2026-04-06T18:09:27.187593Z",
2051
+ "iopub.status.idle": "2026-04-06T18:09:29.428734Z",
2052
+ "shell.execute_reply.started": "2026-04-06T18:09:27.187571Z",
2053
+ "shell.execute_reply": "2026-04-06T18:09:29.427944Z"
2054
+ },
2055
+ "id": "ta-iXVWqMlOe",
2056
+ "colab": {
2057
+ "base_uri": "https://localhost:8080/"
2058
+ },
2059
+ "outputId": "9aefb16f-5c64-47b8-ed5a-bbf699f97ada"
2060
+ },
2061
+ "outputs": [
2062
+ {
2063
+ "output_type": "stream",
2064
+ "name": "stdout",
2065
+ "text": [
2066
+ "Version: 1.26.4\n"
2067
+ ]
2068
+ }
2069
+ ],
2070
+ "execution_count": 24
2071
+ },
2072
+ {
2073
+ "cell_type": "code",
2074
+ "source": [
2075
+ "# ---------- 4. PLY Output ----------\n",
2076
+ "sparse_dir = os.path.join(COLMAP_DIR, \"sparse\", \"0\")\n",
2077
+ "n = convert_colmap_to_ply(sparse_dir, PLY_PATH)\n",
2078
+ "\n",
2079
+ "# ---------- 5. Viewer ----------\n",
2080
+ "#if n > 0:\n",
2081
+ "# display_ply_viewer(PLY_PATH)\n",
2082
+ "\n",
2083
+ "print(\"\\n🎉 Pipeline complete!\")\n",
2084
+ "print(f\" PLY : {PLY_PATH}\")\n",
2085
+ "print(f\" COLMAP: {COLMAP_DIR}\")"
2086
+ ],
2087
+ "metadata": {
2088
+ "papermill": {
2089
+ "duration": null,
2090
+ "end_time": null,
2091
+ "exception": null,
2092
+ "start_time": null,
2093
+ "status": "pending"
2094
+ },
2095
+ "tags": [],
2096
+ "trusted": true,
2097
+ "execution": {
2098
+ "iopub.status.busy": "2026-04-06T18:09:29.430054Z",
2099
+ "iopub.execute_input": "2026-04-06T18:09:29.430304Z",
2100
+ "iopub.status.idle": "2026-04-06T18:10:07.796696Z",
2101
+ "shell.execute_reply.started": "2026-04-06T18:09:29.430279Z",
2102
+ "shell.execute_reply": "2026-04-06T18:10:07.795818Z"
2103
+ },
2104
+ "id": "8umJBHXbMlOe",
2105
+ "colab": {
2106
+ "base_uri": "https://localhost:8080/"
2107
+ },
2108
+ "outputId": "5ccfd0be-75e9-48a9-fa1f-c831873fbaa0"
2109
+ },
2110
+ "outputs": [
2111
+ {
2112
+ "output_type": "stream",
2113
+ "name": "stdout",
2114
+ "text": [
2115
+ "\n",
2116
+ "============================================================\n",
2117
+ "Step 4: COLMAP bin → PLY\n",
2118
+ "============================================================\n",
2119
+ " Cameras: 80\n",
2120
+ " Images: 80\n",
2121
+ " Points: 5000000\n",
2122
+ " X: [-36.452, 7.695]\n",
2123
+ " Y: [-31.787, 10.960]\n",
2124
+ " Z: [-20.766, 17.420]\n",
2125
+ " ✓ PLY saved → /content/output/colmap/point_cloud.ply\n",
2126
+ "\n",
2127
+ "🎉 Pipeline complete!\n",
2128
+ " PLY : /content/output/colmap/point_cloud.ply\n",
2129
+ " COLMAP: /content/output/colmap\n"
2130
+ ]
2131
+ }
2132
+ ],
2133
+ "execution_count": 25
2134
+ },
2135
+ {
2136
+ "cell_type": "code",
2137
+ "source": [
2138
+ "logger.stop()"
2139
+ ],
2140
+ "metadata": {
2141
+ "papermill": {
2142
+ "duration": null,
2143
+ "end_time": null,
2144
+ "exception": null,
2145
+ "start_time": null,
2146
+ "status": "pending"
2147
+ },
2148
+ "tags": [],
2149
+ "trusted": true,
2150
+ "execution": {
2151
+ "iopub.status.busy": "2026-04-06T18:10:07.797817Z",
2152
+ "iopub.execute_input": "2026-04-06T18:10:07.798233Z",
2153
+ "iopub.status.idle": "2026-04-06T18:10:07.801876Z",
2154
+ "shell.execute_reply.started": "2026-04-06T18:10:07.798198Z",
2155
+ "shell.execute_reply": "2026-04-06T18:10:07.801161Z"
2156
+ },
2157
+ "id": "j88mY_ZNMlOe"
2158
+ },
2159
+ "outputs": [],
2160
+ "execution_count": 26
2161
+ }
2162
+ ]
2163
+ }