Datasets:

Modalities:
Image
Text
License:
thenguyentrong commited on
Commit
91fd92a
·
1 Parent(s): 18a97c4

Add example notebooks, scripts, and demo videos

Browse files
.gitattributes CHANGED
@@ -57,3 +57,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
57
  # Video files - compressed
58
  *.mp4 filter=lfs diff=lfs merge=lfs -text
59
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
57
  # Video files - compressed
58
  *.mp4 filter=lfs diff=lfs merge=lfs -text
59
  *.webm filter=lfs diff=lfs merge=lfs -text
60
+ *.ipynb filter=lfs diff=lfs merge=lfs -text
examples/Example_3DPE_Crack22_YOLOv11.ipynb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7ee27b7a76933490f2c8f9ac23924b83f94d76394c9a94372acb2bb88e60d5bd
3
+ size 73902371
examples/Hyperparameters.ipynb ADDED
@@ -0,0 +1,1030 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {
6
+ "id": "ishDL4poP5AP"
7
+ },
8
+ "source": [
9
+ "## Step 1: Install deps"
10
+ ]
11
+ },
12
+ {
13
+ "cell_type": "code",
14
+ "execution_count": 1,
15
+ "metadata": {
16
+ "colab": {
17
+ "base_uri": "https://localhost:8080/"
18
+ },
19
+ "id": "zr9bvajZ1eHV",
20
+ "outputId": "e546b5a3-13a1-43e2-ad98-e92bc2163991"
21
+ },
22
+ "outputs": [
23
+ {
24
+ "name": "stdout",
25
+ "output_type": "stream",
26
+ "text": [
27
+ "\u001b[?25l \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m0.0/1.2 MB\u001b[0m \u001b[31m?\u001b[0m eta \u001b[36m-:--:--\u001b[0m\r\u001b[2K \u001b[91m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m\u001b[91m╸\u001b[0m \u001b[32m1.2/1.2 MB\u001b[0m \u001b[31m44.8 MB/s\u001b[0m eta \u001b[36m0:00:01\u001b[0m\r\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m1.2/1.2 MB\u001b[0m \u001b[31m19.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
28
+ "\u001b[?25h\u001b[?25l \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m0.0/94.0 kB\u001b[0m \u001b[31m?\u001b[0m eta \u001b[36m-:--:--\u001b[0m\r\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m94.0/94.0 kB\u001b[0m \u001b[31m6.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
29
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m66.8/66.8 kB\u001b[0m \u001b[31m3.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
30
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m49.9/49.9 MB\u001b[0m \u001b[31m17.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
31
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m1.5/1.5 MB\u001b[0m \u001b[31m59.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
32
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m5.5/5.5 MB\u001b[0m \u001b[31m137.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
33
+ "\u001b[?25h"
34
+ ]
35
+ }
36
+ ],
37
+ "source": [
38
+ "!pip install --quiet ultralytics pyyaml pandas roboflow\n"
39
+ ]
40
+ },
41
+ {
42
+ "cell_type": "markdown",
43
+ "metadata": {
44
+ "id": "-W6ZMnt7P88e"
45
+ },
46
+ "source": [
47
+ "## Step 2: Download dataset"
48
+ ]
49
+ },
50
+ {
51
+ "cell_type": "code",
52
+ "execution_count": null,
53
+ "metadata": {
54
+ "colab": {
55
+ "base_uri": "https://localhost:8080/"
56
+ },
57
+ "id": "ZahCnJzk3xXe",
58
+ "outputId": "f79309c7-58cb-4305-a95d-da998015c25f"
59
+ },
60
+ "outputs": [
61
+ {
62
+ "name": "stdout",
63
+ "output_type": "stream",
64
+ "text": [
65
+ "loading Roboflow workspace...\n",
66
+ "loading Roboflow project...\n"
67
+ ]
68
+ },
69
+ {
70
+ "name": "stderr",
71
+ "output_type": "stream",
72
+ "text": [
73
+ "Downloading Dataset Version Zip in Clay-Crack-Detection-14 to yolov11:: 100%|██████████| 359480/359480 [00:05<00:00, 61260.38it/s]"
74
+ ]
75
+ },
76
+ {
77
+ "name": "stdout",
78
+ "output_type": "stream",
79
+ "text": [
80
+ "\n"
81
+ ]
82
+ },
83
+ {
84
+ "name": "stderr",
85
+ "output_type": "stream",
86
+ "text": [
87
+ "\n",
88
+ "Extracting Dataset Version Zip to Clay-Crack-Detection-14 in yolov11:: 100%|██████████| 15197/15197 [00:04<00:00, 3417.33it/s]\n"
89
+ ]
90
+ },
91
+ {
92
+ "name": "stdout",
93
+ "output_type": "stream",
94
+ "text": [
95
+ "Dataset at: /content/Clay-Crack-Detection-14\n"
96
+ ]
97
+ }
98
+ ],
99
+ "source": [
100
+ "from roboflow import Roboflow\n",
101
+ "rf = Roboflow(api_key=\"ROBOFLOW_API_KEY\") # avoid sharing this key publicly\n",
102
+ "project = rf.workspace(\"tv-vloon\").project(\"clay-crack-detection\")\n",
103
+ "version = project.version(14)\n",
104
+ "dataset = version.download(\"yolov11\")\n",
105
+ "\n",
106
+ "DATA_DIR = dataset.location # path with data.yaml and roboflow README\n",
107
+ "print(\"Dataset at:\", DATA_DIR)\n"
108
+ ]
109
+ },
110
+ {
111
+ "cell_type": "markdown",
112
+ "metadata": {
113
+ "id": "bwCdXcuKQFOF"
114
+ },
115
+ "source": [
116
+ "## Step 3: Upload weight"
117
+ ]
118
+ },
119
+ {
120
+ "cell_type": "code",
121
+ "execution_count": 4,
122
+ "metadata": {
123
+ "colab": {
124
+ "base_uri": "https://localhost:8080/",
125
+ "height": 90
126
+ },
127
+ "id": "UW3gBrxG339j",
128
+ "outputId": "8089f8a5-15bd-4237-f8fa-f953f2f0c054"
129
+ },
130
+ "outputs": [
131
+ {
132
+ "name": "stdout",
133
+ "output_type": "stream",
134
+ "text": [
135
+ "Upload: best.pt (or last.pt). Optional: args.yaml, hyp.yaml, training.json, or a runs/ zip.\n"
136
+ ]
137
+ },
138
+ {
139
+ "data": {
140
+ "text/html": [
141
+ "\n",
142
+ " <input type=\"file\" id=\"files-13779d1c-4da1-4162-ab3b-283d8da77c70\" name=\"files[]\" multiple disabled\n",
143
+ " style=\"border:none\" />\n",
144
+ " <output id=\"result-13779d1c-4da1-4162-ab3b-283d8da77c70\">\n",
145
+ " Upload widget is only available when the cell has been executed in the\n",
146
+ " current browser session. Please rerun this cell to enable.\n",
147
+ " </output>\n",
148
+ " <script>// Copyright 2017 Google LLC\n",
149
+ "//\n",
150
+ "// Licensed under the Apache License, Version 2.0 (the \"License\");\n",
151
+ "// you may not use this file except in compliance with the License.\n",
152
+ "// You may obtain a copy of the License at\n",
153
+ "//\n",
154
+ "// http://www.apache.org/licenses/LICENSE-2.0\n",
155
+ "//\n",
156
+ "// Unless required by applicable law or agreed to in writing, software\n",
157
+ "// distributed under the License is distributed on an \"AS IS\" BASIS,\n",
158
+ "// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
159
+ "// See the License for the specific language governing permissions and\n",
160
+ "// limitations under the License.\n",
161
+ "\n",
162
+ "/**\n",
163
+ " * @fileoverview Helpers for google.colab Python module.\n",
164
+ " */\n",
165
+ "(function(scope) {\n",
166
+ "function span(text, styleAttributes = {}) {\n",
167
+ " const element = document.createElement('span');\n",
168
+ " element.textContent = text;\n",
169
+ " for (const key of Object.keys(styleAttributes)) {\n",
170
+ " element.style[key] = styleAttributes[key];\n",
171
+ " }\n",
172
+ " return element;\n",
173
+ "}\n",
174
+ "\n",
175
+ "// Max number of bytes which will be uploaded at a time.\n",
176
+ "const MAX_PAYLOAD_SIZE = 100 * 1024;\n",
177
+ "\n",
178
+ "function _uploadFiles(inputId, outputId) {\n",
179
+ " const steps = uploadFilesStep(inputId, outputId);\n",
180
+ " const outputElement = document.getElementById(outputId);\n",
181
+ " // Cache steps on the outputElement to make it available for the next call\n",
182
+ " // to uploadFilesContinue from Python.\n",
183
+ " outputElement.steps = steps;\n",
184
+ "\n",
185
+ " return _uploadFilesContinue(outputId);\n",
186
+ "}\n",
187
+ "\n",
188
+ "// This is roughly an async generator (not supported in the browser yet),\n",
189
+ "// where there are multiple asynchronous steps and the Python side is going\n",
190
+ "// to poll for completion of each step.\n",
191
+ "// This uses a Promise to block the python side on completion of each step,\n",
192
+ "// then passes the result of the previous step as the input to the next step.\n",
193
+ "function _uploadFilesContinue(outputId) {\n",
194
+ " const outputElement = document.getElementById(outputId);\n",
195
+ " const steps = outputElement.steps;\n",
196
+ "\n",
197
+ " const next = steps.next(outputElement.lastPromiseValue);\n",
198
+ " return Promise.resolve(next.value.promise).then((value) => {\n",
199
+ " // Cache the last promise value to make it available to the next\n",
200
+ " // step of the generator.\n",
201
+ " outputElement.lastPromiseValue = value;\n",
202
+ " return next.value.response;\n",
203
+ " });\n",
204
+ "}\n",
205
+ "\n",
206
+ "/**\n",
207
+ " * Generator function which is called between each async step of the upload\n",
208
+ " * process.\n",
209
+ " * @param {string} inputId Element ID of the input file picker element.\n",
210
+ " * @param {string} outputId Element ID of the output display.\n",
211
+ " * @return {!Iterable<!Object>} Iterable of next steps.\n",
212
+ " */\n",
213
+ "function* uploadFilesStep(inputId, outputId) {\n",
214
+ " const inputElement = document.getElementById(inputId);\n",
215
+ " inputElement.disabled = false;\n",
216
+ "\n",
217
+ " const outputElement = document.getElementById(outputId);\n",
218
+ " outputElement.innerHTML = '';\n",
219
+ "\n",
220
+ " const pickedPromise = new Promise((resolve) => {\n",
221
+ " inputElement.addEventListener('change', (e) => {\n",
222
+ " resolve(e.target.files);\n",
223
+ " });\n",
224
+ " });\n",
225
+ "\n",
226
+ " const cancel = document.createElement('button');\n",
227
+ " inputElement.parentElement.appendChild(cancel);\n",
228
+ " cancel.textContent = 'Cancel upload';\n",
229
+ " const cancelPromise = new Promise((resolve) => {\n",
230
+ " cancel.onclick = () => {\n",
231
+ " resolve(null);\n",
232
+ " };\n",
233
+ " });\n",
234
+ "\n",
235
+ " // Wait for the user to pick the files.\n",
236
+ " const files = yield {\n",
237
+ " promise: Promise.race([pickedPromise, cancelPromise]),\n",
238
+ " response: {\n",
239
+ " action: 'starting',\n",
240
+ " }\n",
241
+ " };\n",
242
+ "\n",
243
+ " cancel.remove();\n",
244
+ "\n",
245
+ " // Disable the input element since further picks are not allowed.\n",
246
+ " inputElement.disabled = true;\n",
247
+ "\n",
248
+ " if (!files) {\n",
249
+ " return {\n",
250
+ " response: {\n",
251
+ " action: 'complete',\n",
252
+ " }\n",
253
+ " };\n",
254
+ " }\n",
255
+ "\n",
256
+ " for (const file of files) {\n",
257
+ " const li = document.createElement('li');\n",
258
+ " li.append(span(file.name, {fontWeight: 'bold'}));\n",
259
+ " li.append(span(\n",
260
+ " `(${file.type || 'n/a'}) - ${file.size} bytes, ` +\n",
261
+ " `last modified: ${\n",
262
+ " file.lastModifiedDate ? file.lastModifiedDate.toLocaleDateString() :\n",
263
+ " 'n/a'} - `));\n",
264
+ " const percent = span('0% done');\n",
265
+ " li.appendChild(percent);\n",
266
+ "\n",
267
+ " outputElement.appendChild(li);\n",
268
+ "\n",
269
+ " const fileDataPromise = new Promise((resolve) => {\n",
270
+ " const reader = new FileReader();\n",
271
+ " reader.onload = (e) => {\n",
272
+ " resolve(e.target.result);\n",
273
+ " };\n",
274
+ " reader.readAsArrayBuffer(file);\n",
275
+ " });\n",
276
+ " // Wait for the data to be ready.\n",
277
+ " let fileData = yield {\n",
278
+ " promise: fileDataPromise,\n",
279
+ " response: {\n",
280
+ " action: 'continue',\n",
281
+ " }\n",
282
+ " };\n",
283
+ "\n",
284
+ " // Use a chunked sending to avoid message size limits. See b/62115660.\n",
285
+ " let position = 0;\n",
286
+ " do {\n",
287
+ " const length = Math.min(fileData.byteLength - position, MAX_PAYLOAD_SIZE);\n",
288
+ " const chunk = new Uint8Array(fileData, position, length);\n",
289
+ " position += length;\n",
290
+ "\n",
291
+ " const base64 = btoa(String.fromCharCode.apply(null, chunk));\n",
292
+ " yield {\n",
293
+ " response: {\n",
294
+ " action: 'append',\n",
295
+ " file: file.name,\n",
296
+ " data: base64,\n",
297
+ " },\n",
298
+ " };\n",
299
+ "\n",
300
+ " let percentDone = fileData.byteLength === 0 ?\n",
301
+ " 100 :\n",
302
+ " Math.round((position / fileData.byteLength) * 100);\n",
303
+ " percent.textContent = `${percentDone}% done`;\n",
304
+ "\n",
305
+ " } while (position < fileData.byteLength);\n",
306
+ " }\n",
307
+ "\n",
308
+ " // All done.\n",
309
+ " yield {\n",
310
+ " response: {\n",
311
+ " action: 'complete',\n",
312
+ " }\n",
313
+ " };\n",
314
+ "}\n",
315
+ "\n",
316
+ "scope.google = scope.google || {};\n",
317
+ "scope.google.colab = scope.google.colab || {};\n",
318
+ "scope.google.colab._files = {\n",
319
+ " _uploadFiles,\n",
320
+ " _uploadFilesContinue,\n",
321
+ "};\n",
322
+ "})(self);\n",
323
+ "</script> "
324
+ ],
325
+ "text/plain": [
326
+ "<IPython.core.display.HTML object>"
327
+ ]
328
+ },
329
+ "metadata": {},
330
+ "output_type": "display_data"
331
+ },
332
+ {
333
+ "name": "stdout",
334
+ "output_type": "stream",
335
+ "text": [
336
+ "Saving crack-seg.pt to crack-seg.pt\n"
337
+ ]
338
+ }
339
+ ],
340
+ "source": [
341
+ "from google.colab import files\n",
342
+ "print(\"Upload: best.pt (or last.pt). Optional: args.yaml, hyp.yaml, training.json, or a runs/ zip.\")\n",
343
+ "uploaded = files.upload()\n"
344
+ ]
345
+ },
346
+ {
347
+ "cell_type": "markdown",
348
+ "metadata": {
349
+ "id": "tOYh9EudQLt5"
350
+ },
351
+ "source": [
352
+ "## Step 4: Parse & merge hyperparameters into a clean table + downloads"
353
+ ]
354
+ },
355
+ {
356
+ "cell_type": "code",
357
+ "execution_count": 5,
358
+ "metadata": {
359
+ "colab": {
360
+ "base_uri": "https://localhost:8080/",
361
+ "height": 1000
362
+ },
363
+ "id": "0g_b1GuC36Rc",
364
+ "outputId": "febc99ae-4c02-41f7-81f1-500b9619e986"
365
+ },
366
+ "outputs": [
367
+ {
368
+ "name": "stdout",
369
+ "output_type": "stream",
370
+ "text": [
371
+ "Creating new Ultralytics Settings v0.0.6 file ✅ \n",
372
+ "View Ultralytics Settings with 'yolo settings' or at '/root/.config/Ultralytics/settings.json'\n",
373
+ "Update Settings with 'yolo settings key=value', i.e. 'yolo settings runs_dir=path/to/dir'. For help see https://docs.ultralytics.com/quickstart/#ultralytics-settings.\n",
374
+ "✅ Sources: dataset:README.roboflow.txt, dataset:data.yaml, crack-seg.pt:train_args, crack-seg.pt:model.args\n",
375
+ "✅ Total keys: 111 | Primary shown: 33\n"
376
+ ]
377
+ },
378
+ {
379
+ "data": {
380
+ "application/vnd.google.colaboratory.intrinsic+json": {
381
+ "summary": "{\n \"name\": \"df\",\n \"rows\": 33,\n \"fields\": [\n {\n \"column\": \"parameter\",\n \"properties\": {\n \"dtype\": \"string\",\n \"num_unique_values\": 33,\n \"samples\": [\n \"train.optimizer\",\n \"data.test\",\n \"lr.warmup_momentum\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"value\",\n \"properties\": {\n \"dtype\": \"object\",\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}",
382
+ "type": "dataframe",
383
+ "variable_name": "df"
384
+ },
385
+ "text/html": [
386
+ "\n",
387
+ " <div id=\"df-723fce6a-37d1-4818-b483-a84434f982e8\" class=\"colab-df-container\">\n",
388
+ " <div>\n",
389
+ "<style scoped>\n",
390
+ " .dataframe tbody tr th:only-of-type {\n",
391
+ " vertical-align: middle;\n",
392
+ " }\n",
393
+ "\n",
394
+ " .dataframe tbody tr th {\n",
395
+ " vertical-align: top;\n",
396
+ " }\n",
397
+ "\n",
398
+ " .dataframe thead th {\n",
399
+ " text-align: right;\n",
400
+ " }\n",
401
+ "</style>\n",
402
+ "<table border=\"1\" class=\"dataframe\">\n",
403
+ " <thead>\n",
404
+ " <tr style=\"text-align: right;\">\n",
405
+ " <th></th>\n",
406
+ " <th>parameter</th>\n",
407
+ " <th>value</th>\n",
408
+ " </tr>\n",
409
+ " </thead>\n",
410
+ " <tbody>\n",
411
+ " <tr>\n",
412
+ " <th>0</th>\n",
413
+ " <td>aug.copy_paste</td>\n",
414
+ " <td>0.0</td>\n",
415
+ " </tr>\n",
416
+ " <tr>\n",
417
+ " <th>1</th>\n",
418
+ " <td>aug.degrees</td>\n",
419
+ " <td>0.0</td>\n",
420
+ " </tr>\n",
421
+ " <tr>\n",
422
+ " <th>2</th>\n",
423
+ " <td>aug.erasing</td>\n",
424
+ " <td>0.4</td>\n",
425
+ " </tr>\n",
426
+ " <tr>\n",
427
+ " <th>3</th>\n",
428
+ " <td>aug.fliplr</td>\n",
429
+ " <td>0.0</td>\n",
430
+ " </tr>\n",
431
+ " <tr>\n",
432
+ " <th>4</th>\n",
433
+ " <td>aug.flipud</td>\n",
434
+ " <td>0.0</td>\n",
435
+ " </tr>\n",
436
+ " <tr>\n",
437
+ " <th>5</th>\n",
438
+ " <td>aug.hsv_h</td>\n",
439
+ " <td>0.0</td>\n",
440
+ " </tr>\n",
441
+ " <tr>\n",
442
+ " <th>6</th>\n",
443
+ " <td>aug.hsv_s</td>\n",
444
+ " <td>0.0</td>\n",
445
+ " </tr>\n",
446
+ " <tr>\n",
447
+ " <th>7</th>\n",
448
+ " <td>aug.hsv_v</td>\n",
449
+ " <td>0.0</td>\n",
450
+ " </tr>\n",
451
+ " <tr>\n",
452
+ " <th>8</th>\n",
453
+ " <td>aug.mixup</td>\n",
454
+ " <td>0.0</td>\n",
455
+ " </tr>\n",
456
+ " <tr>\n",
457
+ " <th>9</th>\n",
458
+ " <td>aug.mosaic</td>\n",
459
+ " <td>0.0</td>\n",
460
+ " </tr>\n",
461
+ " <tr>\n",
462
+ " <th>10</th>\n",
463
+ " <td>aug.perspective</td>\n",
464
+ " <td>0.0</td>\n",
465
+ " </tr>\n",
466
+ " <tr>\n",
467
+ " <th>11</th>\n",
468
+ " <td>aug.scale</td>\n",
469
+ " <td>0.0</td>\n",
470
+ " </tr>\n",
471
+ " <tr>\n",
472
+ " <th>12</th>\n",
473
+ " <td>aug.shear</td>\n",
474
+ " <td>0.0</td>\n",
475
+ " </tr>\n",
476
+ " <tr>\n",
477
+ " <th>13</th>\n",
478
+ " <td>aug.translate</td>\n",
479
+ " <td>0.0</td>\n",
480
+ " </tr>\n",
481
+ " <tr>\n",
482
+ " <th>14</th>\n",
483
+ " <td>data.names</td>\n",
484
+ " <td>[crack_b, crack_s, crack_shadow]</td>\n",
485
+ " </tr>\n",
486
+ " <tr>\n",
487
+ " <th>15</th>\n",
488
+ " <td>data.test</td>\n",
489
+ " <td>../test/images</td>\n",
490
+ " </tr>\n",
491
+ " <tr>\n",
492
+ " <th>16</th>\n",
493
+ " <td>data.train</td>\n",
494
+ " <td>../train/images</td>\n",
495
+ " </tr>\n",
496
+ " <tr>\n",
497
+ " <th>17</th>\n",
498
+ " <td>data.val</td>\n",
499
+ " <td>../valid/images</td>\n",
500
+ " </tr>\n",
501
+ " <tr>\n",
502
+ " <th>18</th>\n",
503
+ " <td>env.device</td>\n",
504
+ " <td>None</td>\n",
505
+ " </tr>\n",
506
+ " <tr>\n",
507
+ " <th>19</th>\n",
508
+ " <td>env.seed</td>\n",
509
+ " <td>0</td>\n",
510
+ " </tr>\n",
511
+ " <tr>\n",
512
+ " <th>20</th>\n",
513
+ " <td>env.workers</td>\n",
514
+ " <td>1</td>\n",
515
+ " </tr>\n",
516
+ " <tr>\n",
517
+ " <th>21</th>\n",
518
+ " <td>lr.lr0</td>\n",
519
+ " <td>0.01</td>\n",
520
+ " </tr>\n",
521
+ " <tr>\n",
522
+ " <th>22</th>\n",
523
+ " <td>lr.lrf</td>\n",
524
+ " <td>0.01</td>\n",
525
+ " </tr>\n",
526
+ " <tr>\n",
527
+ " <th>23</th>\n",
528
+ " <td>lr.momentum</td>\n",
529
+ " <td>0.937</td>\n",
530
+ " </tr>\n",
531
+ " <tr>\n",
532
+ " <th>24</th>\n",
533
+ " <td>lr.warmup_bias_lr</td>\n",
534
+ " <td>0.0</td>\n",
535
+ " </tr>\n",
536
+ " <tr>\n",
537
+ " <th>25</th>\n",
538
+ " <td>lr.warmup_epochs</td>\n",
539
+ " <td>3.0</td>\n",
540
+ " </tr>\n",
541
+ " <tr>\n",
542
+ " <th>26</th>\n",
543
+ " <td>lr.warmup_momentum</td>\n",
544
+ " <td>0.8</td>\n",
545
+ " </tr>\n",
546
+ " <tr>\n",
547
+ " <th>27</th>\n",
548
+ " <td>lr.weight_decay</td>\n",
549
+ " <td>0.0005</td>\n",
550
+ " </tr>\n",
551
+ " <tr>\n",
552
+ " <th>28</th>\n",
553
+ " <td>train.batch</td>\n",
554
+ " <td>14</td>\n",
555
+ " </tr>\n",
556
+ " <tr>\n",
557
+ " <th>29</th>\n",
558
+ " <td>train.epochs</td>\n",
559
+ " <td>300</td>\n",
560
+ " </tr>\n",
561
+ " <tr>\n",
562
+ " <th>30</th>\n",
563
+ " <td>train.imgsz</td>\n",
564
+ " <td>640</td>\n",
565
+ " </tr>\n",
566
+ " <tr>\n",
567
+ " <th>31</th>\n",
568
+ " <td>train.optimizer</td>\n",
569
+ " <td>auto</td>\n",
570
+ " </tr>\n",
571
+ " <tr>\n",
572
+ " <th>32</th>\n",
573
+ " <td>train.patience</td>\n",
574
+ " <td>10</td>\n",
575
+ " </tr>\n",
576
+ " </tbody>\n",
577
+ "</table>\n",
578
+ "</div>\n",
579
+ " <div class=\"colab-df-buttons\">\n",
580
+ "\n",
581
+ " <div class=\"colab-df-container\">\n",
582
+ " <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-723fce6a-37d1-4818-b483-a84434f982e8')\"\n",
583
+ " title=\"Convert this dataframe to an interactive table.\"\n",
584
+ " style=\"display:none;\">\n",
585
+ "\n",
586
+ " <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
587
+ " <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
588
+ " </svg>\n",
589
+ " </button>\n",
590
+ "\n",
591
+ " <style>\n",
592
+ " .colab-df-container {\n",
593
+ " display:flex;\n",
594
+ " gap: 12px;\n",
595
+ " }\n",
596
+ "\n",
597
+ " .colab-df-convert {\n",
598
+ " background-color: #E8F0FE;\n",
599
+ " border: none;\n",
600
+ " border-radius: 50%;\n",
601
+ " cursor: pointer;\n",
602
+ " display: none;\n",
603
+ " fill: #1967D2;\n",
604
+ " height: 32px;\n",
605
+ " padding: 0 0 0 0;\n",
606
+ " width: 32px;\n",
607
+ " }\n",
608
+ "\n",
609
+ " .colab-df-convert:hover {\n",
610
+ " background-color: #E2EBFA;\n",
611
+ " box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
612
+ " fill: #174EA6;\n",
613
+ " }\n",
614
+ "\n",
615
+ " .colab-df-buttons div {\n",
616
+ " margin-bottom: 4px;\n",
617
+ " }\n",
618
+ "\n",
619
+ " [theme=dark] .colab-df-convert {\n",
620
+ " background-color: #3B4455;\n",
621
+ " fill: #D2E3FC;\n",
622
+ " }\n",
623
+ "\n",
624
+ " [theme=dark] .colab-df-convert:hover {\n",
625
+ " background-color: #434B5C;\n",
626
+ " box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
627
+ " filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
628
+ " fill: #FFFFFF;\n",
629
+ " }\n",
630
+ " </style>\n",
631
+ "\n",
632
+ " <script>\n",
633
+ " const buttonEl =\n",
634
+ " document.querySelector('#df-723fce6a-37d1-4818-b483-a84434f982e8 button.colab-df-convert');\n",
635
+ " buttonEl.style.display =\n",
636
+ " google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
637
+ "\n",
638
+ " async function convertToInteractive(key) {\n",
639
+ " const element = document.querySelector('#df-723fce6a-37d1-4818-b483-a84434f982e8');\n",
640
+ " const dataTable =\n",
641
+ " await google.colab.kernel.invokeFunction('convertToInteractive',\n",
642
+ " [key], {});\n",
643
+ " if (!dataTable) return;\n",
644
+ "\n",
645
+ " const docLinkHtml = 'Like what you see? Visit the ' +\n",
646
+ " '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
647
+ " + ' to learn more about interactive tables.';\n",
648
+ " element.innerHTML = '';\n",
649
+ " dataTable['output_type'] = 'display_data';\n",
650
+ " await google.colab.output.renderOutput(dataTable, element);\n",
651
+ " const docLink = document.createElement('div');\n",
652
+ " docLink.innerHTML = docLinkHtml;\n",
653
+ " element.appendChild(docLink);\n",
654
+ " }\n",
655
+ " </script>\n",
656
+ " </div>\n",
657
+ "\n",
658
+ "\n",
659
+ " <div id=\"id_3aaba703-05cc-4db8-9426-ae24fc534ac4\">\n",
660
+ " <style>\n",
661
+ " .colab-df-generate {\n",
662
+ " background-color: #E8F0FE;\n",
663
+ " border: none;\n",
664
+ " border-radius: 50%;\n",
665
+ " cursor: pointer;\n",
666
+ " display: none;\n",
667
+ " fill: #1967D2;\n",
668
+ " height: 32px;\n",
669
+ " padding: 0 0 0 0;\n",
670
+ " width: 32px;\n",
671
+ " }\n",
672
+ "\n",
673
+ " .colab-df-generate:hover {\n",
674
+ " background-color: #E2EBFA;\n",
675
+ " box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
676
+ " fill: #174EA6;\n",
677
+ " }\n",
678
+ "\n",
679
+ " [theme=dark] .colab-df-generate {\n",
680
+ " background-color: #3B4455;\n",
681
+ " fill: #D2E3FC;\n",
682
+ " }\n",
683
+ "\n",
684
+ " [theme=dark] .colab-df-generate:hover {\n",
685
+ " background-color: #434B5C;\n",
686
+ " box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
687
+ " filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
688
+ " fill: #FFFFFF;\n",
689
+ " }\n",
690
+ " </style>\n",
691
+ " <button class=\"colab-df-generate\" onclick=\"generateWithVariable('df')\"\n",
692
+ " title=\"Generate code using this dataframe.\"\n",
693
+ " style=\"display:none;\">\n",
694
+ "\n",
695
+ " <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\"viewBox=\"0 0 24 24\"\n",
696
+ " width=\"24px\">\n",
697
+ " <path d=\"M7,19H8.4L18.45,9,17,7.55,7,17.6ZM5,21V16.75L18.45,3.32a2,2,0,0,1,2.83,0l1.4,1.43a1.91,1.91,0,0,1,.58,1.4,1.91,1.91,0,0,1-.58,1.4L9.25,21ZM18.45,9,17,7.55Zm-12,3A5.31,5.31,0,0,0,4.9,8.1,5.31,5.31,0,0,0,1,6.5,5.31,5.31,0,0,0,4.9,4.9,5.31,5.31,0,0,0,6.5,1,5.31,5.31,0,0,0,8.1,4.9,5.31,5.31,0,0,0,12,6.5,5.46,5.46,0,0,0,6.5,12Z\"/>\n",
698
+ " </svg>\n",
699
+ " </button>\n",
700
+ " <script>\n",
701
+ " (() => {\n",
702
+ " const buttonEl =\n",
703
+ " document.querySelector('#id_3aaba703-05cc-4db8-9426-ae24fc534ac4 button.colab-df-generate');\n",
704
+ " buttonEl.style.display =\n",
705
+ " google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
706
+ "\n",
707
+ " buttonEl.onclick = () => {\n",
708
+ " google.colab.notebook.generateWithVariable('df');\n",
709
+ " }\n",
710
+ " })();\n",
711
+ " </script>\n",
712
+ " </div>\n",
713
+ "\n",
714
+ " </div>\n",
715
+ " </div>\n"
716
+ ],
717
+ "text/plain": [
718
+ " parameter value\n",
719
+ "0 aug.copy_paste 0.0\n",
720
+ "1 aug.degrees 0.0\n",
721
+ "2 aug.erasing 0.4\n",
722
+ "3 aug.fliplr 0.0\n",
723
+ "4 aug.flipud 0.0\n",
724
+ "5 aug.hsv_h 0.0\n",
725
+ "6 aug.hsv_s 0.0\n",
726
+ "7 aug.hsv_v 0.0\n",
727
+ "8 aug.mixup 0.0\n",
728
+ "9 aug.mosaic 0.0\n",
729
+ "10 aug.perspective 0.0\n",
730
+ "11 aug.scale 0.0\n",
731
+ "12 aug.shear 0.0\n",
732
+ "13 aug.translate 0.0\n",
733
+ "14 data.names [crack_b, crack_s, crack_shadow]\n",
734
+ "15 data.test ../test/images\n",
735
+ "16 data.train ../train/images\n",
736
+ "17 data.val ../valid/images\n",
737
+ "18 env.device None\n",
738
+ "19 env.seed 0\n",
739
+ "20 env.workers 1\n",
740
+ "21 lr.lr0 0.01\n",
741
+ "22 lr.lrf 0.01\n",
742
+ "23 lr.momentum 0.937\n",
743
+ "24 lr.warmup_bias_lr 0.0\n",
744
+ "25 lr.warmup_epochs 3.0\n",
745
+ "26 lr.warmup_momentum 0.8\n",
746
+ "27 lr.weight_decay 0.0005\n",
747
+ "28 train.batch 14\n",
748
+ "29 train.epochs 300\n",
749
+ "30 train.imgsz 640\n",
750
+ "31 train.optimizer auto\n",
751
+ "32 train.patience 10"
752
+ ]
753
+ },
754
+ "execution_count": 5,
755
+ "metadata": {},
756
+ "output_type": "execute_result"
757
+ }
758
+ ],
759
+ "source": [
760
+ "import io, os, zipfile, json, yaml, pandas as pd\n",
761
+ "from ultralytics import YOLO\n",
762
+ "\n",
763
+ "workdir = \"/content/hparam_scan\"\n",
764
+ "os.makedirs(workdir, exist_ok=True)\n",
765
+ "\n",
766
+ "def try_read_yaml_bytes(b):\n",
767
+ " try: return yaml.safe_load(b.decode(\"utf-8\"))\n",
768
+ " except Exception:\n",
769
+ " try: return yaml.safe_load(b)\n",
770
+ " except Exception: return None\n",
771
+ "\n",
772
+ "def flatten(d, parent=\"\"):\n",
773
+ " out = {}\n",
774
+ " if isinstance(d, dict):\n",
775
+ " for k, v in d.items():\n",
776
+ " key = f\"{parent}.{k}\" if parent else str(k)\n",
777
+ " if isinstance(v, dict):\n",
778
+ " out.update(flatten(v, key))\n",
779
+ " else:\n",
780
+ " out[key] = v\n",
781
+ " return out\n",
782
+ "\n",
783
+ "def take(d, keys):\n",
784
+ " return {k: d[k] for k in keys if k in d}\n",
785
+ "\n",
786
+ "params = {}\n",
787
+ "sources = []\n",
788
+ "\n",
789
+ "# A) Read Roboflow dataset metadata (preprocess/augment & class info)\n",
790
+ "rf_files = [\"README.roboflow.txt\",\"README.dataset.txt\",\"data.yaml\",\"README.txt\"]\n",
791
+ "for f in rf_files:\n",
792
+ " p = os.path.join(DATA_DIR, f)\n",
793
+ " if os.path.exists(p):\n",
794
+ " try:\n",
795
+ " if f.endswith(\".yaml\"):\n",
796
+ " y = try_read_yaml_bytes(open(p,\"rb\").read()) or {}\n",
797
+ " params.update({f\"data.{k}\": v for k,v in y.items()})\n",
798
+ " else:\n",
799
+ " txt = open(p,\"r\",errors=\"ignore\").read()\n",
800
+ " params[\"roboflow.readme_present\"] = True\n",
801
+ " sources.append(f\"dataset:{f}\")\n",
802
+ " except: pass\n",
803
+ "\n",
804
+ "# B) Uploaded YAML/JSON\n",
805
+ "for name, content in uploaded.items():\n",
806
+ " low = name.lower()\n",
807
+ " if any(low.endswith(ext) for ext in [\".yaml\",\".yml\",\".json\"]):\n",
808
+ " try:\n",
809
+ " y = json.loads(content.decode(\"utf-8\")) if low.endswith(\".json\") else try_read_yaml_bytes(content)\n",
810
+ " if isinstance(y, dict):\n",
811
+ " params.update(flatten(y))\n",
812
+ " sources.append(name)\n",
813
+ " except: pass\n",
814
+ "\n",
815
+ "# C) Uploaded ZIP of runs/*\n",
816
+ "for name, content in uploaded.items():\n",
817
+ " if name.lower().endswith(\".zip\"):\n",
818
+ " zpath = os.path.join(workdir, name)\n",
819
+ " open(zpath,\"wb\").write(content)\n",
820
+ " with zipfile.ZipFile(zpath,\"r\") as z: z.extractall(os.path.join(workdir,\"unzipped\"))\n",
821
+ " for root, _, files_ in os.walk(os.path.join(workdir,\"unzipped\")):\n",
822
+ " for f in files_:\n",
823
+ " if f.lower() in {\"args.yaml\",\"hyp.yaml\",\"cfg.yaml\",\"opt.yaml\",\"results.yaml\",\"data.yaml\",\"config.yaml\"}:\n",
824
+ " p = os.path.join(root,f)\n",
825
+ " y = try_read_yaml_bytes(open(p,\"rb\").read())\n",
826
+ " if isinstance(y, dict):\n",
827
+ " params.update(flatten(y))\n",
828
+ " sources.append(f\"zip:{f}\")\n",
829
+ "\n",
830
+ "# D) Read .pt\n",
831
+ "for name, content in uploaded.items():\n",
832
+ " if name.endswith(\".pt\"):\n",
833
+ " tmp = os.path.join(workdir, name)\n",
834
+ " open(tmp,\"wb\").write(content)\n",
835
+ " model = YOLO(tmp)\n",
836
+ " ckpt = getattr(model, \"ckpt\", {}) or {}\n",
837
+ " if isinstance(ckpt, dict):\n",
838
+ " train_args = ckpt.get(\"train_args\", {}) or ckpt.get(\"args\", {}) or {}\n",
839
+ " if train_args:\n",
840
+ " params.update(flatten(train_args))\n",
841
+ " sources.append(f\"{name}:train_args\")\n",
842
+ " try:\n",
843
+ " model_args = getattr(model.model, \"args\", {}) or {}\n",
844
+ " if model_args:\n",
845
+ " params.update(flatten(model_args))\n",
846
+ " sources.append(f\"{name}:model.args\")\n",
847
+ " except: pass\n",
848
+ "\n",
849
+ "# E) Normalize to friendly keys (common YOLO train hypers)\n",
850
+ "alias = {\n",
851
+ " \"epochs\":\"train.epochs\",\"batch\":\"train.batch\",\"imgsz\":\"train.imgsz\",\"img_size\":\"train.imgsz\",\n",
852
+ " \"optimizer\":\"train.optimizer\",\"patience\":\"train.patience\",\n",
853
+ " \"lr0\":\"lr.lr0\",\"lrf\":\"lr.lrf\",\"momentum\":\"lr.momentum\",\"weight_decay\":\"lr.weight_decay\",\n",
854
+ " \"warmup_epochs\":\"lr.warmup_epochs\",\"warmup_momentum\":\"lr.warmup_momentum\",\"warmup_bias_lr\":\"lr.warmup_bias_lr\",\n",
855
+ " \"mosaic\":\"aug.mosaic\",\"hsv_h\":\"aug.hsv_h\",\"hsv_s\":\"aug.hsv_s\",\"hsv_v\":\"aug.hsv_v\",\n",
856
+ " \"flipud\":\"aug.flipud\",\"fliplr\":\"aug.fliplr\",\"degrees\":\"aug.degrees\",\"translate\":\"aug.translate\",\n",
857
+ " \"scale\":\"aug.scale\",\"shear\":\"aug.shear\",\"perspective\":\"aug.perspective\",\"erasing\":\"aug.erasing\",\n",
858
+ " \"mixup\":\"aug.mixup\",\"copy_paste\":\"aug.copy_paste\",\n",
859
+ " \"device\":\"env.device\",\"workers\":\"env.workers\",\"seed\":\"env.seed\",\"project\":\"env.project\",\"name\":\"env.name\",\"exist_ok\":\"env.exist_ok\"\n",
860
+ "}\n",
861
+ "normalized = {}\n",
862
+ "for k, v in list(params.items()):\n",
863
+ " k0 = k.split(\".\")[-1]\n",
864
+ " if k in alias: normalized[alias[k]] = v\n",
865
+ " elif k0 in alias: normalized[alias[k0]] = v\n",
866
+ " else: normalized[k] = v\n",
867
+ "params = normalized\n",
868
+ "\n",
869
+ "# Short, report-ready subset\n",
870
+ "primary_keys = [\n",
871
+ " \"train.epochs\",\"train.batch\",\"train.imgsz\",\"train.optimizer\",\"train.patience\",\n",
872
+ " \"lr.lr0\",\"lr.lrf\",\"lr.momentum\",\"lr.weight_decay\",\"lr.warmup_epochs\",\"lr.warmup_momentum\",\"lr.warmup_bias_lr\",\n",
873
+ " \"aug.mosaic\",\"aug.hsv_h\",\"aug.hsv_s\",\"aug.hsv_v\",\"aug.flipud\",\"aug.fliplr\",\"aug.degrees\",\"aug.translate\",\"aug.scale\",\"aug.shear\",\"aug.perspective\",\"aug.erasing\",\"aug.mixup\",\"aug.copy_paste\",\n",
874
+ " \"env.device\",\"env.workers\",\"env.seed\",\n",
875
+ " \"data.path\",\"data.train\",\"data.val\",\"data.test\",\"data.names\",\"nc\",\"names\"\n",
876
+ "]\n",
877
+ "primary = take(params, primary_keys)\n",
878
+ "\n",
879
+ "print(\"✅ Sources:\", \", \".join(sources) if sources else \"none\")\n",
880
+ "print(f\"✅ Total keys: {len(params)} | Primary shown: {len(primary)}\")\n",
881
+ "\n",
882
+ "import pandas as pd\n",
883
+ "df = pd.DataFrame(\n",
884
+ " [{\"parameter\": k, \"value\": primary.get(k, params.get(k))} for k in sorted(primary or params)]\n",
885
+ ")\n",
886
+ "df\n"
887
+ ]
888
+ },
889
+ {
890
+ "cell_type": "code",
891
+ "execution_count": 6,
892
+ "metadata": {
893
+ "colab": {
894
+ "base_uri": "https://localhost:8080/",
895
+ "height": 34
896
+ },
897
+ "id": "_F1fJ4dh38JN",
898
+ "outputId": "54ad9e14-a7f6-4810-98fb-e80dbaf17610"
899
+ },
900
+ "outputs": [
901
+ {
902
+ "data": {
903
+ "application/javascript": "\n async function download(id, filename, size) {\n if (!google.colab.kernel.accessAllowed) {\n return;\n }\n const div = document.createElement('div');\n const label = document.createElement('label');\n label.textContent = `Downloading \"${filename}\": `;\n div.appendChild(label);\n const progress = document.createElement('progress');\n progress.max = size;\n div.appendChild(progress);\n document.body.appendChild(div);\n\n const buffers = [];\n let downloaded = 0;\n\n const channel = await google.colab.kernel.comms.open(id);\n // Send a message to notify the kernel that we're ready.\n channel.send({})\n\n for await (const message of channel.messages) {\n // Send a message to notify the kernel that we're ready.\n channel.send({})\n if (message.buffers) {\n for (const buffer of message.buffers) {\n buffers.push(buffer);\n downloaded += buffer.byteLength;\n progress.value = downloaded;\n }\n }\n }\n const blob = new Blob(buffers, {type: 'application/binary'});\n const a = document.createElement('a');\n a.href = window.URL.createObjectURL(blob);\n a.download = filename;\n div.appendChild(a);\n a.click();\n div.remove();\n }\n ",
904
+ "text/plain": [
905
+ "<IPython.core.display.Javascript object>"
906
+ ]
907
+ },
908
+ "metadata": {},
909
+ "output_type": "display_data"
910
+ },
911
+ {
912
+ "data": {
913
+ "application/javascript": "download(\"download_227d7458-1155-429c-8f56-4bb4cbf25697\", \"hyperparams_all.yaml\", 2037)",
914
+ "text/plain": [
915
+ "<IPython.core.display.Javascript object>"
916
+ ]
917
+ },
918
+ "metadata": {},
919
+ "output_type": "display_data"
920
+ },
921
+ {
922
+ "data": {
923
+ "application/javascript": "\n async function download(id, filename, size) {\n if (!google.colab.kernel.accessAllowed) {\n return;\n }\n const div = document.createElement('div');\n const label = document.createElement('label');\n label.textContent = `Downloading \"${filename}\": `;\n div.appendChild(label);\n const progress = document.createElement('progress');\n progress.max = size;\n div.appendChild(progress);\n document.body.appendChild(div);\n\n const buffers = [];\n let downloaded = 0;\n\n const channel = await google.colab.kernel.comms.open(id);\n // Send a message to notify the kernel that we're ready.\n channel.send({})\n\n for await (const message of channel.messages) {\n // Send a message to notify the kernel that we're ready.\n channel.send({})\n if (message.buffers) {\n for (const buffer of message.buffers) {\n buffers.push(buffer);\n downloaded += buffer.byteLength;\n progress.value = downloaded;\n }\n }\n }\n const blob = new Blob(buffers, {type: 'application/binary'});\n const a = document.createElement('a');\n a.href = window.URL.createObjectURL(blob);\n a.download = filename;\n div.appendChild(a);\n a.click();\n div.remove();\n }\n ",
924
+ "text/plain": [
925
+ "<IPython.core.display.Javascript object>"
926
+ ]
927
+ },
928
+ "metadata": {},
929
+ "output_type": "display_data"
930
+ },
931
+ {
932
+ "data": {
933
+ "application/javascript": "download(\"download_02788a7c-4324-4881-b298-49de5a6336f8\", \"hyperparams_primary.yaml\", 633)",
934
+ "text/plain": [
935
+ "<IPython.core.display.Javascript object>"
936
+ ]
937
+ },
938
+ "metadata": {},
939
+ "output_type": "display_data"
940
+ },
941
+ {
942
+ "data": {
943
+ "application/javascript": "\n async function download(id, filename, size) {\n if (!google.colab.kernel.accessAllowed) {\n return;\n }\n const div = document.createElement('div');\n const label = document.createElement('label');\n label.textContent = `Downloading \"${filename}\": `;\n div.appendChild(label);\n const progress = document.createElement('progress');\n progress.max = size;\n div.appendChild(progress);\n document.body.appendChild(div);\n\n const buffers = [];\n let downloaded = 0;\n\n const channel = await google.colab.kernel.comms.open(id);\n // Send a message to notify the kernel that we're ready.\n channel.send({})\n\n for await (const message of channel.messages) {\n // Send a message to notify the kernel that we're ready.\n channel.send({})\n if (message.buffers) {\n for (const buffer of message.buffers) {\n buffers.push(buffer);\n downloaded += buffer.byteLength;\n progress.value = downloaded;\n }\n }\n }\n const blob = new Blob(buffers, {type: 'application/binary'});\n const a = document.createElement('a');\n a.href = window.URL.createObjectURL(blob);\n a.download = filename;\n div.appendChild(a);\n a.click();\n div.remove();\n }\n ",
944
+ "text/plain": [
945
+ "<IPython.core.display.Javascript object>"
946
+ ]
947
+ },
948
+ "metadata": {},
949
+ "output_type": "display_data"
950
+ },
951
+ {
952
+ "data": {
953
+ "application/javascript": "download(\"download_73abe0db-c31a-4a05-aa7f-a5a6e10ccb87\", \"hyperparams_all.csv\", 1912)",
954
+ "text/plain": [
955
+ "<IPython.core.display.Javascript object>"
956
+ ]
957
+ },
958
+ "metadata": {},
959
+ "output_type": "display_data"
960
+ },
961
+ {
962
+ "data": {
963
+ "application/javascript": "\n async function download(id, filename, size) {\n if (!google.colab.kernel.accessAllowed) {\n return;\n }\n const div = document.createElement('div');\n const label = document.createElement('label');\n label.textContent = `Downloading \"${filename}\": `;\n div.appendChild(label);\n const progress = document.createElement('progress');\n progress.max = size;\n div.appendChild(progress);\n document.body.appendChild(div);\n\n const buffers = [];\n let downloaded = 0;\n\n const channel = await google.colab.kernel.comms.open(id);\n // Send a message to notify the kernel that we're ready.\n channel.send({})\n\n for await (const message of channel.messages) {\n // Send a message to notify the kernel that we're ready.\n channel.send({})\n if (message.buffers) {\n for (const buffer of message.buffers) {\n buffers.push(buffer);\n downloaded += buffer.byteLength;\n progress.value = downloaded;\n }\n }\n }\n const blob = new Blob(buffers, {type: 'application/binary'});\n const a = document.createElement('a');\n a.href = window.URL.createObjectURL(blob);\n a.download = filename;\n div.appendChild(a);\n a.click();\n div.remove();\n }\n ",
964
+ "text/plain": [
965
+ "<IPython.core.display.Javascript object>"
966
+ ]
967
+ },
968
+ "metadata": {},
969
+ "output_type": "display_data"
970
+ },
971
+ {
972
+ "data": {
973
+ "application/javascript": "download(\"download_b8f2f1bb-5d09-472a-8f54-1a33642b1657\", \"hyperparams_primary.md\", 872)",
974
+ "text/plain": [
975
+ "<IPython.core.display.Javascript object>"
976
+ ]
977
+ },
978
+ "metadata": {},
979
+ "output_type": "display_data"
980
+ },
981
+ {
982
+ "name": "stdout",
983
+ "output_type": "stream",
984
+ "text": [
985
+ "Done.\n"
986
+ ]
987
+ }
988
+ ],
989
+ "source": [
990
+ "from google.colab import files, output\n",
991
+ "import yaml, pandas as pd, os\n",
992
+ "\n",
993
+ "os.makedirs(workdir, exist_ok=True)\n",
994
+ "all_yaml = os.path.join(workdir, \"hyperparams_all.yaml\")\n",
995
+ "primary_yaml = os.path.join(workdir, \"hyperparams_primary.yaml\")\n",
996
+ "csv_path = os.path.join(workdir, \"hyperparams_all.csv\")\n",
997
+ "md_path = os.path.join(workdir, \"hyperparams_primary.md\")\n",
998
+ "\n",
999
+ "with open(all_yaml, \"w\") as f: yaml.safe_dump(params, f, sort_keys=True, allow_unicode=True)\n",
1000
+ "with open(primary_yaml, \"w\") as f: yaml.safe_dump({k: params[k] for k in sorted(primary.keys()) if k in params}, f, sort_keys=False, allow_unicode=True)\n",
1001
+ "pd.DataFrame([{\"parameter\": k, \"value\": v} for k, v in sorted(params.items())]).to_csv(csv_path, index=False)\n",
1002
+ "with open(md_path, \"w\") as f:\n",
1003
+ " f.write(\"# YOLOv11 Hyperparameters (Primary)\\n\\n\")\n",
1004
+ " for k in sorted(primary.keys()):\n",
1005
+ " if k in params:\n",
1006
+ " f.write(f\"- **{k}**: {params[k]}\\n\")\n",
1007
+ "\n",
1008
+ "for p in [all_yaml, primary_yaml, csv_path, md_path]:\n",
1009
+ " files.download(p)\n",
1010
+ "print(\"Done.\")\n"
1011
+ ]
1012
+ }
1013
+ ],
1014
+ "metadata": {
1015
+ "accelerator": "GPU",
1016
+ "colab": {
1017
+ "gpuType": "T4",
1018
+ "provenance": []
1019
+ },
1020
+ "kernelspec": {
1021
+ "display_name": "Python 3",
1022
+ "name": "python3"
1023
+ },
1024
+ "language_info": {
1025
+ "name": "python"
1026
+ }
1027
+ },
1028
+ "nbformat": 4,
1029
+ "nbformat_minor": 0
1030
+ }
examples/Record.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:30036c354c820f7c72f0b9ab6bbb714483b1828fca98fcbb17492351fa1bc816
3
+ size 91906916
examples/crack_evaluation.ipynb ADDED
@@ -0,0 +1,927 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {
6
+ "id": "ZHqQGT0jBqLi"
7
+ },
8
+ "source": [
9
+ "## STEP 1: Install dependencies"
10
+ ]
11
+ },
12
+ {
13
+ "cell_type": "code",
14
+ "execution_count": null,
15
+ "metadata": {
16
+ "colab": {
17
+ "base_uri": "https://localhost:8080/"
18
+ },
19
+ "id": "LHUcg2ZDjre_",
20
+ "outputId": "6d4976a5-62ae-4609-9d8d-9b9cbd586997"
21
+ },
22
+ "outputs": [
23
+ {
24
+ "name": "stdout",
25
+ "output_type": "stream",
26
+ "text": [
27
+ "\u001b[?25l \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m0.0/1.1 MB\u001b[0m \u001b[31m?\u001b[0m eta \u001b[36m-:--:--\u001b[0m\r\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m1.1/1.1 MB\u001b[0m \u001b[31m40.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
28
+ "\u001b[?25h\u001b[?25l \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m0.0/89.9 kB\u001b[0m \u001b[31m?\u001b[0m eta \u001b[36m-:--:--\u001b[0m\r\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m89.9/89.9 kB\u001b[0m \u001b[31m9.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
29
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m66.8/66.8 kB\u001b[0m \u001b[31m6.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
30
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m49.9/49.9 MB\u001b[0m \u001b[31m20.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
31
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m1.4/1.4 MB\u001b[0m \u001b[31m78.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
32
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m4.2/4.2 MB\u001b[0m \u001b[31m126.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
33
+ "\u001b[?25h"
34
+ ]
35
+ }
36
+ ],
37
+ "source": [
38
+ "!pip install ultralytics roboflow --upgrade --quiet"
39
+ ]
40
+ },
41
+ {
42
+ "cell_type": "markdown",
43
+ "metadata": {
44
+ "id": "AMz9DvsFBxtA"
45
+ },
46
+ "source": [
47
+ "## STEP 2: Imports"
48
+ ]
49
+ },
50
+ {
51
+ "cell_type": "code",
52
+ "execution_count": null,
53
+ "metadata": {
54
+ "colab": {
55
+ "base_uri": "https://localhost:8080/"
56
+ },
57
+ "id": "h8GE0fXCjsVO",
58
+ "outputId": "f1fac47c-71e1-4c2e-8a2f-d583d2a86c86"
59
+ },
60
+ "outputs": [
61
+ {
62
+ "name": "stdout",
63
+ "output_type": "stream",
64
+ "text": [
65
+ "Creating new Ultralytics Settings v0.0.6 file ✅ \n",
66
+ "View Ultralytics Settings with 'yolo settings' or at '/root/.config/Ultralytics/settings.json'\n",
67
+ "Update Settings with 'yolo settings key=value', i.e. 'yolo settings runs_dir=path/to/dir'. For help see https://docs.ultralytics.com/quickstart/#ultralytics-settings.\n"
68
+ ]
69
+ }
70
+ ],
71
+ "source": [
72
+ "import os\n",
73
+ "import pandas as pd\n",
74
+ "import matplotlib.pyplot as plt\n",
75
+ "from roboflow import Roboflow\n",
76
+ "from ultralytics import YOLO\n",
77
+ "from google.colab import files"
78
+ ]
79
+ },
80
+ {
81
+ "cell_type": "markdown",
82
+ "metadata": {
83
+ "id": "tHZrVz8-B4VM"
84
+ },
85
+ "source": [
86
+ "## STEP 3: Get training dataset"
87
+ ]
88
+ },
89
+ {
90
+ "cell_type": "code",
91
+ "execution_count": null,
92
+ "metadata": {
93
+ "colab": {
94
+ "base_uri": "https://localhost:8080/"
95
+ },
96
+ "id": "uPmqYYhDj3nf",
97
+ "outputId": "645a87a0-2f61-445e-e68a-3fe04e232dcf"
98
+ },
99
+ "outputs": [
100
+ {
101
+ "name": "stdout",
102
+ "output_type": "stream",
103
+ "text": [
104
+ "loading Roboflow workspace...\n",
105
+ "loading Roboflow project...\n"
106
+ ]
107
+ },
108
+ {
109
+ "name": "stderr",
110
+ "output_type": "stream",
111
+ "text": [
112
+ "Downloading Dataset Version Zip in Clay-Crack-Detection-14 to yolov11:: 100%|██████████| 359480/359480 [00:11<00:00, 30777.63it/s]"
113
+ ]
114
+ },
115
+ {
116
+ "name": "stdout",
117
+ "output_type": "stream",
118
+ "text": [
119
+ "\n"
120
+ ]
121
+ },
122
+ {
123
+ "name": "stderr",
124
+ "output_type": "stream",
125
+ "text": [
126
+ "\n",
127
+ "Extracting Dataset Version Zip to Clay-Crack-Detection-14 in yolov11:: 100%|██████████| 15197/15197 [00:02<00:00, 6929.67it/s]\n"
128
+ ]
129
+ }
130
+ ],
131
+ "source": [
132
+ "rf = Roboflow(api_key=\"ROBOFLOW_API_KEY\")\n",
133
+ "project = rf.workspace(\"tv-vloon\").project(\"clay-crack-detection\")\n",
134
+ "version = project.version(14)\n",
135
+ "dataset = version.download(\"yolov11\")"
136
+ ]
137
+ },
138
+ {
139
+ "cell_type": "code",
140
+ "execution_count": null,
141
+ "metadata": {
142
+ "colab": {
143
+ "base_uri": "https://localhost:8080/",
144
+ "height": 90
145
+ },
146
+ "id": "9EPy__E8j4x2",
147
+ "outputId": "2fdbbb45-1e14-4a21-f402-bdc3fbe5a15a"
148
+ },
149
+ "outputs": [
150
+ {
151
+ "name": "stdout",
152
+ "output_type": "stream",
153
+ "text": [
154
+ "Upload YOLOv11 model\n"
155
+ ]
156
+ },
157
+ {
158
+ "data": {
159
+ "text/html": [
160
+ "\n",
161
+ " <input type=\"file\" id=\"files-f2bc48c8-d992-4c4d-8f9e-b145346f89db\" name=\"files[]\" multiple disabled\n",
162
+ " style=\"border:none\" />\n",
163
+ " <output id=\"result-f2bc48c8-d992-4c4d-8f9e-b145346f89db\">\n",
164
+ " Upload widget is only available when the cell has been executed in the\n",
165
+ " current browser session. Please rerun this cell to enable.\n",
166
+ " </output>\n",
167
+ " <script>// Copyright 2017 Google LLC\n",
168
+ "//\n",
169
+ "// Licensed under the Apache License, Version 2.0 (the \"License\");\n",
170
+ "// you may not use this file except in compliance with the License.\n",
171
+ "// You may obtain a copy of the License at\n",
172
+ "//\n",
173
+ "// http://www.apache.org/licenses/LICENSE-2.0\n",
174
+ "//\n",
175
+ "// Unless required by applicable law or agreed to in writing, software\n",
176
+ "// distributed under the License is distributed on an \"AS IS\" BASIS,\n",
177
+ "// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
178
+ "// See the License for the specific language governing permissions and\n",
179
+ "// limitations under the License.\n",
180
+ "\n",
181
+ "/**\n",
182
+ " * @fileoverview Helpers for google.colab Python module.\n",
183
+ " */\n",
184
+ "(function(scope) {\n",
185
+ "function span(text, styleAttributes = {}) {\n",
186
+ " const element = document.createElement('span');\n",
187
+ " element.textContent = text;\n",
188
+ " for (const key of Object.keys(styleAttributes)) {\n",
189
+ " element.style[key] = styleAttributes[key];\n",
190
+ " }\n",
191
+ " return element;\n",
192
+ "}\n",
193
+ "\n",
194
+ "// Max number of bytes which will be uploaded at a time.\n",
195
+ "const MAX_PAYLOAD_SIZE = 100 * 1024;\n",
196
+ "\n",
197
+ "function _uploadFiles(inputId, outputId) {\n",
198
+ " const steps = uploadFilesStep(inputId, outputId);\n",
199
+ " const outputElement = document.getElementById(outputId);\n",
200
+ " // Cache steps on the outputElement to make it available for the next call\n",
201
+ " // to uploadFilesContinue from Python.\n",
202
+ " outputElement.steps = steps;\n",
203
+ "\n",
204
+ " return _uploadFilesContinue(outputId);\n",
205
+ "}\n",
206
+ "\n",
207
+ "// This is roughly an async generator (not supported in the browser yet),\n",
208
+ "// where there are multiple asynchronous steps and the Python side is going\n",
209
+ "// to poll for completion of each step.\n",
210
+ "// This uses a Promise to block the python side on completion of each step,\n",
211
+ "// then passes the result of the previous step as the input to the next step.\n",
212
+ "function _uploadFilesContinue(outputId) {\n",
213
+ " const outputElement = document.getElementById(outputId);\n",
214
+ " const steps = outputElement.steps;\n",
215
+ "\n",
216
+ " const next = steps.next(outputElement.lastPromiseValue);\n",
217
+ " return Promise.resolve(next.value.promise).then((value) => {\n",
218
+ " // Cache the last promise value to make it available to the next\n",
219
+ " // step of the generator.\n",
220
+ " outputElement.lastPromiseValue = value;\n",
221
+ " return next.value.response;\n",
222
+ " });\n",
223
+ "}\n",
224
+ "\n",
225
+ "/**\n",
226
+ " * Generator function which is called between each async step of the upload\n",
227
+ " * process.\n",
228
+ " * @param {string} inputId Element ID of the input file picker element.\n",
229
+ " * @param {string} outputId Element ID of the output display.\n",
230
+ " * @return {!Iterable<!Object>} Iterable of next steps.\n",
231
+ " */\n",
232
+ "function* uploadFilesStep(inputId, outputId) {\n",
233
+ " const inputElement = document.getElementById(inputId);\n",
234
+ " inputElement.disabled = false;\n",
235
+ "\n",
236
+ " const outputElement = document.getElementById(outputId);\n",
237
+ " outputElement.innerHTML = '';\n",
238
+ "\n",
239
+ " const pickedPromise = new Promise((resolve) => {\n",
240
+ " inputElement.addEventListener('change', (e) => {\n",
241
+ " resolve(e.target.files);\n",
242
+ " });\n",
243
+ " });\n",
244
+ "\n",
245
+ " const cancel = document.createElement('button');\n",
246
+ " inputElement.parentElement.appendChild(cancel);\n",
247
+ " cancel.textContent = 'Cancel upload';\n",
248
+ " const cancelPromise = new Promise((resolve) => {\n",
249
+ " cancel.onclick = () => {\n",
250
+ " resolve(null);\n",
251
+ " };\n",
252
+ " });\n",
253
+ "\n",
254
+ " // Wait for the user to pick the files.\n",
255
+ " const files = yield {\n",
256
+ " promise: Promise.race([pickedPromise, cancelPromise]),\n",
257
+ " response: {\n",
258
+ " action: 'starting',\n",
259
+ " }\n",
260
+ " };\n",
261
+ "\n",
262
+ " cancel.remove();\n",
263
+ "\n",
264
+ " // Disable the input element since further picks are not allowed.\n",
265
+ " inputElement.disabled = true;\n",
266
+ "\n",
267
+ " if (!files) {\n",
268
+ " return {\n",
269
+ " response: {\n",
270
+ " action: 'complete',\n",
271
+ " }\n",
272
+ " };\n",
273
+ " }\n",
274
+ "\n",
275
+ " for (const file of files) {\n",
276
+ " const li = document.createElement('li');\n",
277
+ " li.append(span(file.name, {fontWeight: 'bold'}));\n",
278
+ " li.append(span(\n",
279
+ " `(${file.type || 'n/a'}) - ${file.size} bytes, ` +\n",
280
+ " `last modified: ${\n",
281
+ " file.lastModifiedDate ? file.lastModifiedDate.toLocaleDateString() :\n",
282
+ " 'n/a'} - `));\n",
283
+ " const percent = span('0% done');\n",
284
+ " li.appendChild(percent);\n",
285
+ "\n",
286
+ " outputElement.appendChild(li);\n",
287
+ "\n",
288
+ " const fileDataPromise = new Promise((resolve) => {\n",
289
+ " const reader = new FileReader();\n",
290
+ " reader.onload = (e) => {\n",
291
+ " resolve(e.target.result);\n",
292
+ " };\n",
293
+ " reader.readAsArrayBuffer(file);\n",
294
+ " });\n",
295
+ " // Wait for the data to be ready.\n",
296
+ " let fileData = yield {\n",
297
+ " promise: fileDataPromise,\n",
298
+ " response: {\n",
299
+ " action: 'continue',\n",
300
+ " }\n",
301
+ " };\n",
302
+ "\n",
303
+ " // Use a chunked sending to avoid message size limits. See b/62115660.\n",
304
+ " let position = 0;\n",
305
+ " do {\n",
306
+ " const length = Math.min(fileData.byteLength - position, MAX_PAYLOAD_SIZE);\n",
307
+ " const chunk = new Uint8Array(fileData, position, length);\n",
308
+ " position += length;\n",
309
+ "\n",
310
+ " const base64 = btoa(String.fromCharCode.apply(null, chunk));\n",
311
+ " yield {\n",
312
+ " response: {\n",
313
+ " action: 'append',\n",
314
+ " file: file.name,\n",
315
+ " data: base64,\n",
316
+ " },\n",
317
+ " };\n",
318
+ "\n",
319
+ " let percentDone = fileData.byteLength === 0 ?\n",
320
+ " 100 :\n",
321
+ " Math.round((position / fileData.byteLength) * 100);\n",
322
+ " percent.textContent = `${percentDone}% done`;\n",
323
+ "\n",
324
+ " } while (position < fileData.byteLength);\n",
325
+ " }\n",
326
+ "\n",
327
+ " // All done.\n",
328
+ " yield {\n",
329
+ " response: {\n",
330
+ " action: 'complete',\n",
331
+ " }\n",
332
+ " };\n",
333
+ "}\n",
334
+ "\n",
335
+ "scope.google = scope.google || {};\n",
336
+ "scope.google.colab = scope.google.colab || {};\n",
337
+ "scope.google.colab._files = {\n",
338
+ " _uploadFiles,\n",
339
+ " _uploadFilesContinue,\n",
340
+ "};\n",
341
+ "})(self);\n",
342
+ "</script> "
343
+ ],
344
+ "text/plain": [
345
+ "<IPython.core.display.HTML object>"
346
+ ]
347
+ },
348
+ "metadata": {},
349
+ "output_type": "display_data"
350
+ },
351
+ {
352
+ "name": "stdout",
353
+ "output_type": "stream",
354
+ "text": [
355
+ "Saving crack-seg.pt to crack-seg.pt\n"
356
+ ]
357
+ }
358
+ ],
359
+ "source": [
360
+ "print(\"Upload YOLOv11 model\")\n",
361
+ "uploaded = files.upload()\n",
362
+ "model_path = list(uploaded.keys())[0] # Grab the uploaded file name"
363
+ ]
364
+ },
365
+ {
366
+ "cell_type": "code",
367
+ "execution_count": null,
368
+ "metadata": {
369
+ "id": "-Iv8ULS6j5wq"
370
+ },
371
+ "outputs": [],
372
+ "source": [
373
+ "model = YOLO(model_path)"
374
+ ]
375
+ },
376
+ {
377
+ "cell_type": "markdown",
378
+ "metadata": {
379
+ "id": "ceeSxcFRCOZU"
380
+ },
381
+ "source": [
382
+ "## STEP 4: Run Evaluation"
383
+ ]
384
+ },
385
+ {
386
+ "cell_type": "code",
387
+ "execution_count": null,
388
+ "metadata": {
389
+ "colab": {
390
+ "base_uri": "https://localhost:8080/"
391
+ },
392
+ "id": "lh4IzW4sj6z_",
393
+ "outputId": "1b25edb4-4f7b-4b79-de75-81e584d6264e"
394
+ },
395
+ "outputs": [
396
+ {
397
+ "name": "stdout",
398
+ "output_type": "stream",
399
+ "text": [
400
+ "Ultralytics 8.3.214 🚀 Python-3.12.12 torch-2.8.0+cu126 CUDA:0 (Tesla T4, 15095MiB)\n",
401
+ "YOLO11s-seg summary (fused): 113 layers, 10,067,977 parameters, 0 gradients, 32.8 GFLOPs\n",
402
+ "\u001b[KDownloading https://ultralytics.com/assets/Arial.ttf to '/root/.config/Ultralytics/Arial.ttf': 100% ━━━━━━━━━━━━ 755.1KB 40.9MB/s 0.0s\n",
403
+ "\u001b[34m\u001b[1mval: \u001b[0mFast image access ✅ (ping: 0.0±0.0 ms, read: 1600.0±510.3 MB/s, size: 46.1 KB)\n",
404
+ "\u001b[K\u001b[34m\u001b[1mval: \u001b[0mScanning /content/Clay-Crack-Detection-14/test/labels... 198 images, 34 backgrounds, 0 corrupt: 100% ━━━━━━━━━━━━ 198/198 1.2Kit/s 0.2s\n",
405
+ "\u001b[34m\u001b[1mval: \u001b[0mNew cache created: /content/Clay-Crack-Detection-14/test/labels.cache\n",
406
+ "\u001b[31m\u001b[1mrequirements:\u001b[0m Ultralytics requirement ['faster-coco-eval>=1.6.7'] not found, attempting AutoUpdate...\n",
407
+ "\n",
408
+ "\u001b[31m\u001b[1mrequirements:\u001b[0m AutoUpdate success ✅ 0.8s\n",
409
+ "WARNING ⚠️ \u001b[31m\u001b[1mrequirements:\u001b[0m \u001b[1mRestart runtime or rerun command for updates to take effect\u001b[0m\n",
410
+ "\n",
411
+ "\u001b[K Class Images Instances Box(P R mAP50 mAP50-95) Mask(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 13/13 0.6it/s 20.5s\n",
412
+ " all 198 1911 0.667 0.629 0.622 0.41 0.67 0.632 0.624 0.352\n",
413
+ " crack_b 135 811 0.812 0.816 0.819 0.608 0.816 0.819 0.827 0.542\n",
414
+ " crack_s 152 1034 0.724 0.648 0.656 0.376 0.713 0.637 0.648 0.311\n",
415
+ " crack_shadow 35 66 0.465 0.424 0.392 0.245 0.482 0.439 0.396 0.203\n",
416
+ "Speed: 1.8ms preprocess, 12.3ms inference, 0.0ms loss, 4.6ms postprocess per image\n",
417
+ "Saving /content/runs/segment/val/predictions.json...\n",
418
+ "Results saved to \u001b[1m/content/runs/segment/val\u001b[0m\n"
419
+ ]
420
+ }
421
+ ],
422
+ "source": [
423
+ "results = model.val(data=f\"{dataset.location}/data.yaml\", split=\"test\", save_json=True)"
424
+ ]
425
+ },
426
+ {
427
+ "cell_type": "code",
428
+ "execution_count": null,
429
+ "metadata": {
430
+ "colab": {
431
+ "base_uri": "https://localhost:8080/"
432
+ },
433
+ "id": "iXFceDUyj738",
434
+ "outputId": "a39090b8-65b0-4033-d327-c79f7028e692"
435
+ },
436
+ "outputs": [
437
+ {
438
+ "name": "stdout",
439
+ "output_type": "stream",
440
+ "text": [
441
+ "\n",
442
+ "Bounding Box (Box) Evaluation:\n",
443
+ "Precision : 0.667\n",
444
+ "Recall : 0.629\n",
445
+ "mAP@0.5 : 0.622\n",
446
+ "mAP@0.5:0.95 : 0.410\n",
447
+ "\n",
448
+ "Segmentation Mask (Mask) Evaluation:\n",
449
+ "Precision : 0.670\n",
450
+ "Recall : 0.632\n",
451
+ "mAP@0.5 : 0.624\n",
452
+ "mAP@0.5:0.95 : 0.352\n"
453
+ ]
454
+ }
455
+ ],
456
+ "source": [
457
+ "metrics = results.results_dict\n",
458
+ "\n",
459
+ "print(\"\\nBounding Box (Box) Evaluation:\")\n",
460
+ "print(f\"Precision : {metrics['metrics/precision(B)']:.3f}\")\n",
461
+ "print(f\"Recall : {metrics['metrics/recall(B)']:.3f}\")\n",
462
+ "print(f\"mAP@0.5 : {metrics['metrics/mAP50(B)']:.3f}\")\n",
463
+ "print(f\"mAP@0.5:0.95 : {metrics['metrics/mAP50-95(B)']:.3f}\")\n",
464
+ "\n",
465
+ "print(\"\\nSegmentation Mask (Mask) Evaluation:\")\n",
466
+ "print(f\"Precision : {metrics['metrics/precision(M)']:.3f}\")\n",
467
+ "print(f\"Recall : {metrics['metrics/recall(M)']:.3f}\")\n",
468
+ "print(f\"mAP@0.5 : {metrics['metrics/mAP50(M)']:.3f}\")\n",
469
+ "print(f\"mAP@0.5:0.95 : {metrics['metrics/mAP50-95(M)']:.3f}\")\n"
470
+ ]
471
+ },
472
+ {
473
+ "cell_type": "code",
474
+ "execution_count": null,
475
+ "metadata": {
476
+ "colab": {
477
+ "base_uri": "https://localhost:8080/",
478
+ "height": 196
479
+ },
480
+ "id": "D0MGJRRNj8_4",
481
+ "outputId": "c3abccc8-f308-4495-80fa-65f61d86a902"
482
+ },
483
+ "outputs": [
484
+ {
485
+ "name": "stdout",
486
+ "output_type": "stream",
487
+ "text": [
488
+ "\n",
489
+ "Per-Class Evaluation Metrics:\n"
490
+ ]
491
+ },
492
+ {
493
+ "data": {
494
+ "application/vnd.google.colaboratory.intrinsic+json": {
495
+ "summary": "{\n \"name\": \"df_per_class\",\n \"rows\": 3,\n \"fields\": [\n {\n \"column\": \"Class\",\n \"properties\": {\n \"dtype\": \"string\",\n \"num_unique_values\": 3,\n \"samples\": [\n \"crack_b\",\n \"crack_s\",\n \"crack_shadow\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"Precision\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 0.1803717489527495,\n \"min\": 0.465232485462606,\n \"max\": 0.8121673307119629,\n \"num_unique_values\": 3,\n \"samples\": [\n 0.8121673307119629,\n 0.7243098568355149,\n 0.465232485462606\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"Recall\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 0.19640824276848068,\n \"min\": 0.42424242424242425,\n \"max\": 0.8157276086782503,\n \"num_unique_values\": 3,\n \"samples\": [\n 0.8157276086782503,\n 0.6479690522243714,\n 0.42424242424242425\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"mAP@0.5\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 0.0,\n \"min\": 0.6224444136770416,\n \"max\": 0.6224444136770416,\n \"num_unique_values\": 1,\n \"samples\": [\n 0.6224444136770416\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"mAP@0.5:0.95\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 0.0,\n \"min\": 0.40963491067115904,\n \"max\": 0.40963491067115904,\n \"num_unique_values\": 1,\n \"samples\": [\n 0.40963491067115904\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}",
496
+ "type": "dataframe",
497
+ "variable_name": "df_per_class"
498
+ },
499
+ "text/html": [
500
+ "\n",
501
+ " <div id=\"df-44d224d4-3865-4201-b84c-e6c961b63e3f\" class=\"colab-df-container\">\n",
502
+ " <div>\n",
503
+ "<style scoped>\n",
504
+ " .dataframe tbody tr th:only-of-type {\n",
505
+ " vertical-align: middle;\n",
506
+ " }\n",
507
+ "\n",
508
+ " .dataframe tbody tr th {\n",
509
+ " vertical-align: top;\n",
510
+ " }\n",
511
+ "\n",
512
+ " .dataframe thead th {\n",
513
+ " text-align: right;\n",
514
+ " }\n",
515
+ "</style>\n",
516
+ "<table border=\"1\" class=\"dataframe\">\n",
517
+ " <thead>\n",
518
+ " <tr style=\"text-align: right;\">\n",
519
+ " <th></th>\n",
520
+ " <th>Class</th>\n",
521
+ " <th>Precision</th>\n",
522
+ " <th>Recall</th>\n",
523
+ " <th>mAP@0.5</th>\n",
524
+ " <th>mAP@0.5:0.95</th>\n",
525
+ " </tr>\n",
526
+ " </thead>\n",
527
+ " <tbody>\n",
528
+ " <tr>\n",
529
+ " <th>0</th>\n",
530
+ " <td>crack_b</td>\n",
531
+ " <td>0.812167</td>\n",
532
+ " <td>0.815728</td>\n",
533
+ " <td>0.622444</td>\n",
534
+ " <td>0.409635</td>\n",
535
+ " </tr>\n",
536
+ " <tr>\n",
537
+ " <th>1</th>\n",
538
+ " <td>crack_s</td>\n",
539
+ " <td>0.724310</td>\n",
540
+ " <td>0.647969</td>\n",
541
+ " <td>0.622444</td>\n",
542
+ " <td>0.409635</td>\n",
543
+ " </tr>\n",
544
+ " <tr>\n",
545
+ " <th>2</th>\n",
546
+ " <td>crack_shadow</td>\n",
547
+ " <td>0.465232</td>\n",
548
+ " <td>0.424242</td>\n",
549
+ " <td>0.622444</td>\n",
550
+ " <td>0.409635</td>\n",
551
+ " </tr>\n",
552
+ " </tbody>\n",
553
+ "</table>\n",
554
+ "</div>\n",
555
+ " <div class=\"colab-df-buttons\">\n",
556
+ "\n",
557
+ " <div class=\"colab-df-container\">\n",
558
+ " <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-44d224d4-3865-4201-b84c-e6c961b63e3f')\"\n",
559
+ " title=\"Convert this dataframe to an interactive table.\"\n",
560
+ " style=\"display:none;\">\n",
561
+ "\n",
562
+ " <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
563
+ " <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
564
+ " </svg>\n",
565
+ " </button>\n",
566
+ "\n",
567
+ " <style>\n",
568
+ " .colab-df-container {\n",
569
+ " display:flex;\n",
570
+ " gap: 12px;\n",
571
+ " }\n",
572
+ "\n",
573
+ " .colab-df-convert {\n",
574
+ " background-color: #E8F0FE;\n",
575
+ " border: none;\n",
576
+ " border-radius: 50%;\n",
577
+ " cursor: pointer;\n",
578
+ " display: none;\n",
579
+ " fill: #1967D2;\n",
580
+ " height: 32px;\n",
581
+ " padding: 0 0 0 0;\n",
582
+ " width: 32px;\n",
583
+ " }\n",
584
+ "\n",
585
+ " .colab-df-convert:hover {\n",
586
+ " background-color: #E2EBFA;\n",
587
+ " box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
588
+ " fill: #174EA6;\n",
589
+ " }\n",
590
+ "\n",
591
+ " .colab-df-buttons div {\n",
592
+ " margin-bottom: 4px;\n",
593
+ " }\n",
594
+ "\n",
595
+ " [theme=dark] .colab-df-convert {\n",
596
+ " background-color: #3B4455;\n",
597
+ " fill: #D2E3FC;\n",
598
+ " }\n",
599
+ "\n",
600
+ " [theme=dark] .colab-df-convert:hover {\n",
601
+ " background-color: #434B5C;\n",
602
+ " box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
603
+ " filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
604
+ " fill: #FFFFFF;\n",
605
+ " }\n",
606
+ " </style>\n",
607
+ "\n",
608
+ " <script>\n",
609
+ " const buttonEl =\n",
610
+ " document.querySelector('#df-44d224d4-3865-4201-b84c-e6c961b63e3f button.colab-df-convert');\n",
611
+ " buttonEl.style.display =\n",
612
+ " google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
613
+ "\n",
614
+ " async function convertToInteractive(key) {\n",
615
+ " const element = document.querySelector('#df-44d224d4-3865-4201-b84c-e6c961b63e3f');\n",
616
+ " const dataTable =\n",
617
+ " await google.colab.kernel.invokeFunction('convertToInteractive',\n",
618
+ " [key], {});\n",
619
+ " if (!dataTable) return;\n",
620
+ "\n",
621
+ " const docLinkHtml = 'Like what you see? Visit the ' +\n",
622
+ " '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
623
+ " + ' to learn more about interactive tables.';\n",
624
+ " element.innerHTML = '';\n",
625
+ " dataTable['output_type'] = 'display_data';\n",
626
+ " await google.colab.output.renderOutput(dataTable, element);\n",
627
+ " const docLink = document.createElement('div');\n",
628
+ " docLink.innerHTML = docLinkHtml;\n",
629
+ " element.appendChild(docLink);\n",
630
+ " }\n",
631
+ " </script>\n",
632
+ " </div>\n",
633
+ "\n",
634
+ "\n",
635
+ " <div id=\"df-d486e766-8968-4dc8-8476-2627c282dbb7\">\n",
636
+ " <button class=\"colab-df-quickchart\" onclick=\"quickchart('df-d486e766-8968-4dc8-8476-2627c282dbb7')\"\n",
637
+ " title=\"Suggest charts\"\n",
638
+ " style=\"display:none;\">\n",
639
+ "\n",
640
+ "<svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\"viewBox=\"0 0 24 24\"\n",
641
+ " width=\"24px\">\n",
642
+ " <g>\n",
643
+ " <path d=\"M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z\"/>\n",
644
+ " </g>\n",
645
+ "</svg>\n",
646
+ " </button>\n",
647
+ "\n",
648
+ "<style>\n",
649
+ " .colab-df-quickchart {\n",
650
+ " --bg-color: #E8F0FE;\n",
651
+ " --fill-color: #1967D2;\n",
652
+ " --hover-bg-color: #E2EBFA;\n",
653
+ " --hover-fill-color: #174EA6;\n",
654
+ " --disabled-fill-color: #AAA;\n",
655
+ " --disabled-bg-color: #DDD;\n",
656
+ " }\n",
657
+ "\n",
658
+ " [theme=dark] .colab-df-quickchart {\n",
659
+ " --bg-color: #3B4455;\n",
660
+ " --fill-color: #D2E3FC;\n",
661
+ " --hover-bg-color: #434B5C;\n",
662
+ " --hover-fill-color: #FFFFFF;\n",
663
+ " --disabled-bg-color: #3B4455;\n",
664
+ " --disabled-fill-color: #666;\n",
665
+ " }\n",
666
+ "\n",
667
+ " .colab-df-quickchart {\n",
668
+ " background-color: var(--bg-color);\n",
669
+ " border: none;\n",
670
+ " border-radius: 50%;\n",
671
+ " cursor: pointer;\n",
672
+ " display: none;\n",
673
+ " fill: var(--fill-color);\n",
674
+ " height: 32px;\n",
675
+ " padding: 0;\n",
676
+ " width: 32px;\n",
677
+ " }\n",
678
+ "\n",
679
+ " .colab-df-quickchart:hover {\n",
680
+ " background-color: var(--hover-bg-color);\n",
681
+ " box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
682
+ " fill: var(--button-hover-fill-color);\n",
683
+ " }\n",
684
+ "\n",
685
+ " .colab-df-quickchart-complete:disabled,\n",
686
+ " .colab-df-quickchart-complete:disabled:hover {\n",
687
+ " background-color: var(--disabled-bg-color);\n",
688
+ " fill: var(--disabled-fill-color);\n",
689
+ " box-shadow: none;\n",
690
+ " }\n",
691
+ "\n",
692
+ " .colab-df-spinner {\n",
693
+ " border: 2px solid var(--fill-color);\n",
694
+ " border-color: transparent;\n",
695
+ " border-bottom-color: var(--fill-color);\n",
696
+ " animation:\n",
697
+ " spin 1s steps(1) infinite;\n",
698
+ " }\n",
699
+ "\n",
700
+ " @keyframes spin {\n",
701
+ " 0% {\n",
702
+ " border-color: transparent;\n",
703
+ " border-bottom-color: var(--fill-color);\n",
704
+ " border-left-color: var(--fill-color);\n",
705
+ " }\n",
706
+ " 20% {\n",
707
+ " border-color: transparent;\n",
708
+ " border-left-color: var(--fill-color);\n",
709
+ " border-top-color: var(--fill-color);\n",
710
+ " }\n",
711
+ " 30% {\n",
712
+ " border-color: transparent;\n",
713
+ " border-left-color: var(--fill-color);\n",
714
+ " border-top-color: var(--fill-color);\n",
715
+ " border-right-color: var(--fill-color);\n",
716
+ " }\n",
717
+ " 40% {\n",
718
+ " border-color: transparent;\n",
719
+ " border-right-color: var(--fill-color);\n",
720
+ " border-top-color: var(--fill-color);\n",
721
+ " }\n",
722
+ " 60% {\n",
723
+ " border-color: transparent;\n",
724
+ " border-right-color: var(--fill-color);\n",
725
+ " }\n",
726
+ " 80% {\n",
727
+ " border-color: transparent;\n",
728
+ " border-right-color: var(--fill-color);\n",
729
+ " border-bottom-color: var(--fill-color);\n",
730
+ " }\n",
731
+ " 90% {\n",
732
+ " border-color: transparent;\n",
733
+ " border-bottom-color: var(--fill-color);\n",
734
+ " }\n",
735
+ " }\n",
736
+ "</style>\n",
737
+ "\n",
738
+ " <script>\n",
739
+ " async function quickchart(key) {\n",
740
+ " const quickchartButtonEl =\n",
741
+ " document.querySelector('#' + key + ' button');\n",
742
+ " quickchartButtonEl.disabled = true; // To prevent multiple clicks.\n",
743
+ " quickchartButtonEl.classList.add('colab-df-spinner');\n",
744
+ " try {\n",
745
+ " const charts = await google.colab.kernel.invokeFunction(\n",
746
+ " 'suggestCharts', [key], {});\n",
747
+ " } catch (error) {\n",
748
+ " console.error('Error during call to suggestCharts:', error);\n",
749
+ " }\n",
750
+ " quickchartButtonEl.classList.remove('colab-df-spinner');\n",
751
+ " quickchartButtonEl.classList.add('colab-df-quickchart-complete');\n",
752
+ " }\n",
753
+ " (() => {\n",
754
+ " let quickchartButtonEl =\n",
755
+ " document.querySelector('#df-d486e766-8968-4dc8-8476-2627c282dbb7 button');\n",
756
+ " quickchartButtonEl.style.display =\n",
757
+ " google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
758
+ " })();\n",
759
+ " </script>\n",
760
+ " </div>\n",
761
+ "\n",
762
+ " <div id=\"id_2d7fbd5c-457b-4892-8ab7-07b34cb27aff\">\n",
763
+ " <style>\n",
764
+ " .colab-df-generate {\n",
765
+ " background-color: #E8F0FE;\n",
766
+ " border: none;\n",
767
+ " border-radius: 50%;\n",
768
+ " cursor: pointer;\n",
769
+ " display: none;\n",
770
+ " fill: #1967D2;\n",
771
+ " height: 32px;\n",
772
+ " padding: 0 0 0 0;\n",
773
+ " width: 32px;\n",
774
+ " }\n",
775
+ "\n",
776
+ " .colab-df-generate:hover {\n",
777
+ " background-color: #E2EBFA;\n",
778
+ " box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
779
+ " fill: #174EA6;\n",
780
+ " }\n",
781
+ "\n",
782
+ " [theme=dark] .colab-df-generate {\n",
783
+ " background-color: #3B4455;\n",
784
+ " fill: #D2E3FC;\n",
785
+ " }\n",
786
+ "\n",
787
+ " [theme=dark] .colab-df-generate:hover {\n",
788
+ " background-color: #434B5C;\n",
789
+ " box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
790
+ " filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
791
+ " fill: #FFFFFF;\n",
792
+ " }\n",
793
+ " </style>\n",
794
+ " <button class=\"colab-df-generate\" onclick=\"generateWithVariable('df_per_class')\"\n",
795
+ " title=\"Generate code using this dataframe.\"\n",
796
+ " style=\"display:none;\">\n",
797
+ "\n",
798
+ " <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\"viewBox=\"0 0 24 24\"\n",
799
+ " width=\"24px\">\n",
800
+ " <path d=\"M7,19H8.4L18.45,9,17,7.55,7,17.6ZM5,21V16.75L18.45,3.32a2,2,0,0,1,2.83,0l1.4,1.43a1.91,1.91,0,0,1,.58,1.4,1.91,1.91,0,0,1-.58,1.4L9.25,21ZM18.45,9,17,7.55Zm-12,3A5.31,5.31,0,0,0,4.9,8.1,5.31,5.31,0,0,0,1,6.5,5.31,5.31,0,0,0,4.9,4.9,5.31,5.31,0,0,0,6.5,1,5.31,5.31,0,0,0,8.1,4.9,5.31,5.31,0,0,0,12,6.5,5.46,5.46,0,0,0,6.5,12Z\"/>\n",
801
+ " </svg>\n",
802
+ " </button>\n",
803
+ " <script>\n",
804
+ " (() => {\n",
805
+ " const buttonEl =\n",
806
+ " document.querySelector('#id_2d7fbd5c-457b-4892-8ab7-07b34cb27aff button.colab-df-generate');\n",
807
+ " buttonEl.style.display =\n",
808
+ " google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
809
+ "\n",
810
+ " buttonEl.onclick = () => {\n",
811
+ " google.colab.notebook.generateWithVariable('df_per_class');\n",
812
+ " }\n",
813
+ " })();\n",
814
+ " </script>\n",
815
+ " </div>\n",
816
+ "\n",
817
+ " </div>\n",
818
+ " </div>\n"
819
+ ],
820
+ "text/plain": [
821
+ " Class Precision Recall mAP@0.5 mAP@0.5:0.95\n",
822
+ "0 crack_b 0.812167 0.815728 0.622444 0.409635\n",
823
+ "1 crack_s 0.724310 0.647969 0.622444 0.409635\n",
824
+ "2 crack_shadow 0.465232 0.424242 0.622444 0.409635"
825
+ ]
826
+ },
827
+ "metadata": {},
828
+ "output_type": "display_data"
829
+ },
830
+ {
831
+ "name": "stdout",
832
+ "output_type": "stream",
833
+ "text": [
834
+ "✅ Saved to per_class_metrics.csv\n"
835
+ ]
836
+ }
837
+ ],
838
+ "source": [
839
+ "import pandas as pd\n",
840
+ "\n",
841
+ "# Get class names\n",
842
+ "class_names = list(model.names.values())\n",
843
+ "\n",
844
+ "# Get per-class values (already NumPy arrays)\n",
845
+ "p = results.box.p\n",
846
+ "r = results.box.r\n",
847
+ "map50 = results.box.map50\n",
848
+ "map95 = results.box.map\n",
849
+ "\n",
850
+ "# Build DataFrame\n",
851
+ "df_per_class = pd.DataFrame({\n",
852
+ " \"Class\": class_names,\n",
853
+ " \"Precision\": p,\n",
854
+ " \"Recall\": r,\n",
855
+ " \"mAP@0.5\": map50,\n",
856
+ " \"mAP@0.5:0.95\": map95\n",
857
+ "})\n",
858
+ "\n",
859
+ "# Show + save\n",
860
+ "print(\"\\nPer-Class Evaluation Metrics:\")\n",
861
+ "display(df_per_class)\n",
862
+ "df_per_class.to_csv(\"per_class_metrics.csv\", index=False)\n",
863
+ "print(\"✅ Saved to per_class_metrics.csv\")\n"
864
+ ]
865
+ },
866
+ {
867
+ "cell_type": "code",
868
+ "execution_count": null,
869
+ "metadata": {
870
+ "colab": {
871
+ "base_uri": "https://localhost:8080/",
872
+ "height": 17
873
+ },
874
+ "id": "NBQ0qgXrOMbN",
875
+ "outputId": "23d45da3-9549-4c7c-b95d-6a2c12382871"
876
+ },
877
+ "outputs": [
878
+ {
879
+ "data": {
880
+ "application/javascript": "\n async function download(id, filename, size) {\n if (!google.colab.kernel.accessAllowed) {\n return;\n }\n const div = document.createElement('div');\n const label = document.createElement('label');\n label.textContent = `Downloading \"${filename}\": `;\n div.appendChild(label);\n const progress = document.createElement('progress');\n progress.max = size;\n div.appendChild(progress);\n document.body.appendChild(div);\n\n const buffers = [];\n let downloaded = 0;\n\n const channel = await google.colab.kernel.comms.open(id);\n // Send a message to notify the kernel that we're ready.\n channel.send({})\n\n for await (const message of channel.messages) {\n // Send a message to notify the kernel that we're ready.\n channel.send({})\n if (message.buffers) {\n for (const buffer of message.buffers) {\n buffers.push(buffer);\n downloaded += buffer.byteLength;\n progress.value = downloaded;\n }\n }\n }\n const blob = new Blob(buffers, {type: 'application/binary'});\n const a = document.createElement('a');\n a.href = window.URL.createObjectURL(blob);\n a.download = filename;\n div.appendChild(a);\n a.click();\n div.remove();\n }\n ",
881
+ "text/plain": [
882
+ "<IPython.core.display.Javascript object>"
883
+ ]
884
+ },
885
+ "metadata": {},
886
+ "output_type": "display_data"
887
+ },
888
+ {
889
+ "data": {
890
+ "application/javascript": "download(\"download_8d4b5cea-a8f3-46b8-aef5-606799d3bd61\", \"segment.zip\", 5598780)",
891
+ "text/plain": [
892
+ "<IPython.core.display.Javascript object>"
893
+ ]
894
+ },
895
+ "metadata": {},
896
+ "output_type": "display_data"
897
+ }
898
+ ],
899
+ "source": [
900
+ "from google.colab import files\n",
901
+ "import shutil\n",
902
+ "\n",
903
+ "# Zip the folder\n",
904
+ "shutil.make_archive(\"/content/segment\", 'zip', \"/content/runs/segment\")\n",
905
+ "\n",
906
+ "# Download the zip\n",
907
+ "files.download(\"/content/segment.zip\")\n"
908
+ ]
909
+ }
910
+ ],
911
+ "metadata": {
912
+ "accelerator": "GPU",
913
+ "colab": {
914
+ "gpuType": "T4",
915
+ "provenance": []
916
+ },
917
+ "kernelspec": {
918
+ "display_name": "Python 3",
919
+ "name": "python3"
920
+ },
921
+ "language_info": {
922
+ "name": "python"
923
+ }
924
+ },
925
+ "nbformat": 4,
926
+ "nbformat_minor": 0
927
+ }
examples/example_short.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:33dbd88145905ce71bda8725bdc99e1fbfbd911ea5809419fdf1eb9952424fc1
3
+ size 5734442
examples/extract_preprocess_frames.py ADDED
@@ -0,0 +1,399 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ import os
4
+ from PIL import Image, ExifTags
5
+ import random
6
+ import argparse
7
+ import time
8
+
9
+ # Increase OpenCV/FFMPEG frame read retry attempts for long or unstable video reads
10
+ os.environ["OPENCV_FFMPEG_READ_ATTEMPTS"] = "50000"
11
+
12
+ # Default values (can be overridden via command line)
13
+ video_path = "path/to/video.mp4"
14
+ output_dir = "outputs/preprocessed"
15
+
16
+ frame_interval = 30 # Extract every nth frame
17
+ zoom_level = 5.0 # 5x zoom -> crop 1/5 of original frame, then resize to 640x640
18
+ crops_per_frame = 100 # Number of random crops per extracted frame
19
+ manual_crop = False # If True, use one fixed crop position instead of random crops
20
+ crop_x_center = 0.5 # Manual crop center X (relative: 0.0 to 1.0)
21
+ crop_y_center = 0.5 # Manual crop center Y (relative: 0.0 to 1.0)
22
+
23
+
24
+ def extract_and_preprocess_frames(
25
+ video_path,
26
+ output_dir,
27
+ frame_interval=10,
28
+ zoom_level=5.0,
29
+ crops_per_frame=5,
30
+ manual_crop=False,
31
+ crop_x=0.5,
32
+ crop_y=0.5,
33
+ start_frame=0,
34
+ end_frame=None,
35
+ segment_id=0,
36
+ ):
37
+ """
38
+ Extract frames from a video segment and generate zoomed crops.
39
+
40
+ Workflow:
41
+ 1) Read video frames in a specified frame range [start_frame, end_frame)
42
+ 2) Keep every nth frame (frame_interval)
43
+ 3) Optional EXIF-based orientation correction (mostly useful for images, harmless for video frames)
44
+ 4) Crop a zoom window (manual or random position)
45
+ 5) Resize crop to 640x640
46
+ 6) Apply CLAHE contrast enhancement
47
+ 7) Save as JPG with frame and crop position encoded in filename
48
+
49
+ Returns:
50
+ saved_count (int): Number of extracted frames processed (not total crops)
51
+ total_saved (int): Total number of crops saved
52
+ """
53
+ # Create base output directory
54
+ os.makedirs(output_dir, exist_ok=True)
55
+
56
+ # Open video
57
+ cap = cv2.VideoCapture(video_path)
58
+ if not cap.isOpened():
59
+ raise ValueError(f"Could not open video file: {video_path}")
60
+
61
+ # Video metadata
62
+ total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
63
+ fps = cap.get(cv2.CAP_PROP_FPS)
64
+
65
+ # Clamp end_frame to video length
66
+ if end_frame is None or end_frame > total_frames:
67
+ end_frame = total_frames
68
+
69
+ print(f"Video loaded: {video_path}")
70
+ print(f"Total frames: {total_frames}")
71
+ print(f"FPS: {fps}")
72
+ print(f"Processing segment {segment_id + 1}: frames {start_frame} to {end_frame}")
73
+ print(f"Extracting every {frame_interval} frames")
74
+ print(f"Zooming {zoom_level * 100}% and cropping to 640x640")
75
+ print(f"Crops per frame: {crops_per_frame}")
76
+ print(f"Manual crop: {manual_crop}, Position: ({crop_x}, {crop_y})")
77
+
78
+ # CLAHE for local contrast enhancement (helps visibility in crack-like textures)
79
+ clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
80
+
81
+ # Seek to start frame
82
+ cap.set(cv2.CAP_PROP_POS_FRAMES, start_frame)
83
+ count = start_frame
84
+ saved_count = 0 # Counts processed frames (not crops)
85
+
86
+ # Save segment outputs in separate subfolder
87
+ segment_dir = os.path.join(output_dir, f"segment_{segment_id + 1}")
88
+ os.makedirs(segment_dir, exist_ok=True)
89
+
90
+ while count < end_frame:
91
+ ret, frame = cap.read()
92
+ if not ret:
93
+ print(f"Error reading frame at position {count}. Breaking out of loop.")
94
+ break
95
+
96
+ # Process every nth frame inside this segment
97
+ if (count - start_frame) % frame_interval == 0:
98
+ # Convert to PIL for optional EXIF orientation correction
99
+ pil_img = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
100
+
101
+ # EXIF orientation correction (videos usually don't have EXIF, so this often does nothing)
102
+ try:
103
+ orientation_tag = None
104
+ for tag_id, tag_name in ExifTags.TAGS.items():
105
+ if tag_name == "Orientation":
106
+ orientation_tag = tag_id
107
+ break
108
+
109
+ exif = dict(pil_img.getexif().items())
110
+
111
+ if orientation_tag is not None and orientation_tag in exif:
112
+ if exif[orientation_tag] == 3:
113
+ pil_img = pil_img.rotate(180, expand=True)
114
+ elif exif[orientation_tag] == 6:
115
+ pil_img = pil_img.rotate(270, expand=True)
116
+ elif exif[orientation_tag] == 8:
117
+ pil_img = pil_img.rotate(90, expand=True)
118
+ except (AttributeError, KeyError, IndexError, TypeError):
119
+ # No EXIF or EXIF not readable
120
+ pass
121
+
122
+ # Back to OpenCV BGR
123
+ frame = cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGB2BGR)
124
+
125
+ # Original frame size
126
+ height, width = frame.shape[:2]
127
+
128
+ # Compute crop window size from zoom factor
129
+ # Example: zoom=5 -> crop 1/5 width and 1/5 height, then upscale to 640x640
130
+ crop_width = int(width / zoom_level)
131
+ crop_height = int(height / zoom_level)
132
+
133
+ # Safety check for invalid crop sizes
134
+ if crop_width <= 0 or crop_height <= 0:
135
+ print(f"Skipping frame {count}: invalid crop size ({crop_width}, {crop_height})")
136
+ count += 1
137
+ continue
138
+
139
+ if manual_crop:
140
+ # Single deterministic crop at user-defined relative position
141
+ process_crop(
142
+ frame, count, 0, crop_x, crop_y,
143
+ crop_width, crop_height, width, height,
144
+ segment_dir, clahe
145
+ )
146
+ saved_count += 1
147
+ else:
148
+ # Multiple random crops per frame
149
+ for i in range(crops_per_frame):
150
+ # Avoid edges slightly to reduce out-of-frame crop clipping
151
+ random_x = random.uniform(0.1, 0.9)
152
+ random_y = random.uniform(0.1, 0.9)
153
+
154
+ process_crop(
155
+ frame, count, i, random_x, random_y,
156
+ crop_width, crop_height, width, height,
157
+ segment_dir, clahe
158
+ )
159
+ saved_count += 1
160
+
161
+ if saved_count % 10 == 0:
162
+ print(f"Segment {segment_id + 1}: Processed {saved_count} extracted frames (current frame={count})")
163
+
164
+ count += 1
165
+
166
+ cap.release()
167
+
168
+ # Total number of crop images written
169
+ total_saved = saved_count * (1 if manual_crop else crops_per_frame)
170
+
171
+ print(
172
+ f"Segment {segment_id + 1} completed! "
173
+ f"Processed {saved_count} extracted frames and saved {total_saved} crops."
174
+ )
175
+ return saved_count, total_saved
176
+
177
+
178
+ def process_crop(
179
+ frame,
180
+ frame_count,
181
+ crop_index,
182
+ rel_x,
183
+ rel_y,
184
+ crop_width,
185
+ crop_height,
186
+ width,
187
+ height,
188
+ output_dir,
189
+ clahe,
190
+ ):
191
+ """
192
+ Create one crop from a frame, resize to 640x640, enhance contrast, and save.
193
+
194
+ Args:
195
+ rel_x, rel_y: Relative crop center coordinates in [0, 1]
196
+ """
197
+ # Convert relative center coords to pixel coordinates
198
+ center_x = int(rel_x * width)
199
+ center_y = int(rel_y * height)
200
+
201
+ # Top-left crop corner
202
+ start_x = center_x - (crop_width // 2)
203
+ start_y = center_y - (crop_height // 2)
204
+
205
+ # Clamp crop start so crop stays inside frame
206
+ start_x = max(0, min(start_x, width - crop_width))
207
+ start_y = max(0, min(start_y, height - crop_height))
208
+
209
+ # Compute crop end
210
+ end_x = min(start_x + crop_width, width)
211
+ end_y = min(start_y + crop_height, height)
212
+
213
+ # Final adjustment if crop was clipped
214
+ if end_x - start_x < crop_width:
215
+ start_x = max(0, end_x - crop_width)
216
+ if end_y - start_y < crop_height:
217
+ start_y = max(0, end_y - crop_height)
218
+
219
+ try:
220
+ # Crop region from original frame
221
+ cropped = frame[start_y:end_y, start_x:end_x]
222
+
223
+ # Skip empty crops (rare edge case)
224
+ if cropped.size == 0:
225
+ print(f"Empty crop at frame {frame_count}, crop {crop_index}")
226
+ return
227
+
228
+ # Resize to model-friendly input size
229
+ zoomed = cv2.resize(cropped, (640, 640), interpolation=cv2.INTER_LINEAR)
230
+
231
+ # Apply CLAHE
232
+ if len(zoomed.shape) == 3:
233
+ # Color image: apply CLAHE channel-wise in BGR space
234
+ # Note: This may shift colors slightly. For more natural results, apply on LAB L-channel.
235
+ enhanced = cv2.merge([
236
+ clahe.apply(zoomed[:, :, 0]),
237
+ clahe.apply(zoomed[:, :, 1]),
238
+ clahe.apply(zoomed[:, :, 2]),
239
+ ])
240
+ else:
241
+ # Grayscale image
242
+ enhanced = clahe.apply(zoomed)
243
+
244
+ # Filename convention
245
+ # crop_index == 0 is first crop; in manual mode this is the only crop
246
+ if crop_index == 0:
247
+ filename = f"frame5_{frame_count:06d}"
248
+ else:
249
+ filename = f"frame5_{frame_count:06d}_crop{crop_index}"
250
+
251
+ # Encode crop center position (% of frame) for traceability
252
+ pos_info = f"_x{int(rel_x * 100):03d}_y{int(rel_y * 100):03d}"
253
+ frame_filename = os.path.join(output_dir, f"{filename}{pos_info}.jpg")
254
+
255
+ cv2.imwrite(frame_filename, enhanced)
256
+
257
+ except Exception as e:
258
+ print(f"Error processing crop at frame {frame_count}, crop {crop_index}: {e}")
259
+
260
+
261
+ def process_video_in_segments(
262
+ video_path,
263
+ output_dir,
264
+ frame_interval,
265
+ zoom_level,
266
+ crops_per_frame,
267
+ manual_crop,
268
+ crop_x,
269
+ crop_y,
270
+ segment_size=5000,
271
+ overlap=100,
272
+ ):
273
+ """
274
+ Process video in segments to avoid memory/decoder instability on long videos.
275
+
276
+ Note:
277
+ - Overlap can help avoid missing frames near segment boundaries.
278
+ - But overlap can also create duplicate outputs if the same frame is processed in two segments.
279
+ """
280
+ cap = cv2.VideoCapture(video_path)
281
+ if not cap.isOpened():
282
+ raise ValueError(f"Could not open video file: {video_path}")
283
+
284
+ total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
285
+ cap.release()
286
+
287
+ print(f"Total frames in video: {total_frames}")
288
+ print(f"Processing in segments of {segment_size} frames with {overlap} frame overlap")
289
+
290
+ # Prevent invalid step size
291
+ if segment_size <= overlap:
292
+ raise ValueError("segment_size must be greater than overlap")
293
+
294
+ # Segment start indices
295
+ start_frames = list(range(0, total_frames, segment_size - overlap))
296
+
297
+ total_frames_processed = 0 # processed extracted frames
298
+ total_crops_processed = 0 # saved crop images
299
+
300
+ for i, start_frame in enumerate(start_frames):
301
+ end_frame = min(start_frame + segment_size, total_frames)
302
+
303
+ print(f"\n{'=' * 80}")
304
+ print(f"Processing segment {i + 1}/{len(start_frames)}: frames {start_frame} to {end_frame}")
305
+ print(f"{'=' * 80}\n")
306
+
307
+ # Small pause between segments (helps file handles / decoder stability)
308
+ if i > 0:
309
+ time.sleep(2)
310
+
311
+ try:
312
+ frames_processed, crops_processed = extract_and_preprocess_frames(
313
+ video_path=video_path,
314
+ output_dir=output_dir,
315
+ frame_interval=frame_interval,
316
+ zoom_level=zoom_level,
317
+ crops_per_frame=crops_per_frame,
318
+ manual_crop=manual_crop,
319
+ crop_x=crop_x,
320
+ crop_y=crop_y,
321
+ start_frame=start_frame,
322
+ end_frame=end_frame,
323
+ segment_id=i,
324
+ )
325
+
326
+ total_frames_processed += frames_processed
327
+ total_crops_processed += crops_processed
328
+
329
+ except Exception as e:
330
+ print(f"Error processing segment {i + 1}: {e}")
331
+ print("Continuing with next segment...")
332
+
333
+ print(f"\n{'=' * 80}")
334
+ print(
335
+ f"Processing complete! "
336
+ f"Processed {total_frames_processed} extracted frames and saved {total_crops_processed} crops."
337
+ )
338
+ print(f"{'=' * 80}")
339
+
340
+
341
+ if __name__ == "__main__":
342
+ parser = argparse.ArgumentParser(
343
+ description="Extract frames from a video and generate zoomed crops with optional CLAHE enhancement"
344
+ )
345
+
346
+ # Input/output
347
+ parser.add_argument("--video", type=str, default=video_path, help="Path to input video")
348
+ parser.add_argument("--output", type=str, default=output_dir, help="Directory to save processed crops")
349
+
350
+ # Extraction/cropping settings
351
+ parser.add_argument("--interval", type=int, default=frame_interval, help="Extract every nth frame")
352
+ parser.add_argument("--zoom", type=float, default=zoom_level, help="Zoom factor (e.g., 5.0 = 500%%)")
353
+ parser.add_argument("--crops", type=int, default=crops_per_frame, help="Random crops per extracted frame")
354
+ parser.add_argument("--manual", action="store_true", help="Use one manual crop position instead of random crops")
355
+ parser.add_argument("--crop_x", type=float, default=crop_x_center, help="Manual crop center X in [0,1]")
356
+ parser.add_argument("--crop_y", type=float, default=crop_y_center, help="Manual crop center Y in [0,1]")
357
+
358
+ # Segmentation settings (for long videos)
359
+ parser.add_argument("--segment_size", type=int, default=5000, help="Frames per segment")
360
+ parser.add_argument("--overlap", type=int, default=100, help="Segment overlap in frames")
361
+
362
+ args = parser.parse_args()
363
+
364
+ # Basic input validation
365
+ if not args.video or not os.path.isfile(args.video):
366
+ print(f"Error: Video file '{args.video}' does not exist.")
367
+ raise SystemExit(1)
368
+
369
+ if args.interval <= 0:
370
+ print("Error: --interval must be > 0")
371
+ raise SystemExit(1)
372
+
373
+ if args.zoom <= 0:
374
+ print("Error: --zoom must be > 0")
375
+ raise SystemExit(1)
376
+
377
+ if args.crops <= 0 and not args.manual:
378
+ print("Error: --crops must be > 0 when not using --manual")
379
+ raise SystemExit(1)
380
+
381
+ if not (0.0 <= args.crop_x <= 1.0 and 0.0 <= args.crop_y <= 1.0):
382
+ print("Error: --crop_x and --crop_y must be in [0,1]")
383
+ raise SystemExit(1)
384
+
385
+ try:
386
+ process_video_in_segments(
387
+ video_path=args.video,
388
+ output_dir=args.output,
389
+ frame_interval=args.interval,
390
+ zoom_level=args.zoom,
391
+ crops_per_frame=args.crops,
392
+ manual_crop=args.manual,
393
+ crop_x=args.crop_x,
394
+ crop_y=args.crop_y,
395
+ segment_size=args.segment_size,
396
+ overlap=args.overlap,
397
+ )
398
+ except Exception as e:
399
+ print(f"An error occurred: {e}")
examples/output_with_cracks.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3f68b63e86601fb794a33a5e4717c597ea3645dfaafb8c56f67d71c35a2fb991
3
+ size 83835266