rick003 commited on
Commit
204c94e
·
verified ·
1 Parent(s): 2a71c33

Add files using upload-large-folder tool

Browse files
Files changed (50) hide show
  1. notebooks/colab_gas_valve_auto_label_train.ipynb +970 -0
  2. notebooks/colab_gas_valve_auto_label_train.py +823 -0
  3. raw/valve/Pic_阀门_1.txt +1 -0
  4. raw/valve/Pic_阀门_10.txt +1 -0
  5. raw/valve/Pic_阀门_100.txt +1 -0
  6. raw/valve/Pic_阀门_101.txt +1 -0
  7. raw/valve/Pic_阀门_102.txt +1 -0
  8. raw/valve/Pic_阀门_103.txt +1 -0
  9. raw/valve/Pic_阀门_104.txt +1 -0
  10. raw/valve/Pic_阀门_105.txt +1 -0
  11. raw/valve/Pic_阀门_106.txt +1 -0
  12. raw/valve/Pic_阀门_107.txt +1 -0
  13. raw/valve/Pic_阀门_108.txt +1 -0
  14. raw/valve/Pic_阀门_11.txt +1 -0
  15. raw/valve/Pic_阀门_110.txt +1 -0
  16. raw/valve/Pic_阀门_111.txt +1 -0
  17. raw/valve/Pic_阀门_112.txt +1 -0
  18. raw/valve/Pic_阀门_113.txt +1 -0
  19. raw/valve/Pic_阀门_114.txt +1 -0
  20. raw/valve/Pic_阀门_115.txt +1 -0
  21. raw/valve/Pic_阀门_116.txt +1 -0
  22. raw/valve/Pic_阀门_117.txt +1 -0
  23. raw/valve/Pic_阀门_118.txt +1 -0
  24. raw/valve/Pic_阀门_119.txt +1 -0
  25. raw/valve/Pic_阀门_12.txt +1 -0
  26. raw/valve/Pic_阀门_120.txt +1 -0
  27. raw/valve/Pic_阀门_121.txt +1 -0
  28. raw/valve/Pic_阀门_122.txt +1 -0
  29. raw/valve/Pic_阀门_123.txt +1 -0
  30. raw/valve/Pic_阀门_124.txt +1 -0
  31. raw/valve/Pic_阀门_13.txt +1 -0
  32. raw/valve/Pic_阀门_14.txt +1 -0
  33. raw/valve/Pic_阀门_15.txt +1 -0
  34. raw/valve/Pic_阀门_16.txt +1 -0
  35. raw/valve/Pic_阀门_17.txt +1 -0
  36. raw/valve/Pic_阀门_18.txt +1 -0
  37. raw/valve/Pic_阀门_19.txt +1 -0
  38. raw/valve/Pic_阀门_2.txt +1 -0
  39. raw/valve/Pic_阀门_20.txt +1 -0
  40. raw/valve/Pic_阀门_21.txt +1 -0
  41. raw/valve/Pic_阀门_22.txt +1 -0
  42. raw/valve/Pic_阀门_23.txt +1 -0
  43. raw/valve/Pic_阀门_24.txt +1 -0
  44. raw/valve/Pic_阀门_25.txt +1 -0
  45. raw/valve/Pic_阀门_26.txt +1 -0
  46. raw/valve/Pic_阀门_27.txt +1 -0
  47. raw/valve/Pic_阀门_28.txt +1 -0
  48. raw/valve/Pic_阀门_29.txt +1 -0
  49. raw/valve/Pic_阀门_3.txt +1 -0
  50. scripts/process_valve_to_polygon.py +2381 -0
notebooks/colab_gas_valve_auto_label_train.ipynb ADDED
@@ -0,0 +1,970 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "colab": {
6
+ "provenance": [],
7
+ "gpuType": "T4",
8
+ "toc_visible": true
9
+ },
10
+ "kernelspec": {
11
+ "name": "python3",
12
+ "display_name": "Python 3"
13
+ },
14
+ "language_info": {
15
+ "name": "python",
16
+ "version": "3.10.0"
17
+ },
18
+ "accelerator": "GPU"
19
+ },
20
+ "cells": [
21
+ {
22
+ "cell_type": "markdown",
23
+ "metadata": {},
24
+ "source": [
25
+ "# Gas + valve auto-labeling and training\n",
26
+ "\n",
27
+ "This notebook expects the HuggingFace dataset repo to contain:\n",
28
+ "\n",
29
+ "- `images/train/` and `labels/train/`: existing gas-cylinder labels\n",
30
+ "- `raw/valve/`: valve images plus bbox `.txt` priors\n",
31
+ "- `raw/gas_extra/`: extra gas-cylinder images\n",
32
+ "- `scripts/process_valve_to_polygon.py`: valve polygon auto-label script\n",
33
+ "\n",
34
+ "Class mapping:\n",
35
+ "\n",
36
+ "- `0`: `gas_cylinder`\n",
37
+ "- `1`: `valve`"
38
+ ]
39
+ },
40
+ {
41
+ "cell_type": "markdown",
42
+ "metadata": {},
43
+ "source": [
44
+ "---\n",
45
+ "## Step 1 - Install dependencies"
46
+ ]
47
+ },
48
+ {
49
+ "cell_type": "code",
50
+ "execution_count": null,
51
+ "metadata": {
52
+ "cellView": "form"
53
+ },
54
+ "outputs": [],
55
+ "source": [
56
+ "# @title Step 1 - Install dependencies\n",
57
+ "\n",
58
+ "get_ipython().system(\n",
59
+ " \"pip install -q ultralytics huggingface_hub opencv-python-headless \"\n",
60
+ " \"tqdm pyyaml matplotlib pandas\"\n",
61
+ ")\n",
62
+ "\n",
63
+ "import os\n",
64
+ "import sys\n",
65
+ "import time\n",
66
+ "import shutil\n",
67
+ "import random\n",
68
+ "import subprocess\n",
69
+ "from pathlib import Path\n",
70
+ "\n",
71
+ "import cv2\n",
72
+ "import yaml\n",
73
+ "import torch\n",
74
+ "import numpy as np\n",
75
+ "import matplotlib.pyplot as plt\n",
76
+ "\n",
77
+ "from tqdm.notebook import tqdm\n",
78
+ "from huggingface_hub import (\n",
79
+ " HfApi,\n",
80
+ " login,\n",
81
+ " snapshot_download,\n",
82
+ " CommitOperationAdd,\n",
83
+ ")\n",
84
+ "\n",
85
+ "print(\"Dependencies installed\")\n",
86
+ "print(f\"Python: {sys.version.split()[0]}\")\n",
87
+ "print(f\"PyTorch: {torch.__version__}\")\n",
88
+ "print(f\"CUDA available: {torch.cuda.is_available()}\")\n",
89
+ "if torch.cuda.is_available():\n",
90
+ " print(f\"GPU: {torch.cuda.get_device_name(0)}\")"
91
+ ]
92
+ },
93
+ {
94
+ "cell_type": "markdown",
95
+ "metadata": {},
96
+ "source": [
97
+ "---\n",
98
+ "## Step 2 - HuggingFace authentication"
99
+ ]
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "execution_count": null,
104
+ "metadata": {
105
+ "cellView": "form"
106
+ },
107
+ "outputs": [],
108
+ "source": [
109
+ "# @title Step 2 - HuggingFace authentication\n",
110
+ "# @markdown Token needs write permission if you want to upload generated labels and training results.\n",
111
+ "\n",
112
+ "HF_TOKEN = \"\" # @param {type:\"string\"}\n",
113
+ "DATASET_REPO = \"rick003/11111\" # @param {type:\"string\"}\n",
114
+ "\n",
115
+ "if not HF_TOKEN:\n",
116
+ " from getpass import getpass\n",
117
+ "\n",
118
+ " HF_TOKEN = getpass(\"HuggingFace token: \")\n",
119
+ "\n",
120
+ "if not HF_TOKEN:\n",
121
+ " raise ValueError(\"HF_TOKEN is required\")\n",
122
+ "\n",
123
+ "login(token=HF_TOKEN, add_to_git_credential=False)\n",
124
+ "api = HfApi()\n",
125
+ "api.dataset_info(DATASET_REPO, token=HF_TOKEN)\n",
126
+ "\n",
127
+ "print(\"HuggingFace authentication OK\")\n",
128
+ "print(f\"Dataset: https://huggingface.co/datasets/{DATASET_REPO}\")"
129
+ ]
130
+ },
131
+ {
132
+ "cell_type": "markdown",
133
+ "metadata": {},
134
+ "source": [
135
+ "---\n",
136
+ "## Step 3 - Download required files"
137
+ ]
138
+ },
139
+ {
140
+ "cell_type": "code",
141
+ "execution_count": null,
142
+ "metadata": {
143
+ "cellView": "form"
144
+ },
145
+ "outputs": [],
146
+ "source": [
147
+ "# @title Step 3 - Download required files\n",
148
+ "# @markdown Downloads only the files needed for joint labeling/training.\n",
149
+ "\n",
150
+ "DATASET_LOCAL = \"/content/hf_11111\" # @param {type:\"string\"}\n",
151
+ "RAW_VALVE_PREFIX = \"raw/valve\"\n",
152
+ "RAW_GAS_EXTRA_PREFIX = \"raw/gas_extra\"\n",
153
+ "PROCESS_SCRIPT_REPO_PATH = \"scripts/process_valve_to_polygon.py\"\n",
154
+ "FORCE_REDOWNLOAD = False # @param {type:\"boolean\"}\n",
155
+ "\n",
156
+ "base = Path(DATASET_LOCAL)\n",
157
+ "if FORCE_REDOWNLOAD and base.exists():\n",
158
+ " shutil.rmtree(base)\n",
159
+ "\n",
160
+ "allow_patterns = [\n",
161
+ " \"images/train/**\",\n",
162
+ " \"labels/train/**\",\n",
163
+ " f\"{RAW_VALVE_PREFIX}/**\",\n",
164
+ " f\"{RAW_GAS_EXTRA_PREFIX}/**\",\n",
165
+ " PROCESS_SCRIPT_REPO_PATH,\n",
166
+ " \"dataset.yaml\",\n",
167
+ "]\n",
168
+ "\n",
169
+ "print(f\"Downloading dataset files to {DATASET_LOCAL}\")\n",
170
+ "snapshot_download(\n",
171
+ " repo_id=DATASET_REPO,\n",
172
+ " repo_type=\"dataset\",\n",
173
+ " token=HF_TOKEN,\n",
174
+ " local_dir=DATASET_LOCAL,\n",
175
+ " allow_patterns=allow_patterns,\n",
176
+ " ignore_patterns=[\"runs/**\", \"preview/**\", \"*.cache\", \".git/**\"],\n",
177
+ ")\n",
178
+ "\n",
179
+ "RAW_VALVE_DIR = base / RAW_VALVE_PREFIX\n",
180
+ "RAW_GAS_EXTRA_DIR = base / RAW_GAS_EXTRA_PREFIX\n",
181
+ "PROCESS_SCRIPT_LOCAL = base / PROCESS_SCRIPT_REPO_PATH\n",
182
+ "\n",
183
+ "print(\"Download summary\")\n",
184
+ "for p in [base / \"images/train\", base / \"labels/train\", RAW_VALVE_DIR, RAW_GAS_EXTRA_DIR]:\n",
185
+ " n = len(list(p.glob(\"*\"))) if p.exists() else 0\n",
186
+ " print(f\" {p}: {n} entries\")\n",
187
+ "\n",
188
+ "if not RAW_VALVE_DIR.exists():\n",
189
+ " raise FileNotFoundError(f\"Missing {RAW_VALVE_PREFIX} in HF dataset\")\n",
190
+ "if not RAW_GAS_EXTRA_DIR.exists():\n",
191
+ " raise FileNotFoundError(f\"Missing {RAW_GAS_EXTRA_PREFIX} in HF dataset\")\n",
192
+ "if not PROCESS_SCRIPT_LOCAL.exists():\n",
193
+ " raise FileNotFoundError(\n",
194
+ " f\"Missing {PROCESS_SCRIPT_REPO_PATH}. Upload process_valve_to_polygon.py \"\n",
195
+ " \"to this path before running valve auto-labeling.\"\n",
196
+ " )"
197
+ ]
198
+ },
199
+ {
200
+ "cell_type": "markdown",
201
+ "metadata": {},
202
+ "source": [
203
+ "---\n",
204
+ "## Step 4 - Shared helpers"
205
+ ]
206
+ },
207
+ {
208
+ "cell_type": "code",
209
+ "execution_count": null,
210
+ "metadata": {
211
+ "cellView": "form"
212
+ },
213
+ "outputs": [],
214
+ "source": [
215
+ "# @title Step 4 - Shared helpers\n",
216
+ "\n",
217
+ "IMG_EXTS = {\".png\", \".jpg\", \".jpeg\", \".bmp\", \".webp\"}\n",
218
+ "WORK_DIR = Path(\"/content/gas_valve_work\")\n",
219
+ "LABEL_WORK_DIR = WORK_DIR / \"labels\"\n",
220
+ "VIS_WORK_DIR = WORK_DIR / \"visual\"\n",
221
+ "for d in [LABEL_WORK_DIR, VIS_WORK_DIR]:\n",
222
+ " d.mkdir(parents=True, exist_ok=True)\n",
223
+ "\n",
224
+ "\n",
225
+ "def list_images(folder: Path) -> list[Path]:\n",
226
+ " if not folder.exists():\n",
227
+ " return []\n",
228
+ " return sorted(\n",
229
+ " p for p in folder.iterdir()\n",
230
+ " if p.is_file() and p.suffix.lower() in IMG_EXTS\n",
231
+ " )\n",
232
+ "\n",
233
+ "\n",
234
+ "def find_image_by_stem(folder: Path, stem: str) -> Path | None:\n",
235
+ " for ext in IMG_EXTS:\n",
236
+ " p = folder / f\"{stem}{ext}\"\n",
237
+ " if p.exists():\n",
238
+ " return p\n",
239
+ " for p in folder.glob(f\"{stem}.*\"):\n",
240
+ " if p.suffix.lower() in IMG_EXTS:\n",
241
+ " return p\n",
242
+ " return None\n",
243
+ "\n",
244
+ "\n",
245
+ "def read_image(path: Path) -> np.ndarray | None:\n",
246
+ " raw = np.fromfile(str(path), dtype=np.uint8)\n",
247
+ " if raw.size == 0:\n",
248
+ " return None\n",
249
+ " return cv2.imdecode(raw, cv2.IMREAD_COLOR)\n",
250
+ "\n",
251
+ "\n",
252
+ "def valid_seg_lines(label_path: Path, allowed_classes: set[int] | None = None) -> list[str]:\n",
253
+ " if not label_path.exists():\n",
254
+ " return []\n",
255
+ " text = label_path.read_text(encoding=\"utf-8\", errors=\"ignore\").strip()\n",
256
+ " if not text:\n",
257
+ " return []\n",
258
+ "\n",
259
+ " lines: list[str] = []\n",
260
+ " for raw_line in text.splitlines():\n",
261
+ " parts = raw_line.strip().split()\n",
262
+ " if len(parts) < 7:\n",
263
+ " continue\n",
264
+ " try:\n",
265
+ " cls = int(float(parts[0]))\n",
266
+ " coords = [float(v) for v in parts[1:]]\n",
267
+ " except ValueError:\n",
268
+ " continue\n",
269
+ " if allowed_classes is not None and cls not in allowed_classes:\n",
270
+ " continue\n",
271
+ " if len(coords) < 6 or len(coords) % 2 != 0:\n",
272
+ " continue\n",
273
+ " coords = [min(1.0, max(0.0, v)) for v in coords]\n",
274
+ " out = [str(cls)] + [f\"{v:.6f}\" for v in coords]\n",
275
+ " lines.append(\" \".join(out))\n",
276
+ " return lines\n",
277
+ "\n",
278
+ "\n",
279
+ "def write_lines(path: Path, lines: list[str]) -> None:\n",
280
+ " path.parent.mkdir(parents=True, exist_ok=True)\n",
281
+ " path.write_text(\"\\n\".join(lines).strip() + (\"\\n\" if lines else \"\"), encoding=\"utf-8\")\n",
282
+ "\n",
283
+ "\n",
284
+ "def class_counts(label_files: list[Path]) -> dict[int, int]:\n",
285
+ " counts: dict[int, int] = {}\n",
286
+ " for p in label_files:\n",
287
+ " for line in p.read_text(encoding=\"utf-8\", errors=\"ignore\").splitlines():\n",
288
+ " parts = line.strip().split()\n",
289
+ " if not parts:\n",
290
+ " continue\n",
291
+ " try:\n",
292
+ " cls = int(float(parts[0]))\n",
293
+ " except ValueError:\n",
294
+ " continue\n",
295
+ " counts[cls] = counts.get(cls, 0) + 1\n",
296
+ " return counts\n",
297
+ "\n",
298
+ "\n",
299
+ "print(f\"Old train images: {len(list_images(base / 'images/train'))}\")\n",
300
+ "print(f\"Old train labels: {len(list((base / 'labels/train').glob('*.txt')))}\")\n",
301
+ "print(f\"Raw valve images: {len(list_images(RAW_VALVE_DIR))}\")\n",
302
+ "print(f\"Raw gas-extra images: {len(list_images(RAW_GAS_EXTRA_DIR))}\")"
303
+ ]
304
+ },
305
+ {
306
+ "cell_type": "markdown",
307
+ "metadata": {},
308
+ "source": [
309
+ "---\n",
310
+ "## Step 5 - Gas-cylinder auto-labeler"
311
+ ]
312
+ },
313
+ {
314
+ "cell_type": "code",
315
+ "execution_count": null,
316
+ "metadata": {
317
+ "cellView": "form"
318
+ },
319
+ "outputs": [],
320
+ "source": [
321
+ "# @title Step 5 - Gas-cylinder auto-labeler\n",
322
+ "\n",
323
+ "\n",
324
+ "class GasCylinderSegmenter:\n",
325
+ " CLASS_WEIGHTS = {\n",
326
+ " 39: 2.0, # bottle\n",
327
+ " 10: 1.0, # fire hydrant\n",
328
+ " 71: 1.0, # sink\n",
329
+ " 61: 1.0, # toilet\n",
330
+ " 41: 0.8, # cup\n",
331
+ " 56: 0.8, # chair\n",
332
+ " 75: 0.8, # vase\n",
333
+ " }\n",
334
+ "\n",
335
+ " def __init__(self, model_path: str = \"yolo11x-seg.pt\", class_id: int = 0) -> None:\n",
336
+ " from ultralytics import YOLO\n",
337
+ "\n",
338
+ " self.device = \"0\" if torch.cuda.is_available() else \"cpu\"\n",
339
+ " self.class_id = class_id\n",
340
+ " self.model = YOLO(model_path)\n",
341
+ " self.conf = 0.01\n",
342
+ " self.min_area = 0.03\n",
343
+ " self.max_dist = 0.35\n",
344
+ " print(f\"Gas label model: {model_path}, device={self.device}, class_id={class_id}\")\n",
345
+ "\n",
346
+ " def annotate(self, img: np.ndarray) -> tuple[str, bool]:\n",
347
+ " h, w = img.shape[:2]\n",
348
+ " cx, cy = w / 2.0, h / 2.0\n",
349
+ " area = float(w * h)\n",
350
+ " diag = float(w * w + h * h) ** 0.5\n",
351
+ "\n",
352
+ " result = self.model(img, conf=self.conf, device=self.device, verbose=False)[0]\n",
353
+ " candidates = []\n",
354
+ "\n",
355
+ " if result.masks is not None:\n",
356
+ " for i in range(len(result.masks.data)):\n",
357
+ " cls_id = int(result.boxes.cls[i])\n",
358
+ " if cls_id not in self.CLASS_WEIGHTS:\n",
359
+ " continue\n",
360
+ "\n",
361
+ " conf = float(result.boxes.conf[i])\n",
362
+ " x1, y1, x2, y2 = result.boxes.xyxy[i].tolist()\n",
363
+ " box_cx = (x1 + x2) / 2.0\n",
364
+ " box_cy = (y1 + y2) / 2.0\n",
365
+ " area_ratio = (x2 - x1) * (y2 - y1) / area\n",
366
+ " dist_ratio = ((box_cx - cx) ** 2 + (box_cy - cy) ** 2) ** 0.5 / diag\n",
367
+ "\n",
368
+ " if area_ratio < self.min_area or dist_ratio > self.max_dist:\n",
369
+ " continue\n",
370
+ "\n",
371
+ " centrality_bonus = 1.0 + (1.0 - dist_ratio / self.max_dist)\n",
372
+ " score = conf * self.CLASS_WEIGHTS[cls_id] * centrality_bonus\n",
373
+ " candidates.append((score, result.masks.xyn[i]))\n",
374
+ "\n",
375
+ " if not candidates:\n",
376
+ " return \"\", False\n",
377
+ "\n",
378
+ " _, poly = max(candidates, key=lambda x: x[0])\n",
379
+ " if len(poly) < 3:\n",
380
+ " return \"\", False\n",
381
+ "\n",
382
+ " tokens = [str(self.class_id)]\n",
383
+ " for x, y in poly:\n",
384
+ " tokens.append(f\"{float(x):.6f}\")\n",
385
+ " tokens.append(f\"{float(y):.6f}\")\n",
386
+ " return \" \".join(tokens), True\n",
387
+ "\n",
388
+ "\n",
389
+ "def auto_label_gas_folder(\n",
390
+ " segmenter: GasCylinderSegmenter,\n",
391
+ " image_dir: Path,\n",
392
+ " labels_dir: Path,\n",
393
+ " *,\n",
394
+ " overwrite: bool = False,\n",
395
+ " limit: int = 0,\n",
396
+ ") -> dict[str, int]:\n",
397
+ " labels_dir.mkdir(parents=True, exist_ok=True)\n",
398
+ " images = list_images(image_dir)\n",
399
+ " if limit > 0:\n",
400
+ " images = images[:limit]\n",
401
+ "\n",
402
+ " stats = {\"ok\": 0, \"failed\": 0, \"error\": 0, \"skipped\": 0}\n",
403
+ " for image_path in tqdm(images, desc=f\"Gas labels: {image_dir.name}\"):\n",
404
+ " label_path = labels_dir / f\"{image_path.stem}.txt\"\n",
405
+ " if label_path.exists() and label_path.stat().st_size > 0 and not overwrite:\n",
406
+ " stats[\"skipped\"] += 1\n",
407
+ " continue\n",
408
+ "\n",
409
+ " img = read_image(image_path)\n",
410
+ " if img is None:\n",
411
+ " write_lines(label_path, [])\n",
412
+ " stats[\"error\"] += 1\n",
413
+ " continue\n",
414
+ "\n",
415
+ " try:\n",
416
+ " label, ok = segmenter.annotate(img)\n",
417
+ " write_lines(label_path, [label] if ok else [])\n",
418
+ " stats[\"ok\" if ok else \"failed\"] += 1\n",
419
+ " except Exception as exc:\n",
420
+ " print(f\"Gas label error: {image_path.name}: {exc}\")\n",
421
+ " write_lines(label_path, [])\n",
422
+ " stats[\"error\"] += 1\n",
423
+ "\n",
424
+ " print(f\"{image_dir.name}: {stats}\")\n",
425
+ " return stats"
426
+ ]
427
+ },
428
+ {
429
+ "cell_type": "markdown",
430
+ "metadata": {},
431
+ "source": [
432
+ "---\n",
433
+ "## Step 6 - Auto-label new gas data"
434
+ ]
435
+ },
436
+ {
437
+ "cell_type": "code",
438
+ "execution_count": null,
439
+ "metadata": {
440
+ "cellView": "form"
441
+ },
442
+ "outputs": [],
443
+ "source": [
444
+ "# @title Step 6 - Auto-label new gas data\n",
445
+ "# @markdown Gas labels are generated for both extra gas images and valve images.\n",
446
+ "# @markdown The valve-image gas labels prevent visible gas cylinders from being treated as background.\n",
447
+ "\n",
448
+ "GAS_LABEL_MODEL = \"yolo11x-seg.pt\" # @param [\"yolo11n-seg.pt\",\"yolo11m-seg.pt\",\"yolo11x-seg.pt\"]\n",
449
+ "REGENERATE_GAS_LABELS = False # @param {type:\"boolean\"}\n",
450
+ "GAS_LABEL_LIMIT = 0 # @param {type:\"integer\"}\n",
451
+ "\n",
452
+ "GAS_EXTRA_LABEL_DIR = LABEL_WORK_DIR / \"gas_extra\"\n",
453
+ "VALVE_GAS_LABEL_DIR = LABEL_WORK_DIR / \"valve_gas\"\n",
454
+ "\n",
455
+ "gas_segmenter = GasCylinderSegmenter(GAS_LABEL_MODEL, class_id=0)\n",
456
+ "gas_extra_stats = auto_label_gas_folder(\n",
457
+ " gas_segmenter,\n",
458
+ " RAW_GAS_EXTRA_DIR,\n",
459
+ " GAS_EXTRA_LABEL_DIR,\n",
460
+ " overwrite=REGENERATE_GAS_LABELS,\n",
461
+ " limit=GAS_LABEL_LIMIT,\n",
462
+ ")\n",
463
+ "valve_gas_stats = auto_label_gas_folder(\n",
464
+ " gas_segmenter,\n",
465
+ " RAW_VALVE_DIR,\n",
466
+ " VALVE_GAS_LABEL_DIR,\n",
467
+ " overwrite=REGENERATE_GAS_LABELS,\n",
468
+ " limit=GAS_LABEL_LIMIT,\n",
469
+ ")"
470
+ ]
471
+ },
472
+ {
473
+ "cell_type": "markdown",
474
+ "metadata": {},
475
+ "source": [
476
+ "---\n",
477
+ "## Step 7 - Auto-label valve polygons"
478
+ ]
479
+ },
480
+ {
481
+ "cell_type": "code",
482
+ "execution_count": null,
483
+ "metadata": {
484
+ "cellView": "form"
485
+ },
486
+ "outputs": [],
487
+ "source": [
488
+ "# @title Step 7 - Auto-label valve polygons\n",
489
+ "# @markdown Uses `process_valve_to_polygon.py` and the bbox `.txt` priors in `raw/valve/`.\n",
490
+ "\n",
491
+ "VALVE_LABEL_MODEL = \"yolo11x-seg.pt\" # @param [\"yolo11n-seg.pt\",\"yolo11m-seg.pt\",\"yolo11x-seg.pt\"]\n",
492
+ "REGENERATE_VALVE_LABELS = False # @param {type:\"boolean\"}\n",
493
+ "SAVE_VALVE_VISUALIZATIONS = False # @param {type:\"boolean\"}\n",
494
+ "VALVE_LABEL_LIMIT = 0 # @param {type:\"integer\"}\n",
495
+ "\n",
496
+ "VALVE_LABEL_DIR = LABEL_WORK_DIR / \"valve\"\n",
497
+ "VALVE_VIS_DIR = VIS_WORK_DIR / \"valve\"\n",
498
+ "VALVE_LABEL_DIR.mkdir(parents=True, exist_ok=True)\n",
499
+ "VALVE_VIS_DIR.mkdir(parents=True, exist_ok=True)\n",
500
+ "\n",
501
+ "device = \"0\" if torch.cuda.is_available() else \"cpu\"\n",
502
+ "cmd = [\n",
503
+ " sys.executable,\n",
504
+ " str(PROCESS_SCRIPT_LOCAL),\n",
505
+ " \"--image-dir\",\n",
506
+ " str(RAW_VALVE_DIR),\n",
507
+ " \"--labels-dir\",\n",
508
+ " str(VALVE_LABEL_DIR),\n",
509
+ " \"--vis-dir\",\n",
510
+ " str(VALVE_VIS_DIR),\n",
511
+ " \"--bbox-dir\",\n",
512
+ " str(RAW_VALVE_DIR),\n",
513
+ " \"--class-id\",\n",
514
+ " \"1\",\n",
515
+ " \"--model\",\n",
516
+ " VALVE_LABEL_MODEL,\n",
517
+ " \"--device\",\n",
518
+ " device,\n",
519
+ "]\n",
520
+ "if REGENERATE_VALVE_LABELS:\n",
521
+ " cmd.append(\"--overwrite\")\n",
522
+ "if not SAVE_VALVE_VISUALIZATIONS:\n",
523
+ " cmd.append(\"--skip-visualizations\")\n",
524
+ "if VALVE_LABEL_LIMIT > 0:\n",
525
+ " cmd.extend([\"--limit\", str(VALVE_LABEL_LIMIT)])\n",
526
+ "\n",
527
+ "print(\"Running valve auto-labeler\")\n",
528
+ "print(\" \".join(cmd))\n",
529
+ "subprocess.run(cmd, check=True)\n",
530
+ "\n",
531
+ "valve_labels = list(VALVE_LABEL_DIR.glob(\"*.txt\"))\n",
532
+ "print(f\"Valve label files: {len(valve_labels)}\")\n",
533
+ "print(f\"Valve non-empty labels: {sum(1 for p in valve_labels if p.stat().st_size > 0)}\")"
534
+ ]
535
+ },
536
+ {
537
+ "cell_type": "markdown",
538
+ "metadata": {},
539
+ "source": [
540
+ "---\n",
541
+ "## Step 8 - Optionally upload generated labels"
542
+ ]
543
+ },
544
+ {
545
+ "cell_type": "code",
546
+ "execution_count": null,
547
+ "metadata": {
548
+ "cellView": "form"
549
+ },
550
+ "outputs": [],
551
+ "source": [
552
+ "# @title Step 8 - Optionally upload generated labels\n",
553
+ "# @markdown Uploads generated labels under `auto_labels/gas_valve_v1/`.\n",
554
+ "\n",
555
+ "UPLOAD_GENERATED_LABELS = True # @param {type:\"boolean\"}\n",
556
+ "GENERATED_LABELS_REPO_DIR = \"auto_labels/gas_valve_v1\" # @param {type:\"string\"}\n",
557
+ "\n",
558
+ "if UPLOAD_GENERATED_LABELS:\n",
559
+ " print(f\"Uploading generated labels to {GENERATED_LABELS_REPO_DIR}\")\n",
560
+ " api.upload_folder(\n",
561
+ " repo_id=DATASET_REPO,\n",
562
+ " repo_type=\"dataset\",\n",
563
+ " token=HF_TOKEN,\n",
564
+ " folder_path=str(LABEL_WORK_DIR),\n",
565
+ " path_in_repo=GENERATED_LABELS_REPO_DIR,\n",
566
+ " commit_message=\"upload_generated_gas_valve_labels\",\n",
567
+ " )\n",
568
+ " print(\"Generated labels uploaded\")\n",
569
+ "else:\n",
570
+ " print(\"Skipping generated label upload\")"
571
+ ]
572
+ },
573
+ {
574
+ "cell_type": "markdown",
575
+ "metadata": {},
576
+ "source": [
577
+ "---\n",
578
+ "## Step 9 - Build the two-class training dataset"
579
+ ]
580
+ },
581
+ {
582
+ "cell_type": "code",
583
+ "execution_count": null,
584
+ "metadata": {
585
+ "cellView": "form"
586
+ },
587
+ "outputs": [],
588
+ "source": [
589
+ "# @title Step 9 - Build the two-class training dataset\n",
590
+ "\n",
591
+ "COMBINED_DATASET = Path(\"/content/gas_valve_dataset\")\n",
592
+ "VAL_RATIO = 0.20 # @param {type:\"number\"}\n",
593
+ "RANDOM_SEED = 42 # @param {type:\"integer\"}\n",
594
+ "INCLUDE_OLD_GAS_DATA = True # @param {type:\"boolean\"}\n",
595
+ "\n",
596
+ "if COMBINED_DATASET.exists():\n",
597
+ " shutil.rmtree(COMBINED_DATASET)\n",
598
+ "\n",
599
+ "for split in [\"train\", \"val\"]:\n",
600
+ " (COMBINED_DATASET / f\"images/{split}\").mkdir(parents=True, exist_ok=True)\n",
601
+ " (COMBINED_DATASET / f\"labels/{split}\").mkdir(parents=True, exist_ok=True)\n",
602
+ "\n",
603
+ "samples: list[dict] = []\n",
604
+ "\n",
605
+ "if INCLUDE_OLD_GAS_DATA:\n",
606
+ " old_img_dir = base / \"images/train\"\n",
607
+ " old_lbl_dir = base / \"labels/train\"\n",
608
+ " for lbl_path in sorted(old_lbl_dir.glob(\"*.txt\")):\n",
609
+ " lines = valid_seg_lines(lbl_path, {0})\n",
610
+ " if not lines:\n",
611
+ " continue\n",
612
+ " img_path = find_image_by_stem(old_img_dir, lbl_path.stem)\n",
613
+ " if img_path is None:\n",
614
+ " continue\n",
615
+ " samples.append({\n",
616
+ " \"image\": img_path,\n",
617
+ " \"lines\": lines,\n",
618
+ " \"group\": \"gas\",\n",
619
+ " \"source\": \"old_gas\",\n",
620
+ " })\n",
621
+ "\n",
622
+ "for img_path in list_images(RAW_GAS_EXTRA_DIR):\n",
623
+ " lines = valid_seg_lines(GAS_EXTRA_LABEL_DIR / f\"{img_path.stem}.txt\", {0})\n",
624
+ " if not lines:\n",
625
+ " continue\n",
626
+ " samples.append({\n",
627
+ " \"image\": img_path,\n",
628
+ " \"lines\": lines,\n",
629
+ " \"group\": \"gas\",\n",
630
+ " \"source\": \"gas_extra\",\n",
631
+ " })\n",
632
+ "\n",
633
+ "for img_path in list_images(RAW_VALVE_DIR):\n",
634
+ " valve_lines = valid_seg_lines(VALVE_LABEL_DIR / f\"{img_path.stem}.txt\", {1})\n",
635
+ " if not valve_lines:\n",
636
+ " continue\n",
637
+ " gas_lines = valid_seg_lines(VALVE_GAS_LABEL_DIR / f\"{img_path.stem}.txt\", {0})\n",
638
+ " samples.append({\n",
639
+ " \"image\": img_path,\n",
640
+ " \"lines\": gas_lines + valve_lines,\n",
641
+ " \"group\": \"valve\",\n",
642
+ " \"source\": \"valve\",\n",
643
+ " })\n",
644
+ "\n",
645
+ "print(f\"Collected labeled samples: {len(samples)}\")\n",
646
+ "print(f\" gas samples: {sum(1 for s in samples if s['group'] == 'gas')}\")\n",
647
+ "print(f\" valve samples: {sum(1 for s in samples if s['group'] == 'valve')}\")\n",
648
+ "\n",
649
+ "if not any(s[\"group\"] == \"valve\" for s in samples):\n",
650
+ " raise RuntimeError(\"No valve samples were collected. Check valve auto-label output.\")\n",
651
+ "\n",
652
+ "rng = random.Random(RANDOM_SEED)\n",
653
+ "train_samples: list[dict] = []\n",
654
+ "val_samples: list[dict] = []\n",
655
+ "for group in sorted({s[\"group\"] for s in samples}):\n",
656
+ " group_samples = [s for s in samples if s[\"group\"] == group]\n",
657
+ " rng.shuffle(group_samples)\n",
658
+ " n_val = int(round(len(group_samples) * VAL_RATIO))\n",
659
+ " if len(group_samples) >= 5:\n",
660
+ " n_val = max(1, n_val)\n",
661
+ " val_samples.extend(group_samples[:n_val])\n",
662
+ " train_samples.extend(group_samples[n_val:])\n",
663
+ "\n",
664
+ "rng.shuffle(train_samples)\n",
665
+ "rng.shuffle(val_samples)\n",
666
+ "\n",
667
+ "\n",
668
+ "def materialize(split: str, split_samples: list[dict]) -> None:\n",
669
+ " for idx, sample in enumerate(split_samples, 1):\n",
670
+ " suffix = sample[\"image\"].suffix.lower()\n",
671
+ " stem = f\"{sample['source']}_{idx:05d}\"\n",
672
+ " dst_img = COMBINED_DATASET / f\"images/{split}/{stem}{suffix}\"\n",
673
+ " dst_lbl = COMBINED_DATASET / f\"labels/{split}/{stem}.txt\"\n",
674
+ " shutil.copy2(sample[\"image\"], dst_img)\n",
675
+ " write_lines(dst_lbl, sample[\"lines\"])\n",
676
+ "\n",
677
+ "\n",
678
+ "materialize(\"train\", train_samples)\n",
679
+ "materialize(\"val\", val_samples)\n",
680
+ "\n",
681
+ "YAML_PATH = COMBINED_DATASET / \"dataset.yaml\"\n",
682
+ "yaml_content = {\n",
683
+ " \"path\": str(COMBINED_DATASET),\n",
684
+ " \"train\": \"images/train\",\n",
685
+ " \"val\": \"images/val\",\n",
686
+ " \"names\": {\n",
687
+ " 0: \"gas_cylinder\",\n",
688
+ " 1: \"valve\",\n",
689
+ " },\n",
690
+ "}\n",
691
+ "YAML_PATH.write_text(\n",
692
+ " yaml.safe_dump(yaml_content, allow_unicode=True, sort_keys=False),\n",
693
+ " encoding=\"utf-8\",\n",
694
+ ")\n",
695
+ "\n",
696
+ "train_label_files = list((COMBINED_DATASET / \"labels/train\").glob(\"*.txt\"))\n",
697
+ "val_label_files = list((COMBINED_DATASET / \"labels/val\").glob(\"*.txt\"))\n",
698
+ "\n",
699
+ "print(\"Combined dataset built\")\n",
700
+ "print(f\" train images: {len(list_images(COMBINED_DATASET / 'images/train'))}\")\n",
701
+ "print(f\" train labels: {len(train_label_files)}\")\n",
702
+ "print(f\" val images: {len(list_images(COMBINED_DATASET / 'images/val'))}\")\n",
703
+ "print(f\" val labels: {len(val_label_files)}\")\n",
704
+ "print(f\" train class counts: {class_counts(train_label_files)}\")\n",
705
+ "print(f\" val class counts: {class_counts(val_label_files)}\")\n",
706
+ "print(YAML_PATH.read_text(encoding=\"utf-8\"))"
707
+ ]
708
+ },
709
+ {
710
+ "cell_type": "markdown",
711
+ "metadata": {},
712
+ "source": [
713
+ "---\n",
714
+ "## Step 10 - Visual sanity check"
715
+ ]
716
+ },
717
+ {
718
+ "cell_type": "code",
719
+ "execution_count": null,
720
+ "metadata": {
721
+ "cellView": "form"
722
+ },
723
+ "outputs": [],
724
+ "source": [
725
+ "# @title Step 10 - Visual sanity check\n",
726
+ "\n",
727
+ "def draw_label_overlay(img_path: Path, label_path: Path) -> np.ndarray:\n",
728
+ " img = read_image(img_path)\n",
729
+ " if img is None:\n",
730
+ " raise ValueError(f\"Cannot read {img_path}\")\n",
731
+ " h, w = img.shape[:2]\n",
732
+ " scale = 720 / max(w, h)\n",
733
+ " disp = cv2.resize(img, (int(w * scale), int(h * scale)), interpolation=cv2.INTER_AREA)\n",
734
+ " dh, dw = disp.shape[:2]\n",
735
+ " colors = {\n",
736
+ " 0: (0, 220, 0),\n",
737
+ " 1: (255, 80, 0),\n",
738
+ " }\n",
739
+ "\n",
740
+ " lines = valid_seg_lines(label_path, {0, 1})\n",
741
+ " for line in lines:\n",
742
+ " parts = line.split()\n",
743
+ " cls = int(parts[0])\n",
744
+ " vals = np.array([float(v) for v in parts[1:]], dtype=np.float32).reshape(-1, 2)\n",
745
+ " pts = (vals * np.array([dw, dh], dtype=np.float32)).astype(np.int32).reshape(-1, 1, 2)\n",
746
+ " color = colors.get(cls, (0, 255, 255))\n",
747
+ " overlay = disp.copy()\n",
748
+ " cv2.fillPoly(overlay, [pts], color)\n",
749
+ " cv2.addWeighted(overlay, 0.25, disp, 0.75, 0, disp)\n",
750
+ " cv2.polylines(disp, [pts], True, color, 2)\n",
751
+ " x, y = pts[0, 0]\n",
752
+ " cv2.putText(disp, str(cls), (int(x), int(y)), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2)\n",
753
+ " return cv2.cvtColor(disp, cv2.COLOR_BGR2RGB)\n",
754
+ "\n",
755
+ "\n",
756
+ "preview_imgs = list_images(COMBINED_DATASET / \"images/train\")\n",
757
+ "preview_imgs = random.sample(preview_imgs, min(6, len(preview_imgs)))\n",
758
+ "\n",
759
+ "if preview_imgs:\n",
760
+ " fig, axes = plt.subplots(2, 3, figsize=(18, 10))\n",
761
+ " axes = axes.flatten()\n",
762
+ " for ax, img_path in zip(axes, preview_imgs):\n",
763
+ " lbl_path = COMBINED_DATASET / \"labels/train\" / f\"{img_path.stem}.txt\"\n",
764
+ " ax.imshow(draw_label_overlay(img_path, lbl_path))\n",
765
+ " ax.set_title(img_path.name, fontsize=9)\n",
766
+ " ax.axis(\"off\")\n",
767
+ " for ax in axes[len(preview_imgs):]:\n",
768
+ " ax.axis(\"off\")\n",
769
+ " plt.tight_layout()\n",
770
+ " plt.show()\n",
771
+ "else:\n",
772
+ " print(\"No preview images found\")"
773
+ ]
774
+ },
775
+ {
776
+ "cell_type": "markdown",
777
+ "metadata": {},
778
+ "source": [
779
+ "---\n",
780
+ "## Step 11 - Train YOLO-seg"
781
+ ]
782
+ },
783
+ {
784
+ "cell_type": "code",
785
+ "execution_count": null,
786
+ "metadata": {
787
+ "cellView": "form"
788
+ },
789
+ "outputs": [],
790
+ "source": [
791
+ "# @title Step 11 - Train YOLO-seg\n",
792
+ "\n",
793
+ "from ultralytics import YOLO\n",
794
+ "\n",
795
+ "TRAIN_MODEL = \"yolo11x-seg.pt\" # @param [\"yolo11n-seg.pt\",\"yolo11m-seg.pt\",\"yolo11x-seg.pt\"]\n",
796
+ "EPOCHS = 120 # @param {type:\"integer\"}\n",
797
+ "IMG_SIZE = 640 # @param {type:\"integer\"}\n",
798
+ "BATCH = -1 # @param {type:\"integer\"}\n",
799
+ "PATIENCE = 35 # @param {type:\"integer\"}\n",
800
+ "RUN_NAME = \"gas_valve_seg_v1\" # @param {type:\"string\"}\n",
801
+ "\n",
802
+ "print(\"Training config\")\n",
803
+ "print(f\" model: {TRAIN_MODEL}\")\n",
804
+ "print(f\" data: {YAML_PATH}\")\n",
805
+ "print(f\" epochs: {EPOCHS}\")\n",
806
+ "print(f\" imgsz: {IMG_SIZE}\")\n",
807
+ "print(f\" batch: {BATCH}\")\n",
808
+ "print(f\" run: {RUN_NAME}\")\n",
809
+ "\n",
810
+ "model = YOLO(TRAIN_MODEL)\n",
811
+ "t_start = time.time()\n",
812
+ "train_results = model.train(\n",
813
+ " data=str(YAML_PATH),\n",
814
+ " epochs=EPOCHS,\n",
815
+ " imgsz=IMG_SIZE,\n",
816
+ " batch=BATCH,\n",
817
+ " patience=PATIENCE,\n",
818
+ " project=\"/content/runs\",\n",
819
+ " name=RUN_NAME,\n",
820
+ " device=\"0\" if torch.cuda.is_available() else \"cpu\",\n",
821
+ " workers=2,\n",
822
+ " amp=True,\n",
823
+ " plots=True,\n",
824
+ " save=True,\n",
825
+ " verbose=True,\n",
826
+ " hsv_h=0.015,\n",
827
+ " hsv_s=0.7,\n",
828
+ " hsv_v=0.4,\n",
829
+ " degrees=8.0,\n",
830
+ " translate=0.1,\n",
831
+ " scale=0.5,\n",
832
+ " flipud=0.0,\n",
833
+ " fliplr=0.5,\n",
834
+ " mosaic=0.8,\n",
835
+ " close_mosaic=10,\n",
836
+ " copy_paste=0.05,\n",
837
+ ")\n",
838
+ "\n",
839
+ "RUN_DIR = Path(train_results.save_dir)\n",
840
+ "elapsed = time.time() - t_start\n",
841
+ "print(f\"Training finished in {elapsed / 60:.1f} min\")\n",
842
+ "print(f\"Run dir: {RUN_DIR}\")\n",
843
+ "print(f\"Best weights: {RUN_DIR / 'weights/best.pt'}\")"
844
+ ]
845
+ },
846
+ {
847
+ "cell_type": "markdown",
848
+ "metadata": {},
849
+ "source": [
850
+ "---\n",
851
+ "## Step 12 - Review results"
852
+ ]
853
+ },
854
+ {
855
+ "cell_type": "code",
856
+ "execution_count": null,
857
+ "metadata": {
858
+ "cellView": "form"
859
+ },
860
+ "outputs": [],
861
+ "source": [
862
+ "# @title Step 12 - Review results\n",
863
+ "\n",
864
+ "import pandas as pd\n",
865
+ "import matplotlib.image as mpimg\n",
866
+ "\n",
867
+ "results_csv = RUN_DIR / \"results.csv\"\n",
868
+ "if results_csv.exists():\n",
869
+ " df = pd.read_csv(results_csv)\n",
870
+ " df.columns = df.columns.str.strip()\n",
871
+ " map_cols = [c for c in df.columns if \"mAP50\" in c]\n",
872
+ " if map_cols:\n",
873
+ " best_idx = df[map_cols[0]].idxmax()\n",
874
+ " print(\"Best row\")\n",
875
+ " print(df.iloc[best_idx][[\"epoch\"] + map_cols].to_string())\n",
876
+ "\n",
877
+ "for name in [\"results.png\", \"confusion_matrix_normalized.png\", \"confusion_matrix.png\"]:\n",
878
+ " p = RUN_DIR / name\n",
879
+ " if p.exists():\n",
880
+ " plt.figure(figsize=(14, 7))\n",
881
+ " plt.imshow(mpimg.imread(str(p)))\n",
882
+ " plt.axis(\"off\")\n",
883
+ " plt.title(name)\n",
884
+ " plt.show()"
885
+ ]
886
+ },
887
+ {
888
+ "cell_type": "markdown",
889
+ "metadata": {},
890
+ "source": [
891
+ "---\n",
892
+ "## Step 13 - Upload training results"
893
+ ]
894
+ },
895
+ {
896
+ "cell_type": "code",
897
+ "execution_count": null,
898
+ "metadata": {
899
+ "cellView": "form"
900
+ },
901
+ "outputs": [],
902
+ "source": [
903
+ "# @title Step 13 - Upload training results\n",
904
+ "\n",
905
+ "UPLOAD_TRAINING_RESULTS = True # @param {type:\"boolean\"}\n",
906
+ "UPLOAD_REPO = DATASET_REPO # @param {type:\"string\"}\n",
907
+ "UPLOAD_REPO_TYPE = \"dataset\" # @param [\"dataset\", \"model\"]\n",
908
+ "\n",
909
+ "if UPLOAD_TRAINING_RESULTS:\n",
910
+ " upload_items = [\n",
911
+ " \"weights/best.pt\",\n",
912
+ " \"weights/last.pt\",\n",
913
+ " \"results.png\",\n",
914
+ " \"results.csv\",\n",
915
+ " \"args.yaml\",\n",
916
+ " \"confusion_matrix_normalized.png\",\n",
917
+ " \"confusion_matrix.png\",\n",
918
+ " \"BoxP_curve.png\",\n",
919
+ " \"BoxR_curve.png\",\n",
920
+ " \"BoxF1_curve.png\",\n",
921
+ " \"BoxPR_curve.png\",\n",
922
+ " \"MaskP_curve.png\",\n",
923
+ " \"MaskR_curve.png\",\n",
924
+ " \"MaskF1_curve.png\",\n",
925
+ " \"MaskPR_curve.png\",\n",
926
+ " ]\n",
927
+ "\n",
928
+ " operations = []\n",
929
+ " for rel in upload_items:\n",
930
+ " local_file = RUN_DIR / rel\n",
931
+ " if not local_file.exists():\n",
932
+ " continue\n",
933
+ " operations.append(CommitOperationAdd(\n",
934
+ " path_in_repo=f\"runs/{RUN_NAME}/{rel}\",\n",
935
+ " path_or_fileobj=local_file.read_bytes(),\n",
936
+ " ))\n",
937
+ " print(f\"Prepared {rel}\")\n",
938
+ "\n",
939
+ " operations.append(CommitOperationAdd(\n",
940
+ " path_in_repo=f\"runs/{RUN_NAME}/dataset.yaml\",\n",
941
+ " path_or_fileobj=YAML_PATH.read_bytes(),\n",
942
+ " ))\n",
943
+ "\n",
944
+ " if operations:\n",
945
+ " api.create_commit(\n",
946
+ " repo_id=UPLOAD_REPO,\n",
947
+ " repo_type=UPLOAD_REPO_TYPE,\n",
948
+ " token=HF_TOKEN,\n",
949
+ " operations=operations,\n",
950
+ " commit_message=f\"Training_results_{RUN_NAME}\",\n",
951
+ " )\n",
952
+ " print(f\"Uploaded results to https://huggingface.co/datasets/{UPLOAD_REPO}/tree/main/runs/{RUN_NAME}\")\n",
953
+ " else:\n",
954
+ " print(\"No result files found to upload\")\n",
955
+ "else:\n",
956
+ " print(\"Skipping result upload\")"
957
+ ]
958
+ },
959
+ {
960
+ "cell_type": "markdown",
961
+ "metadata": {},
962
+ "source": [
963
+ "---\n",
964
+ "## Done\n",
965
+ "\n",
966
+ "The best model is in `RUN_DIR / \"weights/best.pt\"`."
967
+ ]
968
+ }
969
+ ]
970
+ }
notebooks/colab_gas_valve_auto_label_train.py ADDED
@@ -0,0 +1,823 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ============================================================
2
+ # Gas + valve YOLO-seg Colab pipeline
3
+ #
4
+ # Flow:
5
+ # 1. Authenticate HuggingFace
6
+ # 2. Download old gas dataset + raw valve/gas-extra folders
7
+ # 3. Auto-label new gas images and gas regions in valve images
8
+ # 4. Auto-label valve polygons with process_valve_to_polygon.py
9
+ # 5. Build a two-class YOLO-seg dataset
10
+ # 6. Train and upload results
11
+ # ============================================================
12
+
13
+
14
+ # %% [markdown]
15
+ # # Gas + valve auto-labeling and training
16
+ #
17
+ # This notebook expects the HuggingFace dataset repo to contain:
18
+ #
19
+ # - `images/train/` and `labels/train/`: existing gas-cylinder labels
20
+ # - `raw/valve/`: valve images plus bbox `.txt` priors
21
+ # - `raw/gas_extra/`: extra gas-cylinder images
22
+ # - `scripts/process_valve_to_polygon.py`: valve polygon auto-label script
23
+ #
24
+ # Class mapping:
25
+ #
26
+ # - `0`: `gas_cylinder`
27
+ # - `1`: `valve`
28
+
29
+
30
+ # %% [markdown]
31
+ # ---
32
+ # ## Step 1 - Install dependencies
33
+
34
+
35
+ # %%
36
+ # @title Step 1 - Install dependencies
37
+
38
+ get_ipython().system(
39
+ "pip install -q ultralytics huggingface_hub opencv-python-headless "
40
+ "tqdm pyyaml matplotlib pandas"
41
+ )
42
+
43
+ import os
44
+ import sys
45
+ import time
46
+ import shutil
47
+ import random
48
+ import subprocess
49
+ from pathlib import Path
50
+
51
+ import cv2
52
+ import yaml
53
+ import torch
54
+ import numpy as np
55
+ import matplotlib.pyplot as plt
56
+
57
+ from tqdm.notebook import tqdm
58
+ from huggingface_hub import (
59
+ HfApi,
60
+ login,
61
+ snapshot_download,
62
+ CommitOperationAdd,
63
+ )
64
+
65
+ print("Dependencies installed")
66
+ print(f"Python: {sys.version.split()[0]}")
67
+ print(f"PyTorch: {torch.__version__}")
68
+ print(f"CUDA available: {torch.cuda.is_available()}")
69
+ if torch.cuda.is_available():
70
+ print(f"GPU: {torch.cuda.get_device_name(0)}")
71
+
72
+
73
+ # %% [markdown]
74
+ # ---
75
+ # ## Step 2 - HuggingFace authentication
76
+
77
+
78
+ # %%
79
+ # @title Step 2 - HuggingFace authentication
80
+ # @markdown Token needs write permission if you want to upload generated labels and training results.
81
+
82
+ HF_TOKEN = "" # @param {type:"string"}
83
+ DATASET_REPO = "rick003/11111" # @param {type:"string"}
84
+
85
+ if not HF_TOKEN:
86
+ from getpass import getpass
87
+
88
+ HF_TOKEN = getpass("HuggingFace token: ")
89
+
90
+ if not HF_TOKEN:
91
+ raise ValueError("HF_TOKEN is required")
92
+
93
+ login(token=HF_TOKEN, add_to_git_credential=False)
94
+ api = HfApi()
95
+ api.dataset_info(DATASET_REPO, token=HF_TOKEN)
96
+
97
+ print("HuggingFace authentication OK")
98
+ print(f"Dataset: https://huggingface.co/datasets/{DATASET_REPO}")
99
+
100
+
101
+ # %% [markdown]
102
+ # ---
103
+ # ## Step 3 - Download required files
104
+
105
+
106
+ # %%
107
+ # @title Step 3 - Download required files
108
+ # @markdown Downloads only the files needed for joint labeling/training.
109
+
110
+ DATASET_LOCAL = "/content/hf_11111" # @param {type:"string"}
111
+ RAW_VALVE_PREFIX = "raw/valve"
112
+ RAW_GAS_EXTRA_PREFIX = "raw/gas_extra"
113
+ PROCESS_SCRIPT_REPO_PATH = "scripts/process_valve_to_polygon.py"
114
+ FORCE_REDOWNLOAD = False # @param {type:"boolean"}
115
+
116
+ base = Path(DATASET_LOCAL)
117
+ if FORCE_REDOWNLOAD and base.exists():
118
+ shutil.rmtree(base)
119
+
120
+ allow_patterns = [
121
+ "images/train/**",
122
+ "labels/train/**",
123
+ f"{RAW_VALVE_PREFIX}/**",
124
+ f"{RAW_GAS_EXTRA_PREFIX}/**",
125
+ PROCESS_SCRIPT_REPO_PATH,
126
+ "dataset.yaml",
127
+ ]
128
+
129
+ print(f"Downloading dataset files to {DATASET_LOCAL}")
130
+ snapshot_download(
131
+ repo_id=DATASET_REPO,
132
+ repo_type="dataset",
133
+ token=HF_TOKEN,
134
+ local_dir=DATASET_LOCAL,
135
+ allow_patterns=allow_patterns,
136
+ ignore_patterns=["runs/**", "preview/**", "*.cache", ".git/**"],
137
+ )
138
+
139
+ RAW_VALVE_DIR = base / RAW_VALVE_PREFIX
140
+ RAW_GAS_EXTRA_DIR = base / RAW_GAS_EXTRA_PREFIX
141
+ PROCESS_SCRIPT_LOCAL = base / PROCESS_SCRIPT_REPO_PATH
142
+
143
+ print("Download summary")
144
+ for p in [base / "images/train", base / "labels/train", RAW_VALVE_DIR, RAW_GAS_EXTRA_DIR]:
145
+ n = len(list(p.glob("*"))) if p.exists() else 0
146
+ print(f" {p}: {n} entries")
147
+
148
+ if not RAW_VALVE_DIR.exists():
149
+ raise FileNotFoundError(f"Missing {RAW_VALVE_PREFIX} in HF dataset")
150
+ if not RAW_GAS_EXTRA_DIR.exists():
151
+ raise FileNotFoundError(f"Missing {RAW_GAS_EXTRA_PREFIX} in HF dataset")
152
+ if not PROCESS_SCRIPT_LOCAL.exists():
153
+ raise FileNotFoundError(
154
+ f"Missing {PROCESS_SCRIPT_REPO_PATH}. Upload process_valve_to_polygon.py "
155
+ "to this path before running valve auto-labeling."
156
+ )
157
+
158
+
159
+ # %% [markdown]
160
+ # ---
161
+ # ## Step 4 - Shared helpers
162
+
163
+
164
+ # %%
165
+ # @title Step 4 - Shared helpers
166
+
167
+ IMG_EXTS = {".png", ".jpg", ".jpeg", ".bmp", ".webp"}
168
+ WORK_DIR = Path("/content/gas_valve_work")
169
+ LABEL_WORK_DIR = WORK_DIR / "labels"
170
+ VIS_WORK_DIR = WORK_DIR / "visual"
171
+ for d in [LABEL_WORK_DIR, VIS_WORK_DIR]:
172
+ d.mkdir(parents=True, exist_ok=True)
173
+
174
+
175
+ def list_images(folder: Path) -> list[Path]:
176
+ if not folder.exists():
177
+ return []
178
+ return sorted(
179
+ p for p in folder.iterdir()
180
+ if p.is_file() and p.suffix.lower() in IMG_EXTS
181
+ )
182
+
183
+
184
+ def find_image_by_stem(folder: Path, stem: str) -> Path | None:
185
+ for ext in IMG_EXTS:
186
+ p = folder / f"{stem}{ext}"
187
+ if p.exists():
188
+ return p
189
+ for p in folder.glob(f"{stem}.*"):
190
+ if p.suffix.lower() in IMG_EXTS:
191
+ return p
192
+ return None
193
+
194
+
195
+ def read_image(path: Path) -> np.ndarray | None:
196
+ raw = np.fromfile(str(path), dtype=np.uint8)
197
+ if raw.size == 0:
198
+ return None
199
+ return cv2.imdecode(raw, cv2.IMREAD_COLOR)
200
+
201
+
202
+ def valid_seg_lines(label_path: Path, allowed_classes: set[int] | None = None) -> list[str]:
203
+ if not label_path.exists():
204
+ return []
205
+ text = label_path.read_text(encoding="utf-8", errors="ignore").strip()
206
+ if not text:
207
+ return []
208
+
209
+ lines: list[str] = []
210
+ for raw_line in text.splitlines():
211
+ parts = raw_line.strip().split()
212
+ if len(parts) < 7:
213
+ continue
214
+ try:
215
+ cls = int(float(parts[0]))
216
+ coords = [float(v) for v in parts[1:]]
217
+ except ValueError:
218
+ continue
219
+ if allowed_classes is not None and cls not in allowed_classes:
220
+ continue
221
+ if len(coords) < 6 or len(coords) % 2 != 0:
222
+ continue
223
+ coords = [min(1.0, max(0.0, v)) for v in coords]
224
+ out = [str(cls)] + [f"{v:.6f}" for v in coords]
225
+ lines.append(" ".join(out))
226
+ return lines
227
+
228
+
229
+ def write_lines(path: Path, lines: list[str]) -> None:
230
+ path.parent.mkdir(parents=True, exist_ok=True)
231
+ path.write_text("\n".join(lines).strip() + ("\n" if lines else ""), encoding="utf-8")
232
+
233
+
234
+ def class_counts(label_files: list[Path]) -> dict[int, int]:
235
+ counts: dict[int, int] = {}
236
+ for p in label_files:
237
+ for line in p.read_text(encoding="utf-8", errors="ignore").splitlines():
238
+ parts = line.strip().split()
239
+ if not parts:
240
+ continue
241
+ try:
242
+ cls = int(float(parts[0]))
243
+ except ValueError:
244
+ continue
245
+ counts[cls] = counts.get(cls, 0) + 1
246
+ return counts
247
+
248
+
249
+ print(f"Old train images: {len(list_images(base / 'images/train'))}")
250
+ print(f"Old train labels: {len(list((base / 'labels/train').glob('*.txt')))}")
251
+ print(f"Raw valve images: {len(list_images(RAW_VALVE_DIR))}")
252
+ print(f"Raw gas-extra images: {len(list_images(RAW_GAS_EXTRA_DIR))}")
253
+
254
+
255
+ # %% [markdown]
256
+ # ---
257
+ # ## Step 5 - Gas-cylinder auto-labeler
258
+
259
+
260
+ # %%
261
+ # @title Step 5 - Gas-cylinder auto-labeler
262
+
263
+
264
+ class GasCylinderSegmenter:
265
+ CLASS_WEIGHTS = {
266
+ 39: 2.0, # bottle
267
+ 10: 1.0, # fire hydrant
268
+ 71: 1.0, # sink
269
+ 61: 1.0, # toilet
270
+ 41: 0.8, # cup
271
+ 56: 0.8, # chair
272
+ 75: 0.8, # vase
273
+ }
274
+
275
+ def __init__(self, model_path: str = "yolo11x-seg.pt", class_id: int = 0) -> None:
276
+ from ultralytics import YOLO
277
+
278
+ self.device = "0" if torch.cuda.is_available() else "cpu"
279
+ self.class_id = class_id
280
+ self.model = YOLO(model_path)
281
+ self.conf = 0.01
282
+ self.min_area = 0.03
283
+ self.max_dist = 0.35
284
+ print(f"Gas label model: {model_path}, device={self.device}, class_id={class_id}")
285
+
286
+ def annotate(self, img: np.ndarray) -> tuple[str, bool]:
287
+ h, w = img.shape[:2]
288
+ cx, cy = w / 2.0, h / 2.0
289
+ area = float(w * h)
290
+ diag = float(w * w + h * h) ** 0.5
291
+
292
+ result = self.model(img, conf=self.conf, device=self.device, verbose=False)[0]
293
+ candidates = []
294
+
295
+ if result.masks is not None:
296
+ for i in range(len(result.masks.data)):
297
+ cls_id = int(result.boxes.cls[i])
298
+ if cls_id not in self.CLASS_WEIGHTS:
299
+ continue
300
+
301
+ conf = float(result.boxes.conf[i])
302
+ x1, y1, x2, y2 = result.boxes.xyxy[i].tolist()
303
+ box_cx = (x1 + x2) / 2.0
304
+ box_cy = (y1 + y2) / 2.0
305
+ area_ratio = (x2 - x1) * (y2 - y1) / area
306
+ dist_ratio = ((box_cx - cx) ** 2 + (box_cy - cy) ** 2) ** 0.5 / diag
307
+
308
+ if area_ratio < self.min_area or dist_ratio > self.max_dist:
309
+ continue
310
+
311
+ centrality_bonus = 1.0 + (1.0 - dist_ratio / self.max_dist)
312
+ score = conf * self.CLASS_WEIGHTS[cls_id] * centrality_bonus
313
+ candidates.append((score, result.masks.xyn[i]))
314
+
315
+ if not candidates:
316
+ return "", False
317
+
318
+ _, poly = max(candidates, key=lambda x: x[0])
319
+ if len(poly) < 3:
320
+ return "", False
321
+
322
+ tokens = [str(self.class_id)]
323
+ for x, y in poly:
324
+ tokens.append(f"{float(x):.6f}")
325
+ tokens.append(f"{float(y):.6f}")
326
+ return " ".join(tokens), True
327
+
328
+
329
+ def auto_label_gas_folder(
330
+ segmenter: GasCylinderSegmenter,
331
+ image_dir: Path,
332
+ labels_dir: Path,
333
+ *,
334
+ overwrite: bool = False,
335
+ limit: int = 0,
336
+ ) -> dict[str, int]:
337
+ labels_dir.mkdir(parents=True, exist_ok=True)
338
+ images = list_images(image_dir)
339
+ if limit > 0:
340
+ images = images[:limit]
341
+
342
+ stats = {"ok": 0, "failed": 0, "error": 0, "skipped": 0}
343
+ for image_path in tqdm(images, desc=f"Gas labels: {image_dir.name}"):
344
+ label_path = labels_dir / f"{image_path.stem}.txt"
345
+ if label_path.exists() and label_path.stat().st_size > 0 and not overwrite:
346
+ stats["skipped"] += 1
347
+ continue
348
+
349
+ img = read_image(image_path)
350
+ if img is None:
351
+ write_lines(label_path, [])
352
+ stats["error"] += 1
353
+ continue
354
+
355
+ try:
356
+ label, ok = segmenter.annotate(img)
357
+ write_lines(label_path, [label] if ok else [])
358
+ stats["ok" if ok else "failed"] += 1
359
+ except Exception as exc:
360
+ print(f"Gas label error: {image_path.name}: {exc}")
361
+ write_lines(label_path, [])
362
+ stats["error"] += 1
363
+
364
+ print(f"{image_dir.name}: {stats}")
365
+ return stats
366
+
367
+
368
+ # %% [markdown]
369
+ # ---
370
+ # ## Step 6 - Auto-label new gas data
371
+
372
+
373
+ # %%
374
+ # @title Step 6 - Auto-label new gas data
375
+ # @markdown Gas labels are generated for both extra gas images and valve images.
376
+ # @markdown The valve-image gas labels prevent visible gas cylinders from being treated as background.
377
+
378
+ GAS_LABEL_MODEL = "yolo11x-seg.pt" # @param ["yolo11n-seg.pt","yolo11m-seg.pt","yolo11x-seg.pt"]
379
+ REGENERATE_GAS_LABELS = False # @param {type:"boolean"}
380
+ GAS_LABEL_LIMIT = 0 # @param {type:"integer"}
381
+
382
+ GAS_EXTRA_LABEL_DIR = LABEL_WORK_DIR / "gas_extra"
383
+ VALVE_GAS_LABEL_DIR = LABEL_WORK_DIR / "valve_gas"
384
+
385
+ gas_segmenter = GasCylinderSegmenter(GAS_LABEL_MODEL, class_id=0)
386
+ gas_extra_stats = auto_label_gas_folder(
387
+ gas_segmenter,
388
+ RAW_GAS_EXTRA_DIR,
389
+ GAS_EXTRA_LABEL_DIR,
390
+ overwrite=REGENERATE_GAS_LABELS,
391
+ limit=GAS_LABEL_LIMIT,
392
+ )
393
+ valve_gas_stats = auto_label_gas_folder(
394
+ gas_segmenter,
395
+ RAW_VALVE_DIR,
396
+ VALVE_GAS_LABEL_DIR,
397
+ overwrite=REGENERATE_GAS_LABELS,
398
+ limit=GAS_LABEL_LIMIT,
399
+ )
400
+
401
+
402
+ # %% [markdown]
403
+ # ---
404
+ # ## Step 7 - Auto-label valve polygons
405
+
406
+
407
+ # %%
408
+ # @title Step 7 - Auto-label valve polygons
409
+ # @markdown Uses `process_valve_to_polygon.py` and the bbox `.txt` priors in `raw/valve/`.
410
+
411
+ VALVE_LABEL_MODEL = "yolo11x-seg.pt" # @param ["yolo11n-seg.pt","yolo11m-seg.pt","yolo11x-seg.pt"]
412
+ REGENERATE_VALVE_LABELS = False # @param {type:"boolean"}
413
+ SAVE_VALVE_VISUALIZATIONS = False # @param {type:"boolean"}
414
+ VALVE_LABEL_LIMIT = 0 # @param {type:"integer"}
415
+
416
+ VALVE_LABEL_DIR = LABEL_WORK_DIR / "valve"
417
+ VALVE_VIS_DIR = VIS_WORK_DIR / "valve"
418
+ VALVE_LABEL_DIR.mkdir(parents=True, exist_ok=True)
419
+ VALVE_VIS_DIR.mkdir(parents=True, exist_ok=True)
420
+
421
+ device = "0" if torch.cuda.is_available() else "cpu"
422
+ cmd = [
423
+ sys.executable,
424
+ str(PROCESS_SCRIPT_LOCAL),
425
+ "--image-dir",
426
+ str(RAW_VALVE_DIR),
427
+ "--labels-dir",
428
+ str(VALVE_LABEL_DIR),
429
+ "--vis-dir",
430
+ str(VALVE_VIS_DIR),
431
+ "--bbox-dir",
432
+ str(RAW_VALVE_DIR),
433
+ "--class-id",
434
+ "1",
435
+ "--model",
436
+ VALVE_LABEL_MODEL,
437
+ "--device",
438
+ device,
439
+ ]
440
+ if REGENERATE_VALVE_LABELS:
441
+ cmd.append("--overwrite")
442
+ if not SAVE_VALVE_VISUALIZATIONS:
443
+ cmd.append("--skip-visualizations")
444
+ if VALVE_LABEL_LIMIT > 0:
445
+ cmd.extend(["--limit", str(VALVE_LABEL_LIMIT)])
446
+
447
+ print("Running valve auto-labeler")
448
+ print(" ".join(cmd))
449
+ subprocess.run(cmd, check=True)
450
+
451
+ valve_labels = list(VALVE_LABEL_DIR.glob("*.txt"))
452
+ print(f"Valve label files: {len(valve_labels)}")
453
+ print(f"Valve non-empty labels: {sum(1 for p in valve_labels if p.stat().st_size > 0)}")
454
+
455
+
456
+ # %% [markdown]
457
+ # ---
458
+ # ## Step 8 - Optionally upload generated labels
459
+
460
+
461
+ # %%
462
+ # @title Step 8 - Optionally upload generated labels
463
+ # @markdown Uploads generated labels under `auto_labels/gas_valve_v1/`.
464
+
465
+ UPLOAD_GENERATED_LABELS = True # @param {type:"boolean"}
466
+ GENERATED_LABELS_REPO_DIR = "auto_labels/gas_valve_v1" # @param {type:"string"}
467
+
468
+ if UPLOAD_GENERATED_LABELS:
469
+ print(f"Uploading generated labels to {GENERATED_LABELS_REPO_DIR}")
470
+ api.upload_folder(
471
+ repo_id=DATASET_REPO,
472
+ repo_type="dataset",
473
+ token=HF_TOKEN,
474
+ folder_path=str(LABEL_WORK_DIR),
475
+ path_in_repo=GENERATED_LABELS_REPO_DIR,
476
+ commit_message="upload_generated_gas_valve_labels",
477
+ )
478
+ print("Generated labels uploaded")
479
+ else:
480
+ print("Skipping generated label upload")
481
+
482
+
483
+ # %% [markdown]
484
+ # ---
485
+ # ## Step 9 - Build the two-class training dataset
486
+
487
+
488
+ # %%
489
+ # @title Step 9 - Build the two-class training dataset
490
+
491
+ COMBINED_DATASET = Path("/content/gas_valve_dataset")
492
+ VAL_RATIO = 0.20 # @param {type:"number"}
493
+ RANDOM_SEED = 42 # @param {type:"integer"}
494
+ INCLUDE_OLD_GAS_DATA = True # @param {type:"boolean"}
495
+
496
+ if COMBINED_DATASET.exists():
497
+ shutil.rmtree(COMBINED_DATASET)
498
+
499
+ for split in ["train", "val"]:
500
+ (COMBINED_DATASET / f"images/{split}").mkdir(parents=True, exist_ok=True)
501
+ (COMBINED_DATASET / f"labels/{split}").mkdir(parents=True, exist_ok=True)
502
+
503
+ samples: list[dict] = []
504
+
505
+ if INCLUDE_OLD_GAS_DATA:
506
+ old_img_dir = base / "images/train"
507
+ old_lbl_dir = base / "labels/train"
508
+ for lbl_path in sorted(old_lbl_dir.glob("*.txt")):
509
+ lines = valid_seg_lines(lbl_path, {0})
510
+ if not lines:
511
+ continue
512
+ img_path = find_image_by_stem(old_img_dir, lbl_path.stem)
513
+ if img_path is None:
514
+ continue
515
+ samples.append({
516
+ "image": img_path,
517
+ "lines": lines,
518
+ "group": "gas",
519
+ "source": "old_gas",
520
+ })
521
+
522
+ for img_path in list_images(RAW_GAS_EXTRA_DIR):
523
+ lines = valid_seg_lines(GAS_EXTRA_LABEL_DIR / f"{img_path.stem}.txt", {0})
524
+ if not lines:
525
+ continue
526
+ samples.append({
527
+ "image": img_path,
528
+ "lines": lines,
529
+ "group": "gas",
530
+ "source": "gas_extra",
531
+ })
532
+
533
+ for img_path in list_images(RAW_VALVE_DIR):
534
+ valve_lines = valid_seg_lines(VALVE_LABEL_DIR / f"{img_path.stem}.txt", {1})
535
+ if not valve_lines:
536
+ continue
537
+ gas_lines = valid_seg_lines(VALVE_GAS_LABEL_DIR / f"{img_path.stem}.txt", {0})
538
+ samples.append({
539
+ "image": img_path,
540
+ "lines": gas_lines + valve_lines,
541
+ "group": "valve",
542
+ "source": "valve",
543
+ })
544
+
545
+ print(f"Collected labeled samples: {len(samples)}")
546
+ print(f" gas samples: {sum(1 for s in samples if s['group'] == 'gas')}")
547
+ print(f" valve samples: {sum(1 for s in samples if s['group'] == 'valve')}")
548
+
549
+ if not any(s["group"] == "valve" for s in samples):
550
+ raise RuntimeError("No valve samples were collected. Check valve auto-label output.")
551
+
552
+ rng = random.Random(RANDOM_SEED)
553
+ train_samples: list[dict] = []
554
+ val_samples: list[dict] = []
555
+ for group in sorted({s["group"] for s in samples}):
556
+ group_samples = [s for s in samples if s["group"] == group]
557
+ rng.shuffle(group_samples)
558
+ n_val = int(round(len(group_samples) * VAL_RATIO))
559
+ if len(group_samples) >= 5:
560
+ n_val = max(1, n_val)
561
+ val_samples.extend(group_samples[:n_val])
562
+ train_samples.extend(group_samples[n_val:])
563
+
564
+ rng.shuffle(train_samples)
565
+ rng.shuffle(val_samples)
566
+
567
+
568
+ def materialize(split: str, split_samples: list[dict]) -> None:
569
+ for idx, sample in enumerate(split_samples, 1):
570
+ suffix = sample["image"].suffix.lower()
571
+ stem = f"{sample['source']}_{idx:05d}"
572
+ dst_img = COMBINED_DATASET / f"images/{split}/{stem}{suffix}"
573
+ dst_lbl = COMBINED_DATASET / f"labels/{split}/{stem}.txt"
574
+ shutil.copy2(sample["image"], dst_img)
575
+ write_lines(dst_lbl, sample["lines"])
576
+
577
+
578
+ materialize("train", train_samples)
579
+ materialize("val", val_samples)
580
+
581
+ YAML_PATH = COMBINED_DATASET / "dataset.yaml"
582
+ yaml_content = {
583
+ "path": str(COMBINED_DATASET),
584
+ "train": "images/train",
585
+ "val": "images/val",
586
+ "names": {
587
+ 0: "gas_cylinder",
588
+ 1: "valve",
589
+ },
590
+ }
591
+ YAML_PATH.write_text(
592
+ yaml.safe_dump(yaml_content, allow_unicode=True, sort_keys=False),
593
+ encoding="utf-8",
594
+ )
595
+
596
+ train_label_files = list((COMBINED_DATASET / "labels/train").glob("*.txt"))
597
+ val_label_files = list((COMBINED_DATASET / "labels/val").glob("*.txt"))
598
+
599
+ print("Combined dataset built")
600
+ print(f" train images: {len(list_images(COMBINED_DATASET / 'images/train'))}")
601
+ print(f" train labels: {len(train_label_files)}")
602
+ print(f" val images: {len(list_images(COMBINED_DATASET / 'images/val'))}")
603
+ print(f" val labels: {len(val_label_files)}")
604
+ print(f" train class counts: {class_counts(train_label_files)}")
605
+ print(f" val class counts: {class_counts(val_label_files)}")
606
+ print(YAML_PATH.read_text(encoding="utf-8"))
607
+
608
+
609
+ # %% [markdown]
610
+ # ---
611
+ # ## Step 10 - Visual sanity check
612
+
613
+
614
+ # %%
615
+ # @title Step 10 - Visual sanity check
616
+
617
+ def draw_label_overlay(img_path: Path, label_path: Path) -> np.ndarray:
618
+ img = read_image(img_path)
619
+ if img is None:
620
+ raise ValueError(f"Cannot read {img_path}")
621
+ h, w = img.shape[:2]
622
+ scale = 720 / max(w, h)
623
+ disp = cv2.resize(img, (int(w * scale), int(h * scale)), interpolation=cv2.INTER_AREA)
624
+ dh, dw = disp.shape[:2]
625
+ colors = {
626
+ 0: (0, 220, 0),
627
+ 1: (255, 80, 0),
628
+ }
629
+
630
+ lines = valid_seg_lines(label_path, {0, 1})
631
+ for line in lines:
632
+ parts = line.split()
633
+ cls = int(parts[0])
634
+ vals = np.array([float(v) for v in parts[1:]], dtype=np.float32).reshape(-1, 2)
635
+ pts = (vals * np.array([dw, dh], dtype=np.float32)).astype(np.int32).reshape(-1, 1, 2)
636
+ color = colors.get(cls, (0, 255, 255))
637
+ overlay = disp.copy()
638
+ cv2.fillPoly(overlay, [pts], color)
639
+ cv2.addWeighted(overlay, 0.25, disp, 0.75, 0, disp)
640
+ cv2.polylines(disp, [pts], True, color, 2)
641
+ x, y = pts[0, 0]
642
+ cv2.putText(disp, str(cls), (int(x), int(y)), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2)
643
+ return cv2.cvtColor(disp, cv2.COLOR_BGR2RGB)
644
+
645
+
646
+ preview_imgs = list_images(COMBINED_DATASET / "images/train")
647
+ preview_imgs = random.sample(preview_imgs, min(6, len(preview_imgs)))
648
+
649
+ if preview_imgs:
650
+ fig, axes = plt.subplots(2, 3, figsize=(18, 10))
651
+ axes = axes.flatten()
652
+ for ax, img_path in zip(axes, preview_imgs):
653
+ lbl_path = COMBINED_DATASET / "labels/train" / f"{img_path.stem}.txt"
654
+ ax.imshow(draw_label_overlay(img_path, lbl_path))
655
+ ax.set_title(img_path.name, fontsize=9)
656
+ ax.axis("off")
657
+ for ax in axes[len(preview_imgs):]:
658
+ ax.axis("off")
659
+ plt.tight_layout()
660
+ plt.show()
661
+ else:
662
+ print("No preview images found")
663
+
664
+
665
+ # %% [markdown]
666
+ # ---
667
+ # ## Step 11 - Train YOLO-seg
668
+
669
+
670
+ # %%
671
+ # @title Step 11 - Train YOLO-seg
672
+
673
+ from ultralytics import YOLO
674
+
675
+ TRAIN_MODEL = "yolo11x-seg.pt" # @param ["yolo11n-seg.pt","yolo11m-seg.pt","yolo11x-seg.pt"]
676
+ EPOCHS = 120 # @param {type:"integer"}
677
+ IMG_SIZE = 640 # @param {type:"integer"}
678
+ BATCH = -1 # @param {type:"integer"}
679
+ PATIENCE = 35 # @param {type:"integer"}
680
+ RUN_NAME = "gas_valve_seg_v1" # @param {type:"string"}
681
+
682
+ print("Training config")
683
+ print(f" model: {TRAIN_MODEL}")
684
+ print(f" data: {YAML_PATH}")
685
+ print(f" epochs: {EPOCHS}")
686
+ print(f" imgsz: {IMG_SIZE}")
687
+ print(f" batch: {BATCH}")
688
+ print(f" run: {RUN_NAME}")
689
+
690
+ model = YOLO(TRAIN_MODEL)
691
+ t_start = time.time()
692
+ train_results = model.train(
693
+ data=str(YAML_PATH),
694
+ epochs=EPOCHS,
695
+ imgsz=IMG_SIZE,
696
+ batch=BATCH,
697
+ patience=PATIENCE,
698
+ project="/content/runs",
699
+ name=RUN_NAME,
700
+ device="0" if torch.cuda.is_available() else "cpu",
701
+ workers=2,
702
+ amp=True,
703
+ plots=True,
704
+ save=True,
705
+ verbose=True,
706
+ hsv_h=0.015,
707
+ hsv_s=0.7,
708
+ hsv_v=0.4,
709
+ degrees=8.0,
710
+ translate=0.1,
711
+ scale=0.5,
712
+ flipud=0.0,
713
+ fliplr=0.5,
714
+ mosaic=0.8,
715
+ close_mosaic=10,
716
+ copy_paste=0.05,
717
+ )
718
+
719
+ RUN_DIR = Path(train_results.save_dir)
720
+ elapsed = time.time() - t_start
721
+ print(f"Training finished in {elapsed / 60:.1f} min")
722
+ print(f"Run dir: {RUN_DIR}")
723
+ print(f"Best weights: {RUN_DIR / 'weights/best.pt'}")
724
+
725
+
726
+ # %% [markdown]
727
+ # ---
728
+ # ## Step 12 - Review results
729
+
730
+
731
+ # %%
732
+ # @title Step 12 - Review results
733
+
734
+ import pandas as pd
735
+ import matplotlib.image as mpimg
736
+
737
+ results_csv = RUN_DIR / "results.csv"
738
+ if results_csv.exists():
739
+ df = pd.read_csv(results_csv)
740
+ df.columns = df.columns.str.strip()
741
+ map_cols = [c for c in df.columns if "mAP50" in c]
742
+ if map_cols:
743
+ best_idx = df[map_cols[0]].idxmax()
744
+ print("Best row")
745
+ print(df.iloc[best_idx][["epoch"] + map_cols].to_string())
746
+
747
+ for name in ["results.png", "confusion_matrix_normalized.png", "confusion_matrix.png"]:
748
+ p = RUN_DIR / name
749
+ if p.exists():
750
+ plt.figure(figsize=(14, 7))
751
+ plt.imshow(mpimg.imread(str(p)))
752
+ plt.axis("off")
753
+ plt.title(name)
754
+ plt.show()
755
+
756
+
757
+ # %% [markdown]
758
+ # ---
759
+ # ## Step 13 - Upload training results
760
+
761
+
762
+ # %%
763
+ # @title Step 13 - Upload training results
764
+
765
+ UPLOAD_TRAINING_RESULTS = True # @param {type:"boolean"}
766
+ UPLOAD_REPO = DATASET_REPO # @param {type:"string"}
767
+ UPLOAD_REPO_TYPE = "dataset" # @param ["dataset", "model"]
768
+
769
+ if UPLOAD_TRAINING_RESULTS:
770
+ upload_items = [
771
+ "weights/best.pt",
772
+ "weights/last.pt",
773
+ "results.png",
774
+ "results.csv",
775
+ "args.yaml",
776
+ "confusion_matrix_normalized.png",
777
+ "confusion_matrix.png",
778
+ "BoxP_curve.png",
779
+ "BoxR_curve.png",
780
+ "BoxF1_curve.png",
781
+ "BoxPR_curve.png",
782
+ "MaskP_curve.png",
783
+ "MaskR_curve.png",
784
+ "MaskF1_curve.png",
785
+ "MaskPR_curve.png",
786
+ ]
787
+
788
+ operations = []
789
+ for rel in upload_items:
790
+ local_file = RUN_DIR / rel
791
+ if not local_file.exists():
792
+ continue
793
+ operations.append(CommitOperationAdd(
794
+ path_in_repo=f"runs/{RUN_NAME}/{rel}",
795
+ path_or_fileobj=local_file.read_bytes(),
796
+ ))
797
+ print(f"Prepared {rel}")
798
+
799
+ operations.append(CommitOperationAdd(
800
+ path_in_repo=f"runs/{RUN_NAME}/dataset.yaml",
801
+ path_or_fileobj=YAML_PATH.read_bytes(),
802
+ ))
803
+
804
+ if operations:
805
+ api.create_commit(
806
+ repo_id=UPLOAD_REPO,
807
+ repo_type=UPLOAD_REPO_TYPE,
808
+ token=HF_TOKEN,
809
+ operations=operations,
810
+ commit_message=f"Training_results_{RUN_NAME}",
811
+ )
812
+ print(f"Uploaded results to https://huggingface.co/datasets/{UPLOAD_REPO}/tree/main/runs/{RUN_NAME}")
813
+ else:
814
+ print("No result files found to upload")
815
+ else:
816
+ print("Skipping result upload")
817
+
818
+
819
+ # %% [markdown]
820
+ # ---
821
+ # ## Done
822
+ #
823
+ # The best model is in `RUN_DIR / "weights/best.pt"`.
raw/valve/Pic_阀门_1.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.653809 0.549333 0.338867 0.454667
raw/valve/Pic_阀门_10.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.643921 0.526167 0.346436 0.471667
raw/valve/Pic_阀门_100.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.613525 0.585000 0.377930 0.488667
raw/valve/Pic_阀门_101.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.531372 0.563833 0.356201 0.485667
raw/valve/Pic_阀门_102.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.245972 0.618167 0.452393 0.697000
raw/valve/Pic_阀门_103.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.321411 0.547167 0.461182 0.493667
raw/valve/Pic_阀门_104.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.433716 0.536833 0.530518 0.522333
raw/valve/Pic_阀门_105.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.440796 0.504167 0.488525 0.524333
raw/valve/Pic_阀门_106.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.297852 0.506000 0.490723 0.518000
raw/valve/Pic_阀门_107.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.365967 0.551167 0.476074 0.665000
raw/valve/Pic_阀门_108.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.636963 0.620500 0.365234 0.497000
raw/valve/Pic_阀门_11.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.356079 0.519167 0.458740 0.475667
raw/valve/Pic_阀门_110.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.513550 0.496167 0.397705 0.527000
raw/valve/Pic_阀门_111.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.453125 0.542667 0.403809 0.506667
raw/valve/Pic_阀门_112.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.622803 0.541833 0.375977 0.504333
raw/valve/Pic_阀门_113.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.440674 0.491667 0.487793 0.589333
raw/valve/Pic_阀门_114.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.347046 0.539167 0.441650 0.493667
raw/valve/Pic_阀门_115.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.346558 0.518333 0.475830 0.510667
raw/valve/Pic_阀门_116.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.437744 0.505667 0.498535 0.531333
raw/valve/Pic_阀门_117.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.646362 0.554000 0.379639 0.510667
raw/valve/Pic_阀门_118.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.467529 0.555167 0.426758 0.511000
raw/valve/Pic_阀门_119.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.402954 0.578833 0.473877 0.509000
raw/valve/Pic_阀门_12.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.635376 0.516500 0.352295 0.474333
raw/valve/Pic_阀门_120.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.513794 0.648333 0.521729 0.634667
raw/valve/Pic_阀门_121.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.412720 0.522000 0.483643 0.566000
raw/valve/Pic_阀门_122.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.300293 0.643500 0.486816 0.647000
raw/valve/Pic_阀门_123.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.516968 0.545000 0.500244 0.538667
raw/valve/Pic_阀门_124.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.640137 0.636167 0.575195 0.665667
raw/valve/Pic_阀门_13.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.420776 0.505500 0.451904 0.480333
raw/valve/Pic_阀门_14.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.540771 0.505167 0.494629 0.480333
raw/valve/Pic_阀门_15.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.379028 0.501667 0.496826 0.485333
raw/valve/Pic_阀门_16.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.523926 0.501833 0.502441 0.475667
raw/valve/Pic_阀门_17.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.322876 0.495500 0.569580 0.493667
raw/valve/Pic_阀门_18.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.493774 0.492167 0.481201 0.488333
raw/valve/Pic_阀门_19.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.366211 0.498500 0.460938 0.521000
raw/valve/Pic_阀门_2.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.400635 0.502000 0.448730 0.552667
raw/valve/Pic_阀门_20.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.654663 0.512833 0.354736 0.479667
raw/valve/Pic_阀门_21.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.526367 0.544000 0.384277 0.484667
raw/valve/Pic_阀门_22.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.691406 0.548167 0.366211 0.471000
raw/valve/Pic_阀门_23.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.490479 0.598000 0.465820 0.625333
raw/valve/Pic_阀门_24.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.710083 0.673000 0.353271 0.475333
raw/valve/Pic_阀门_25.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.469727 0.624000 0.494629 0.508000
raw/valve/Pic_阀门_26.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.706421 0.636833 0.356201 0.478333
raw/valve/Pic_阀门_27.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.525024 0.597500 0.400635 0.479000
raw/valve/Pic_阀门_28.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.604736 0.595500 0.469238 0.483000
raw/valve/Pic_阀门_29.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.464355 0.572833 0.477539 0.489000
raw/valve/Pic_阀门_3.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 1 0.679443 0.574833 0.353027 0.459667
scripts/process_valve_to_polygon.py ADDED
@@ -0,0 +1,2381 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Auto-label valve handwheels as polygon segmentation masks.
3
+
4
+ Design notes
5
+ ------------
6
+ The valve is the WHITE 5-petal handwheel on top of the gas cylinder.
7
+ Pure YOLO (open-vocabulary / YOLO-World) does not know this specific
8
+ object well and tends to box the whole cylinder, so we use a two-stage
9
+ hybrid pipeline that mirrors ``process_E_to_F.py`` for the gas cylinder:
10
+
11
+ Stage 1 (coarse) : YOLO11x-seg locates the gas cylinder region and
12
+ returns a polygon mask. This restricts the valve
13
+ search to the cylinder body and avoids spurious
14
+ white pixels from walls / ceiling / backlight.
15
+
16
+ Stage 2 (fine) : Inside the cylinder mask, we threshold the L
17
+ channel of CIE-LAB with an adaptive (Otsu) cut
18
+ to isolate bright pixels. A morphological close
19
+ fuses the 5 petals (and their inner holes + the
20
+ central bolt hole) into one solid blob, then we
21
+ pick the blob that is central, large enough and
22
+ not too elongated. Its external contour is the
23
+ valve edge label.
24
+
25
+ Output
26
+ ------
27
+ - YOLO-seg label files next to each image (``<class_id> x1 y1 x2 y2 ...``,
28
+ normalized polygon coordinates). ``class_id`` defaults to 1 so the
29
+ labels combine cleanly with the gas-cylinder labels (class 0).
30
+ - Optional visualization images with the detected cylinder outlined in
31
+ blue and the valve polygon filled + outlined in green (same style as
32
+ ``process_E_to_F.py``).
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import argparse
38
+ import os
39
+ import sys
40
+ import time
41
+ from dataclasses import dataclass
42
+ from pathlib import Path
43
+
44
+ import cv2
45
+ import numpy as np
46
+
47
+
48
+ # ----------------------------------------------------------------------
49
+ # Defaults
50
+ # ----------------------------------------------------------------------
51
+ DEFAULT_IMAGE_DIR = Path(r"D:\biyesheji\famen\阀门\阀门")
52
+ DEFAULT_VIS_DIR = Path(r"D:\biyesheji\famen\阀门\valve_poly_visualized")
53
+ DEFAULT_DEBUG_DIR = Path(r"D:\biyesheji\famen\阀门\valve_poly_debug")
54
+ DEFAULT_MODEL = "yolo11x-seg.pt"
55
+ IMAGE_SUFFIXES = {".png", ".jpg", ".jpeg", ".bmp", ".webp"}
56
+
57
+ # COCO class weights for the coarse cylinder locator, kept identical to
58
+ # process_E_to_F.py / auto_label_final_robust.py so behaviour matches.
59
+ CYLINDER_CLASS_WEIGHTS = {
60
+ 39: 2.0, # bottle (best match)
61
+ 71: 1.0, # sink
62
+ 61: 1.0, # toilet
63
+ 41: 0.8, # cup
64
+ 56: 0.8, # chair
65
+ 10: 1.0, # fire hydrant
66
+ 75: 0.8, # vase
67
+ }
68
+
69
+
70
+ # ----------------------------------------------------------------------
71
+ # Data classes
72
+ # ----------------------------------------------------------------------
73
+ @dataclass
74
+ class CylinderROI:
75
+ mask: np.ndarray # uint8 HxW, 255 inside cylinder
76
+ bbox: tuple[int, int, int, int] # x1,y1,x2,y2 in original image
77
+ cls_name: str
78
+ conf: float
79
+ polygon_norm: np.ndarray # Nx2 normalized polygon vertices
80
+
81
+
82
+ @dataclass
83
+ class ValveCandidate:
84
+ contour: np.ndarray # (N,1,2) int32, image pixel coords
85
+ area: float
86
+ perimeter: float
87
+ circularity: float
88
+ aspect: float
89
+ centrality: float
90
+ dark_center_ratio: float
91
+ score: float
92
+
93
+
94
+ @dataclass
95
+ class FivePetalGeometry:
96
+ center: tuple[float, float]
97
+ center_radius: float
98
+ sector_angles: np.ndarray
99
+ sector_radii: np.ndarray
100
+ sector_hole_radii: np.ndarray
101
+ sector_matched: np.ndarray
102
+ ring_radius: float
103
+ hole_radius: float
104
+ matched_outer: int
105
+ inner_spots: int
106
+ score: float
107
+
108
+
109
+ # ----------------------------------------------------------------------
110
+ # I/O helpers (unicode-safe for Chinese paths)
111
+ # ----------------------------------------------------------------------
112
+ def imread_unicode(path: Path) -> np.ndarray | None:
113
+ try:
114
+ raw = np.fromfile(str(path), dtype=np.uint8)
115
+ except Exception:
116
+ return None
117
+ if raw.size == 0:
118
+ return None
119
+ return cv2.imdecode(raw, cv2.IMREAD_COLOR)
120
+
121
+
122
+ def read_yolo_bbox(
123
+ label_path: Path,
124
+ img_w: int,
125
+ img_h: int,
126
+ class_id: int = 1,
127
+ ) -> tuple[int, int, int, int] | None:
128
+ """Read the first matching bbox (class, cx, cy, w, h) from a YOLO
129
+ label file and return it in ``(x1, y1, x2, y2)`` pixel coords.
130
+ Returns ``None`` if the file is missing / empty / has no bbox for
131
+ the given class. Lines that appear to be segmentation labels
132
+ (more than 5 fields) are ignored so the function doesn't confuse
133
+ a polygon output with a bbox prior.
134
+ """
135
+ if not label_path.exists():
136
+ return None
137
+ try:
138
+ text = label_path.read_text(encoding="utf-8")
139
+ except Exception:
140
+ return None
141
+ for line in text.splitlines():
142
+ parts = line.strip().split()
143
+ # Proper YOLO bbox lines have exactly 5 fields.
144
+ if len(parts) != 5:
145
+ continue
146
+ try:
147
+ cls = int(float(parts[0]))
148
+ except ValueError:
149
+ continue
150
+ if cls != class_id:
151
+ continue
152
+ try:
153
+ cx, cy, bw, bh = (float(p) for p in parts[1:5])
154
+ except ValueError:
155
+ continue
156
+ x1 = int(round((cx - bw / 2.0) * img_w))
157
+ y1 = int(round((cy - bh / 2.0) * img_h))
158
+ x2 = int(round((cx + bw / 2.0) * img_w))
159
+ y2 = int(round((cy + bh / 2.0) * img_h))
160
+ x1 = max(0, min(img_w - 1, x1))
161
+ y1 = max(0, min(img_h - 1, y1))
162
+ x2 = max(0, min(img_w, x2))
163
+ y2 = max(0, min(img_h, y2))
164
+ if x2 - x1 < 5 or y2 - y1 < 5:
165
+ return None
166
+ return (x1, y1, x2, y2)
167
+ return None
168
+
169
+
170
+ def imwrite_unicode(path: Path, image: np.ndarray) -> bool:
171
+ suffix = path.suffix.lower()
172
+ ext = ".jpg" if suffix in {".jpg", ".jpeg"} else ".png"
173
+ ok, buf = cv2.imencode(ext, image)
174
+ if not ok:
175
+ return False
176
+ path.parent.mkdir(parents=True, exist_ok=True)
177
+ buf.tofile(str(path))
178
+ return True
179
+
180
+
181
+ # ----------------------------------------------------------------------
182
+ # Stage 1 — cylinder locator (YOLO11x-seg)
183
+ # ----------------------------------------------------------------------
184
+ class CylinderLocator:
185
+ """Locate the gas cylinder to restrict the valve search area."""
186
+
187
+ def __init__(self, model_path: str, device: str = "cpu") -> None:
188
+ from ultralytics import YOLO
189
+
190
+ print(f"[Cylinder] Loading {model_path} on device={device} ...", flush=True)
191
+ self.model = YOLO(model_path)
192
+ self.device = device
193
+ self.conf_threshold = 0.01
194
+ self.min_area_ratio = 0.03
195
+ self.max_dist_ratio = 0.35
196
+
197
+ def locate(self, img: np.ndarray) -> CylinderROI | None:
198
+ h, w = img.shape[:2]
199
+ cx, cy = w / 2.0, h / 2.0
200
+ diag = float(w * w + h * h) ** 0.5
201
+ total_area = float(w * h)
202
+
203
+ result = self.model(
204
+ img,
205
+ conf=self.conf_threshold,
206
+ device=self.device,
207
+ verbose=False,
208
+ )[0]
209
+
210
+ if result.masks is None:
211
+ return None
212
+
213
+ best: CylinderROI | None = None
214
+ best_score = -1.0
215
+
216
+ for i in range(len(result.masks.data)):
217
+ cls_id = int(result.boxes.cls[i])
218
+ if cls_id not in CYLINDER_CLASS_WEIGHTS:
219
+ continue
220
+
221
+ conf = float(result.boxes.conf[i])
222
+ x1, y1, x2, y2 = result.boxes.xyxy[i].tolist()
223
+
224
+ box_area = (x2 - x1) * (y2 - y1)
225
+ area_ratio = box_area / total_area
226
+ if area_ratio < self.min_area_ratio:
227
+ continue
228
+
229
+ bcx = (x1 + x2) / 2.0
230
+ bcy = (y1 + y2) / 2.0
231
+ dist_ratio = ((bcx - cx) ** 2 + (bcy - cy) ** 2) ** 0.5 / diag
232
+ if dist_ratio > self.max_dist_ratio:
233
+ continue
234
+
235
+ centrality_bonus = 1.0 + (1.0 - dist_ratio / self.max_dist_ratio)
236
+ score = conf * CYLINDER_CLASS_WEIGHTS[cls_id] * centrality_bonus
237
+ if score <= best_score:
238
+ continue
239
+
240
+ poly_norm = result.masks.xyn[i]
241
+ if len(poly_norm) < 3:
242
+ continue
243
+
244
+ pts = (poly_norm * np.array([w, h])).astype(np.int32).reshape(-1, 1, 2)
245
+ mask = np.zeros((h, w), dtype=np.uint8)
246
+ cv2.fillPoly(mask, [pts], 255)
247
+
248
+ best = CylinderROI(
249
+ mask=mask,
250
+ bbox=(int(x1), int(y1), int(x2), int(y2)),
251
+ cls_name=result.names[cls_id],
252
+ conf=conf,
253
+ polygon_norm=poly_norm,
254
+ )
255
+ best_score = score
256
+
257
+ return best
258
+
259
+
260
+ # ----------------------------------------------------------------------
261
+ # Stage 2 — white handwheel detector
262
+ # ----------------------------------------------------------------------
263
+ def _compute_bright_mask(
264
+ img: np.ndarray,
265
+ percentile: float,
266
+ min_thresh: int,
267
+ neutral_tol: int,
268
+ ) -> tuple[np.ndarray, np.ndarray, int]:
269
+ """Threshold the L channel (LAB) to isolate bright, colour-neutral
270
+ pixels globally. Returns ``(bright_mask, L, threshold)``."""
271
+ lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
272
+ L, A, B = cv2.split(lab)
273
+
274
+ # Exclude extreme overexposed pixels (often from the direct light
275
+ # source) so they do not dominate the percentile computation.
276
+ L_for_stats = L[(L > 30) & (L < 252)]
277
+ if L_for_stats.size == 0:
278
+ L_for_stats = L.reshape(-1)
279
+
280
+ pct_val = float(np.percentile(L_for_stats, percentile))
281
+ thresh_val = int(max(pct_val, min_thresh))
282
+
283
+ # Neutral-colour check: LAB a,b channels are stored offset by 128,
284
+ # so a neutral grey/white has |a-128|+|b-128| small. A warm wall has
285
+ # a noticeable yellow tint (b > 128 → diff > 0). The valve itself
286
+ # is largely neutral even under warm lighting because its white
287
+ # surface reflects the dominant light colour but with less hue.
288
+ a_diff = np.abs(A.astype(np.int16) - 128)
289
+ b_diff = np.abs(B.astype(np.int16) - 128)
290
+ neutral = (a_diff + b_diff) < neutral_tol
291
+
292
+ bright = ((L > thresh_val) & neutral).astype(np.uint8) * 255
293
+ return bright, L, thresh_val
294
+
295
+
296
+ def _find_dark_spots(
297
+ gray: np.ndarray,
298
+ min_radius: int,
299
+ max_radius: int,
300
+ ) -> list[tuple[int, int, int]]:
301
+ """Find small dark circular blobs using SimpleBlobDetector.
302
+
303
+ Returns a list of (x, y, radius) in image coords. These correspond
304
+ to the valve's central bolt and its 5 petal-holes.
305
+ """
306
+ params = cv2.SimpleBlobDetector_Params()
307
+ params.filterByColor = True
308
+ params.blobColor = 0 # dark blobs on light background
309
+ params.filterByArea = True
310
+ params.minArea = float(np.pi * min_radius * min_radius)
311
+ params.maxArea = float(np.pi * max_radius * max_radius)
312
+ params.filterByCircularity = True
313
+ params.minCircularity = 0.45 # loosened to catch slightly-ellipsoidal holes
314
+ params.filterByConvexity = True
315
+ params.minConvexity = 0.70
316
+ params.filterByInertia = True
317
+ params.minInertiaRatio = 0.25
318
+ params.minThreshold = 20
319
+ params.maxThreshold = 220
320
+ params.thresholdStep = 10
321
+
322
+ detector = cv2.SimpleBlobDetector_create(params)
323
+ kps = detector.detect(gray)
324
+ return [(int(k.pt[0]), int(k.pt[1]), int(k.size / 2.0)) for k in kps]
325
+
326
+
327
+ def _filter_spots_on_bright_surface(
328
+ spots: list[tuple[int, int, int]],
329
+ L: np.ndarray,
330
+ min_surround_L: int,
331
+ ring_radius_scale: float = 2.2,
332
+ ) -> list[tuple[int, int, int]]:
333
+ """Keep only spots whose immediate surroundings are bright.
334
+
335
+ The valve bolt / petal-holes sit on a white handwheel; chain links
336
+ and dark text on grey cylinder sit on a darker surface. Testing the
337
+ mean L of a ring just outside the spot reliably separates them.
338
+ """
339
+ h, w = L.shape[:2]
340
+ kept: list[tuple[int, int, int]] = []
341
+ for (x, y, r) in spots:
342
+ check_r = int(max(r, 6) * ring_radius_scale)
343
+ y1 = max(0, y - check_r)
344
+ y2 = min(h, y + check_r + 1)
345
+ x1 = max(0, x - check_r)
346
+ x2 = min(w, x + check_r + 1)
347
+ patch = L[y1:y2, x1:x2]
348
+ if patch.size == 0:
349
+ continue
350
+ yi, xi = np.ogrid[y1:y2, x1:x2]
351
+ dist2 = (yi - y) ** 2 + (xi - x) ** 2
352
+ ring = dist2 > (r * 1.4) ** 2
353
+ if not ring.any():
354
+ continue
355
+ surround_mean = float(patch[ring].mean())
356
+ if surround_mean >= min_surround_L:
357
+ kept.append((x, y, r))
358
+ return kept
359
+
360
+
361
+ def _cluster_spots(
362
+ spots: list[tuple[int, int, int]],
363
+ max_gap: float,
364
+ min_cluster_size: int,
365
+ max_diameter: float | None = None,
366
+ ) -> list[list[tuple[int, int, int]]]:
367
+ """Single-link clustering by proximity, with an optional diameter
368
+ cap. Two spots belong to the same cluster if their centres are
369
+ within ``max_gap`` pixels. Clusters whose furthest-pair distance
370
+ exceeds ``max_diameter`` are split by dropping outliers until they
371
+ shrink below the cap (this handles cases where a wire bridges
372
+ valve-hole spots with unrelated background spots).
373
+ """
374
+ n = len(spots)
375
+ if n == 0:
376
+ return []
377
+
378
+ parent = list(range(n))
379
+
380
+ def find(x: int) -> int:
381
+ while parent[x] != x:
382
+ parent[x] = parent[parent[x]]
383
+ x = parent[x]
384
+ return x
385
+
386
+ def union(a: int, b: int) -> None:
387
+ ra, rb = find(a), find(b)
388
+ if ra != rb:
389
+ parent[ra] = rb
390
+
391
+ for i in range(n):
392
+ xi, yi, _ = spots[i]
393
+ for j in range(i + 1, n):
394
+ xj, yj, _ = spots[j]
395
+ d = ((xi - xj) ** 2 + (yi - yj) ** 2) ** 0.5
396
+ if d <= max_gap:
397
+ union(i, j)
398
+
399
+ buckets: dict[int, list[tuple[int, int, int]]] = {}
400
+ for i in range(n):
401
+ r = find(i)
402
+ buckets.setdefault(r, []).append(spots[i])
403
+
404
+ raw_clusters = [c for c in buckets.values() if len(c) >= min_cluster_size]
405
+
406
+ if max_diameter is None:
407
+ return raw_clusters
408
+
409
+ def cluster_diameter(pts: list[tuple[int, int, int]]) -> float:
410
+ xs = np.array([s[0] for s in pts], dtype=np.float32)
411
+ ys = np.array([s[1] for s in pts], dtype=np.float32)
412
+ cx, cy = float(xs.mean()), float(ys.mean())
413
+ dists = np.sqrt((xs - cx) ** 2 + (ys - cy) ** 2)
414
+ return float(dists.max() * 2.0) if dists.size else 0.0
415
+
416
+ compact: list[list[tuple[int, int, int]]] = []
417
+ for cluster in raw_clusters:
418
+ # Iteratively drop the spot farthest from the centroid until the
419
+ # cluster is compact enough, or it shrinks below min size.
420
+ current = list(cluster)
421
+ while len(current) >= min_cluster_size:
422
+ xs = np.array([s[0] for s in current], dtype=np.float32)
423
+ ys = np.array([s[1] for s in current], dtype=np.float32)
424
+ cx, cy = float(xs.mean()), float(ys.mean())
425
+ dists = np.sqrt((xs - cx) ** 2 + (ys - cy) ** 2)
426
+ if float(dists.max() * 2.0) <= max_diameter:
427
+ break
428
+ # Drop the farthest spot and try again
429
+ worst = int(np.argmax(dists))
430
+ current.pop(worst)
431
+ if len(current) >= min_cluster_size:
432
+ if cluster_diameter(current) <= max_diameter:
433
+ compact.append(current)
434
+
435
+ return compact
436
+
437
+
438
+ def _wrap_angle(angle: float) -> float:
439
+ return float((angle + np.pi) % (2.0 * np.pi) - np.pi)
440
+
441
+
442
+ def _build_five_petal_mask(
443
+ shape: tuple[int, int],
444
+ spots: list[tuple[int, int, int]],
445
+ center_hint: tuple[float, float],
446
+ radius_hint: float,
447
+ ) -> tuple[np.ndarray, float, int, int] | None:
448
+ if len(spots) < 3:
449
+ return None
450
+
451
+ cx0, cy0 = center_hint
452
+ keep_r = max(18.0, radius_hint * 1.35)
453
+ keep_r2 = keep_r * keep_r
454
+ local: list[tuple[int, int, int]] = []
455
+ seen: set[tuple[int, int, int]] = set()
456
+ for x, y, r in spots:
457
+ key = (int(x), int(y), int(r))
458
+ if key in seen:
459
+ continue
460
+ seen.add(key)
461
+ if (key[0] - cx0) ** 2 + (key[1] - cy0) ** 2 <= keep_r2:
462
+ local.append(key)
463
+
464
+ if len(local) < 5:
465
+ local = list(seen)
466
+ if len(local) < 3:
467
+ return None
468
+
469
+ d0 = np.array([
470
+ ((x - cx0) ** 2 + (y - cy0) ** 2) ** 0.5 for (x, y, _) in local
471
+ ], dtype=np.float32)
472
+ nearest_idx = int(np.argmin(d0))
473
+ cx, cy = cx0, cy0
474
+ if float(d0[nearest_idx]) <= max(8.0, radius_hint * 0.22):
475
+ cx = 0.80 * cx0 + 0.20 * float(local[nearest_idx][0])
476
+ cy = 0.80 * cy0 + 0.20 * float(local[nearest_idx][1])
477
+
478
+ polar: list[tuple[int, int, int, float, float]] = []
479
+ for x, y, r in local:
480
+ dist = float(((x - cx) ** 2 + (y - cy) ** 2) ** 0.5)
481
+ if dist <= keep_r * 1.05:
482
+ polar.append((x, y, r, dist, float(np.arctan2(y - cy, x - cx))))
483
+ if len(polar) < 3:
484
+ return None
485
+
486
+ dvals = np.array([p[3] for p in polar], dtype=np.float32)
487
+ max_d = float(dvals.max()) if dvals.size else 0.0
488
+ outer_min = max(radius_hint * 0.22, max_d * 0.35)
489
+ outer = [p for p in polar if p[3] >= outer_min]
490
+ if len(outer) < 3:
491
+ outer = sorted(polar, key=lambda item: item[3], reverse=True)[: min(5, len(polar))]
492
+ if len(outer) < 3:
493
+ return None
494
+
495
+ inner_limit = max(radius_hint * 0.34, max_d * 0.32)
496
+ inner_spots = sum(1 for p in polar if p[3] <= inner_limit)
497
+ step = 2.0 * np.pi / 5.0
498
+ outer_angles = np.array([p[4] for p in outer], dtype=np.float32)
499
+ best_base = float(outer_angles[0])
500
+ best_cost = float("inf")
501
+ for ang in outer_angles:
502
+ for k in range(5):
503
+ base = _wrap_angle(float(ang - step * k))
504
+ cost = 0.0
505
+ for obs in outer_angles:
506
+ cost += min(
507
+ abs(_wrap_angle(float(obs - (base + step * j))))
508
+ for j in range(5)
509
+ )
510
+ if cost < best_cost:
511
+ best_cost = cost
512
+ best_base = base
513
+
514
+ sector_angles = np.array([
515
+ _wrap_angle(best_base + step * k) for k in range(5)
516
+ ], dtype=np.float32)
517
+ sector_points: list[list[tuple[int, int, int, float, float]]] = [[] for _ in range(5)]
518
+ ang_errors: list[float] = []
519
+ max_ang_err = step * 0.42
520
+ for item in outer:
521
+ diffs = np.array([
522
+ abs(_wrap_angle(float(item[4] - ang))) for ang in sector_angles
523
+ ], dtype=np.float32)
524
+ idx = int(np.argmin(diffs))
525
+ if float(diffs[idx]) <= max_ang_err:
526
+ sector_points[idx].append(item)
527
+ ang_errors.append(float(diffs[idx]))
528
+
529
+ matched_outer = sum(1 for pts in sector_points if pts)
530
+ if matched_outer < 3:
531
+ return None
532
+
533
+ observed_radii = [
534
+ float(max(pts, key=lambda item: item[3])[3])
535
+ for pts in sector_points if pts
536
+ ]
537
+ if not observed_radii:
538
+ return None
539
+
540
+ petal_hole_r = float(np.median(np.array(observed_radii, dtype=np.float32)))
541
+ tip_r = max(petal_hole_r * 1.55, radius_hint * 1.00)
542
+ tip_r = min(tip_r, max(radius_hint * 1.28, petal_hole_r * 1.75))
543
+ valley_r = max(petal_hole_r * 1.12, tip_r * 0.76)
544
+ valley_r = min(valley_r, tip_r * 0.87)
545
+ shoulder_r = tip_r * 0.95
546
+ shoulder_delta = (np.pi / 5.0) * 0.55
547
+
548
+ pts: list[list[int]] = []
549
+ for ang in sector_angles:
550
+ pts.append([
551
+ int(round(cx + shoulder_r * np.cos(float(ang - shoulder_delta)))),
552
+ int(round(cy + shoulder_r * np.sin(float(ang - shoulder_delta)))),
553
+ ])
554
+ pts.append([
555
+ int(round(cx + tip_r * np.cos(float(ang)))),
556
+ int(round(cy + tip_r * np.sin(float(ang)))),
557
+ ])
558
+ pts.append([
559
+ int(round(cx + shoulder_r * np.cos(float(ang + shoulder_delta)))),
560
+ int(round(cy + shoulder_r * np.sin(float(ang + shoulder_delta)))),
561
+ ])
562
+ mid = float(ang + np.pi / 5.0)
563
+ pts.append([
564
+ int(round(cx + valley_r * np.cos(mid))),
565
+ int(round(cy + valley_r * np.sin(mid))),
566
+ ])
567
+
568
+ poly = np.array(pts, dtype=np.int32).reshape(-1, 1, 2)
569
+ mask = np.zeros(shape, dtype=np.uint8)
570
+ cv2.fillPoly(mask, [poly], 255)
571
+
572
+ mean_ang_err = float(np.mean(ang_errors)) if ang_errors else step
573
+ angular_score = max(0.0, 1.0 - mean_ang_err / (step * 0.45))
574
+ if len(observed_radii) >= 2:
575
+ radii_arr = np.array(observed_radii, dtype=np.float32)
576
+ radius_score = max(0.0, 1.0 - float(radii_arr.std()) / max(1.0, float(radii_arr.mean())))
577
+ else:
578
+ radius_score = 0.5
579
+ inner_score = min(1.0, inner_spots / 2.0)
580
+ score = min(1.0, 0.60 * (matched_outer / 5.0) + 0.20 * angular_score + 0.10 * radius_score + 0.10 * inner_score)
581
+ return mask, float(score), int(matched_outer), int(inner_spots)
582
+
583
+
584
+ def _fit_five_petal_geometry(
585
+ spots: list[tuple[int, int, int]],
586
+ shape: tuple[int, int],
587
+ ) -> FivePetalGeometry | None:
588
+ if len(spots) < 4:
589
+ return None
590
+
591
+ short = float(min(shape))
592
+ max_spot_radius = max(float(s[2]) for s in spots)
593
+ centre_candidates = sorted(spots, key=lambda item: item[2], reverse=True)[: min(6, len(spots))]
594
+ best: FivePetalGeometry | None = None
595
+ best_score = -1.0
596
+ step = 2.0 * np.pi / 5.0
597
+
598
+ for cx_i, cy_i, cr_i in centre_candidates:
599
+ cx = float(cx_i)
600
+ cy = float(cy_i)
601
+ cr = float(cr_i)
602
+ polar: list[tuple[int, int, int, float, float]] = []
603
+ for x, y, r in spots:
604
+ if x == cx_i and y == cy_i and r == cr_i:
605
+ continue
606
+ dist = float(((x - cx) ** 2 + (y - cy) ** 2) ** 0.5)
607
+ if dist <= max(18.0, cr * 0.75):
608
+ continue
609
+ if dist >= short * 0.60:
610
+ continue
611
+ polar.append((x, y, r, dist, float(np.arctan2(y - cy, x - cx))))
612
+
613
+ if len(polar) < 3:
614
+ continue
615
+
616
+ ordered = sorted(polar, key=lambda item: item[3])
617
+ seed_d = np.array([p[3] for p in ordered[: min(5, len(ordered))]], dtype=np.float32)
618
+ ring_seed = float(np.median(seed_d))
619
+ outer_min = max(ring_seed * 0.55, cr * 1.25)
620
+ outer_max = ring_seed * 1.55
621
+ outer = [p for p in polar if outer_min <= p[3] <= outer_max]
622
+ if len(outer) < 3:
623
+ outer_min = max(ring_seed * 0.42, cr * 1.10)
624
+ outer = [p for p in polar if outer_min <= p[3] <= outer_max]
625
+ if len(outer) < 3:
626
+ continue
627
+
628
+ outer_angles = np.array([p[4] for p in outer], dtype=np.float32)
629
+ best_base = float(outer_angles[0])
630
+ best_cost = float("inf")
631
+ for ang in outer_angles:
632
+ for k in range(5):
633
+ base = _wrap_angle(float(ang - step * k))
634
+ cost = 0.0
635
+ for obs in outer_angles:
636
+ cost += min(
637
+ abs(_wrap_angle(float(obs - (base + step * j))))
638
+ for j in range(5)
639
+ )
640
+ if cost < best_cost:
641
+ best_cost = cost
642
+ best_base = base
643
+
644
+ sector_angles = np.array([
645
+ _wrap_angle(best_base + step * k) for k in range(5)
646
+ ], dtype=np.float32)
647
+ sector_points: list[list[tuple[int, int, int, float, float]]] = [[] for _ in range(5)]
648
+ ang_errors: list[float] = []
649
+ for item in outer:
650
+ diffs = np.array([
651
+ abs(_wrap_angle(float(item[4] - ang))) for ang in sector_angles
652
+ ], dtype=np.float32)
653
+ idx = int(np.argmin(diffs))
654
+ if float(diffs[idx]) <= step * 0.43:
655
+ sector_points[idx].append(item)
656
+ ang_errors.append(float(diffs[idx]))
657
+
658
+ matched_outer = sum(1 for pts in sector_points if pts)
659
+ if matched_outer < 3:
660
+ continue
661
+
662
+ outer_radius_ref = float(np.median(np.array([p[3] for p in outer], dtype=np.float32)))
663
+ outer_hole_ref = float(np.median(np.array([p[2] for p in outer], dtype=np.float32)))
664
+
665
+ def pick_sector_point(
666
+ pts: list[tuple[int, int, int, float, float]],
667
+ sector_idx: int,
668
+ radius_ref: float,
669
+ ) -> tuple[int, int, int, float, float]:
670
+ radius_ref = max(1.0, float(radius_ref))
671
+ hole_ref = max(1.0, outer_hole_ref)
672
+ sector_ang = float(sector_angles[sector_idx])
673
+ return min(
674
+ pts,
675
+ key=lambda item: (
676
+ abs(float(item[3]) - radius_ref) / radius_ref
677
+ + 0.16 * abs(_wrap_angle(float(item[4] - sector_ang))) / (step * 0.43)
678
+ - 0.025 * min(2.0, float(item[2]) / hole_ref)
679
+ ),
680
+ )
681
+
682
+ observed = [
683
+ pick_sector_point(pts, idx, outer_radius_ref)
684
+ for idx, pts in enumerate(sector_points) if pts
685
+ ]
686
+ observed_r = np.array([p[3] for p in observed], dtype=np.float32)
687
+ ring_radius = float(np.median(observed_r))
688
+ hole_radius = float(np.median(np.array([p[2] for p in observed], dtype=np.float32)))
689
+ sector_radii = np.full(5, ring_radius, dtype=np.float32)
690
+ sector_hole_radii = np.full(5, hole_radius, dtype=np.float32)
691
+ sector_angles_refined = sector_angles.copy()
692
+ sector_matched = np.zeros(5, dtype=bool)
693
+ accepted_radii: list[float] = []
694
+ for idx, pts in enumerate(sector_points):
695
+ if not pts:
696
+ continue
697
+ picked = pick_sector_point(pts, idx, ring_radius)
698
+ if picked[3] < ring_radius * 0.72 or picked[3] > ring_radius * 1.32:
699
+ continue
700
+ sector_radii[idx] = float(picked[3])
701
+ sector_hole_radii[idx] = float(picked[2])
702
+ sector_matched[idx] = True
703
+ accepted_radii.append(float(picked[3]))
704
+ angle_delta = _wrap_angle(float(picked[4] - sector_angles[idx]))
705
+ blend = 0.55 if abs(angle_delta) <= step * 0.30 else 0.25
706
+ sector_angles_refined[idx] = _wrap_angle(float(sector_angles[idx] + blend * angle_delta))
707
+ sector_angles = sector_angles_refined
708
+ sector_radii = np.clip(sector_radii, ring_radius * 0.80, ring_radius * 1.25)
709
+ sector_hole_radii = np.clip(sector_hole_radii, hole_radius * 0.85, hole_radius * 1.20)
710
+ matched_outer = int(sector_matched.sum())
711
+ if matched_outer < 3:
712
+ continue
713
+ inner_spots = 1 + sum(
714
+ 1 for p in polar
715
+ if p[3] <= max(cr * 1.80, ring_radius * 0.48)
716
+ )
717
+ mean_ang_err = float(np.mean(ang_errors)) if ang_errors else step
718
+ angular_score = max(0.0, 1.0 - mean_ang_err / (step * 0.45))
719
+ radius_values = np.array(accepted_radii, dtype=np.float32)
720
+ radius_score = max(0.0, 1.0 - float(radius_values.std()) / max(1.0, float(radius_values.mean())))
721
+ centre_score = min(1.0, cr / max(1.0, max_spot_radius * 0.85))
722
+ score = min(
723
+ 1.0,
724
+ 0.44 * (matched_outer / 5.0)
725
+ + 0.18 * angular_score
726
+ + 0.12 * radius_score
727
+ + 0.10 * min(1.0, inner_spots / 2.0)
728
+ + 0.16 * centre_score,
729
+ )
730
+ if cr < max_spot_radius * 0.75 and matched_outer <= 3:
731
+ score *= 0.84
732
+ if score > best_score:
733
+ best_score = score
734
+ best = FivePetalGeometry(
735
+ center=(cx, cy),
736
+ center_radius=cr,
737
+ sector_angles=sector_angles,
738
+ sector_radii=sector_radii,
739
+ sector_hole_radii=sector_hole_radii,
740
+ sector_matched=sector_matched,
741
+ ring_radius=ring_radius,
742
+ hole_radius=hole_radius,
743
+ matched_outer=matched_outer,
744
+ inner_spots=inner_spots,
745
+ score=float(score),
746
+ )
747
+
748
+ return best
749
+
750
+
751
+ def _build_radial_five_petal_contour(
752
+ bright: np.ndarray,
753
+ geom: FivePetalGeometry,
754
+ samples: int = 120,
755
+ ) -> np.ndarray | None:
756
+ h, w = bright.shape[:2]
757
+ cx, cy = geom.center
758
+ step = 2.0 * np.pi / 5.0
759
+ sector_radii = np.asarray(geom.sector_radii, dtype=np.float32)
760
+ sector_hole_radii = np.asarray(geom.sector_hole_radii, dtype=np.float32)
761
+ sector_matched = np.asarray(geom.sector_matched, dtype=bool)
762
+ if sector_radii.size != 5:
763
+ sector_radii = np.full(5, geom.ring_radius, dtype=np.float32)
764
+ if sector_hole_radii.size != 5:
765
+ sector_hole_radii = np.full(5, geom.hole_radius, dtype=np.float32)
766
+ if sector_matched.size != 5:
767
+ sector_matched = np.ones(5, dtype=bool)
768
+ sector_tip_r = np.maximum(sector_radii + 2.20 * sector_hole_radii,
769
+ sector_radii * 1.16)
770
+ sector_tip_r = np.maximum(sector_tip_r, geom.center_radius * 2.45)
771
+ sector_tip_r = np.minimum(sector_tip_r, sector_radii * 1.42)
772
+ min_r = max(geom.center_radius * 1.15, float(sector_radii.min()) * 0.35)
773
+ max_r = float(sector_tip_r.max()) * 1.18
774
+
775
+ src = (bright > 0).astype(np.uint8) * 255
776
+ if cv2.countNonZero(src) < 50:
777
+ return None
778
+ raw_src = src.copy()
779
+ mk = max(3, int(0.006 * min(h, w)))
780
+ mk = mk if mk % 2 == 1 else mk + 1
781
+ morph_kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (mk, mk))
782
+ src = cv2.morphologyEx(src, cv2.MORPH_CLOSE, morph_kernel)
783
+ src_cnts, _ = cv2.findContours(src, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
784
+ if not src_cnts:
785
+ return None
786
+ solid = np.zeros_like(src)
787
+ cv2.drawContours(solid, src_cnts, -1, 255, thickness=cv2.FILLED)
788
+
789
+ angles = np.linspace(-np.pi, np.pi, samples, endpoint=False, dtype=np.float32)
790
+ radii: list[float] = []
791
+ priors: list[float] = []
792
+ caps: list[float] = []
793
+ floors: list[float] = []
794
+ evidences: list[float] = []
795
+ lobes: list[float] = []
796
+ radial_grid = np.arange(min_r, max_r + 2.0, 2.0, dtype=np.float32)
797
+ for theta in angles:
798
+ diffs = np.array([
799
+ abs(_wrap_angle(float(theta - sec))) for sec in geom.sector_angles
800
+ ], dtype=np.float32)
801
+ weights = np.exp(-((diffs / (step * 0.72)) ** 2))
802
+ wsum = float(weights.sum())
803
+ if wsum <= 1e-6:
804
+ weights = np.ones(5, dtype=np.float32)
805
+ wsum = 5.0
806
+ local_ring = float(np.dot(weights, sector_radii) / wsum)
807
+ local_hole = float(np.dot(weights, sector_hole_radii) / wsum)
808
+ matched_strength = float(
809
+ np.dot(weights, sector_matched.astype(np.float32)) / wsum
810
+ )
811
+ local_tip = max(
812
+ local_ring + 2.20 * local_hole,
813
+ local_ring * 1.16,
814
+ geom.center_radius * 2.45,
815
+ )
816
+ local_tip = min(local_tip, local_ring * 1.42)
817
+ local_valley = max(local_ring * 0.70, local_tip * 0.58)
818
+ local_valley = min(local_valley, local_tip * 0.82)
819
+ diff = float(diffs.min())
820
+ lobe = max(0.0, float(np.cos(diff * 2.5)))
821
+ prior = local_valley + (local_tip - local_valley) * (lobe ** 0.55)
822
+ priors.append(prior)
823
+ rs = radial_grid[radial_grid <= min(max_r, prior * 1.08)]
824
+ xs = np.round(cx + rs * np.cos(float(theta))).astype(np.int32)
825
+ ys = np.round(cy + rs * np.sin(float(theta))).astype(np.int32)
826
+ valid = (xs >= 0) & (xs < w) & (ys >= 0) & (ys < h)
827
+ cap = prior * (0.965 if matched_strength >= 0.55 else 0.920)
828
+ floor = local_valley * (0.74 if matched_strength >= 0.55 else 0.66)
829
+ if lobe >= 0.60 and matched_strength >= 0.55:
830
+ floor = max(floor, prior * 0.74)
831
+ if matched_strength >= 0.55 and lobe >= 0.35:
832
+ floor = max(floor, prior * (0.74 + 0.14 * lobe))
833
+ if matched_strength >= 0.55:
834
+ radius = prior * (0.88 + 0.05 * lobe)
835
+ else:
836
+ radius = prior * (0.82 + 0.05 * lobe)
837
+ evidence = 0.0
838
+ if np.any(valid):
839
+ rs_v = rs[valid]
840
+ raw_vals = raw_src[ys[valid], xs[valid]] > 0
841
+ solid_vals = solid[ys[valid], xs[valid]] > 0
842
+ raw_fg = raw_vals & (rs_v >= prior * 0.42)
843
+ solid_fg = solid_vals & (rs_v >= prior * 0.42)
844
+ tail = (rs_v >= prior * 0.78) & (rs_v <= prior * 1.06)
845
+ raw_tail_density = (
846
+ float(raw_vals[tail].sum()) / float(max(1, int(tail.sum())))
847
+ if np.any(tail) else 0.0
848
+ )
849
+ solid_tail_density = (
850
+ float(solid_vals[tail].sum()) / float(max(1, int(tail.sum())))
851
+ if np.any(tail) else 0.0
852
+ )
853
+ raw_idxs = np.array([], dtype=np.int64)
854
+ if np.any(raw_fg):
855
+ raw_support = np.convolve(
856
+ raw_fg.astype(np.uint8), np.ones(5, dtype=np.uint8),
857
+ mode="same",
858
+ )
859
+ raw_idxs = np.flatnonzero((raw_support >= 2) & (rs_v >= prior * 0.48))
860
+ solid_idxs = np.array([], dtype=np.int64)
861
+ if np.any(solid_fg):
862
+ solid_support = np.convolve(
863
+ solid_fg.astype(np.uint8), np.ones(5, dtype=np.uint8),
864
+ mode="same",
865
+ )
866
+ solid_idxs = np.flatnonzero((solid_support >= 2) & (rs_v >= prior * 0.48))
867
+ if raw_idxs.size:
868
+ measured = float(rs_v[raw_idxs[-1]])
869
+ strong_raw_edge = raw_tail_density >= max(0.26, 0.42 - 0.18 * lobe)
870
+ evidence = max(evidence, raw_tail_density, 0.42 if measured >= prior * 0.78 else 0.20)
871
+ if measured >= prior * 0.95:
872
+ edge_cap = prior * (0.980 if strong_raw_edge else 0.925)
873
+ radius = min(measured, edge_cap)
874
+ if strong_raw_edge:
875
+ evidence = max(evidence, 0.64)
876
+ elif solid_idxs.size and measured < prior * (0.82 if lobe >= 0.45 else 0.74):
877
+ filled = float(rs_v[solid_idxs[-1]])
878
+ if matched_strength >= 0.50 and solid_tail_density >= 0.20:
879
+ target = min(filled, prior * (0.935 if lobe >= 0.45 else 0.875))
880
+ blend = min(0.62, 0.32 + 0.30 * matched_strength)
881
+ radius = (1.0 - blend) * measured + blend * target
882
+ evidence = max(evidence, solid_tail_density, 0.34)
883
+ else:
884
+ radius = measured
885
+ else:
886
+ radius = measured
887
+ elif solid_idxs.size:
888
+ measured = float(rs_v[solid_idxs[-1]])
889
+ if matched_strength >= 0.55 and solid_tail_density >= 0.24:
890
+ radius = min(measured, prior * (0.940 if lobe >= 0.45 else 0.860))
891
+ evidence = max(evidence, solid_tail_density, 0.32)
892
+ elif measured < prior * 0.72:
893
+ radius = 0.42 * prior + 0.58 * measured
894
+ evidence = max(evidence, solid_tail_density * 0.60)
895
+ else:
896
+ radius = min(measured, prior * 0.900)
897
+ evidence = max(evidence, solid_tail_density * 0.50)
898
+ radius = max(floor, min(cap, radius))
899
+ caps.append(cap)
900
+ floors.append(floor)
901
+ evidences.append(evidence)
902
+ lobes.append(lobe)
903
+ radii.append(radius)
904
+
905
+ radii_arr = np.array(radii, dtype=np.float32)
906
+ prior_arr = np.array(priors, dtype=np.float32)
907
+ cap_arr = np.array(caps, dtype=np.float32)
908
+ floor_arr = np.array(floors, dtype=np.float32)
909
+ evidence_arr = np.array(evidences, dtype=np.float32)
910
+ lobe_arr = np.array(lobes, dtype=np.float32)
911
+ offsets = np.array([-4, -3, -2, -1, 1, 2, 3, 4], dtype=np.int32)
912
+ for _ in range(2):
913
+ filled_arr = radii_arr.copy()
914
+ for i in range(samples):
915
+ if evidence_arr[i] >= 0.22 or lobe_arr[i] < 0.32:
916
+ continue
917
+ idx = np.mod(i + offsets, samples)
918
+ good = evidence_arr[idx] >= 0.32
919
+ if int(good.sum()) < 3:
920
+ continue
921
+ candidate = float(np.median(radii_arr[idx][good]))
922
+ max_fill = prior_arr[i] * (0.925 if lobe_arr[i] >= 0.50 else 0.880)
923
+ if candidate > radii_arr[i] * 1.08:
924
+ filled_arr[i] = max(radii_arr[i], min(candidate * 0.96, max_fill, cap_arr[i]))
925
+ evidence_arr[i] = max(evidence_arr[i], 0.24)
926
+ radii_arr = np.maximum(floor_arr, np.minimum(cap_arr, filled_arr))
927
+ for _ in range(2):
928
+ median_arr = np.array([
929
+ float(np.median(np.take(radii_arr, np.arange(i - 2, i + 3), mode="wrap")))
930
+ for i in range(samples)
931
+ ], dtype=np.float32)
932
+ radii_arr = np.minimum(radii_arr, median_arr * 1.07)
933
+ radii_arr = np.maximum(radii_arr, np.minimum(median_arr * 0.88, prior_arr * 0.70))
934
+ radii_arr = (
935
+ np.roll(radii_arr, 1) * 0.22
936
+ + radii_arr * 0.56
937
+ + np.roll(radii_arr, -1) * 0.22
938
+ )
939
+ radii_arr = np.maximum(floor_arr, np.minimum(cap_arr, radii_arr))
940
+ radii_arr = np.maximum(floor_arr, np.minimum(cap_arr, radii_arr))
941
+ pts = np.stack([
942
+ np.round(cx + radii_arr * np.cos(angles)).astype(np.int32),
943
+ np.round(cy + radii_arr * np.sin(angles)).astype(np.int32),
944
+ ], axis=1)
945
+ pts[:, 0] = np.clip(pts[:, 0], 0, w - 1)
946
+ pts[:, 1] = np.clip(pts[:, 1], 0, h - 1)
947
+
948
+ mask = np.zeros((h, w), dtype=np.uint8)
949
+ cv2.fillPoly(mask, [pts.reshape(-1, 1, 2)], 255)
950
+ centre_pt = (int(round(cx)), int(round(cy)))
951
+ cv2.circle(mask, centre_pt, max(3, int(round(geom.center_radius * 1.25))), 255, -1)
952
+ for idx in range(5):
953
+ if not bool(sector_matched[idx]):
954
+ continue
955
+ hx = int(round(cx + float(sector_radii[idx]) * np.cos(float(geom.sector_angles[idx]))))
956
+ hy = int(round(cy + float(sector_radii[idx]) * np.sin(float(geom.sector_angles[idx]))))
957
+ if hx < 0 or hx >= w or hy < 0 or hy >= h:
958
+ continue
959
+ hole_r = max(3, int(round(float(sector_hole_radii[idx]) * 1.35)))
960
+ cv2.line(mask, centre_pt, (hx, hy), 255, max(3, int(round(hole_r * 1.15))))
961
+ cv2.circle(mask, (hx, hy), hole_r, 255, -1)
962
+ cnts, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
963
+ if not cnts:
964
+ return None
965
+ return max(cnts, key=cv2.contourArea)
966
+
967
+
968
+ def _find_valve_polygon_in_bbox(
969
+ img: np.ndarray,
970
+ bbox: tuple[int, int, int, int],
971
+ *,
972
+ bbox_expand_ratio: float = 0.08,
973
+ neutral_tol: int = 90,
974
+ close_kernel_ratio: float = 0.09, # relative to bbox short edge
975
+ open_kernel_ratio: float = 0.012,
976
+ bridge_erode_ratio: float = 0.030, # larger erosion to break wall bridges
977
+ min_area_ratio_of_bbox: float = 0.03,
978
+ max_area_ratio_of_bbox: float = 1.30,
979
+ require_dark_spots: bool = True,
980
+ min_dark_spots_inside: int = 3,
981
+ dark_spot_min_radius_ratio: float = 0.010, # relative to bbox short edge
982
+ dark_spot_max_radius_ratio: float = 0.15,
983
+ debug_out: Path | None = None,
984
+ ) -> ValveCandidate | None:
985
+ """Find the valve polygon *inside* a given bounding box.
986
+
987
+ This is the primary detection path when a valve bbox prior is
988
+ available (from a pre-existing YOLO bbox label). It is much more
989
+ accurate than a global search because:
990
+
991
+ 1. It crops the image to ``bbox`` (plus a small margin) so
992
+ unrelated bright regions in the scene cannot compete.
993
+ 2. It finds bright, colour-neutral pixels, morph-closes them so
994
+ the 5 petals fuse into a single blob, and picks the largest
995
+ connected component.
996
+ 3. It *validates* that component by requiring 3+ dark circular
997
+ spots (valve bolt + petal holes) inside it. If the validation
998
+ fails, we return ``None`` so the caller can fall back to the
999
+ spot-seeded global detector.
1000
+
1001
+ All pixel parameters are scaled by the bbox short edge so the
1002
+ method works at any image resolution / valve size.
1003
+ """
1004
+ h_img, w_img = img.shape[:2]
1005
+ x1, y1, x2, y2 = bbox
1006
+ bw, bh = x2 - x1, y2 - y1
1007
+ if bw < 20 or bh < 20:
1008
+ return None
1009
+
1010
+ # Expand bbox slightly so the valve outer rim isn't clipped.
1011
+ ex = int(bbox_expand_ratio * bw)
1012
+ ey = int(bbox_expand_ratio * bh)
1013
+ cx1 = max(0, x1 - ex)
1014
+ cy1 = max(0, y1 - ey)
1015
+ cx2 = min(w_img, x2 + ex)
1016
+ cy2 = min(h_img, y2 + ey)
1017
+
1018
+ crop = img[cy1:cy2, cx1:cx2]
1019
+ ch, cw = crop.shape[:2]
1020
+ short = min(cw, ch)
1021
+ if short < 30:
1022
+ return None
1023
+
1024
+ # Scale-aware morphology.
1025
+ ck = max(9, int(close_kernel_ratio * short))
1026
+ ok = max(3, int(open_kernel_ratio * short))
1027
+ ck = ck if ck % 2 == 1 else ck + 1
1028
+ ok = ok if ok % 2 == 1 else ok + 1
1029
+ kernel_close = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (ck, ck))
1030
+ kernel_open = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (ok, ok))
1031
+
1032
+ lab = cv2.cvtColor(crop, cv2.COLOR_BGR2LAB)
1033
+ L, A, B = cv2.split(lab)
1034
+ a_diff = np.abs(A.astype(np.int16) - 128)
1035
+ b_diff = np.abs(B.astype(np.int16) - 128)
1036
+ # Relax neutrality: warm studio lighting tints the white valve
1037
+ # slightly yellow/orange, so a strict neutral filter can reject
1038
+ # half the petals. Saturation ~ a_diff + b_diff ; we keep pixels
1039
+ # whose colour is at least "not vivid".
1040
+ neutral = (a_diff + b_diff) < neutral_tol
1041
+
1042
+ neutral_L = L[neutral & (L < 252)]
1043
+ if neutral_L.size < 200:
1044
+ return None
1045
+ # Initial coarse threshold from percentiles. This is only used when
1046
+ # the dark-spot cluster localization fails and we need a global
1047
+ # threshold across the whole bbox.
1048
+ q45 = float(np.percentile(neutral_L, 45))
1049
+ q70 = float(np.percentile(neutral_L, 70))
1050
+ local_thresh = int(max(110.0, (q45 + q70) / 2.0 - 5))
1051
+
1052
+ bright = ((L > local_thresh) & neutral).astype(np.uint8) * 255
1053
+
1054
+ # --------------------------------------------------------------
1055
+ # Localize the valve centre using dark circular spots (bolt + petal
1056
+ # holes). The cluster of small dark circles is an extremely strong
1057
+ # valve signature, much more reliable than bright-pixel geometry.
1058
+ # We then constrain the bright-valve search to a small disk around
1059
+ # the cluster centroid so adjacent walls / background cannot be
1060
+ # picked up even when they are bright-connected to the valve.
1061
+ # --------------------------------------------------------------
1062
+ gray = cv2.cvtColor(crop, cv2.COLOR_BGR2GRAY)
1063
+ gray_blur = cv2.GaussianBlur(gray, (5, 5), 0)
1064
+ spot_min_r = max(3, int(dark_spot_min_radius_ratio * short))
1065
+ spot_max_r = max(6, int(dark_spot_max_radius_ratio * short))
1066
+ all_spots = _find_dark_spots(gray_blur, spot_min_r, spot_max_r)
1067
+
1068
+ # Keep only spots that lie inside the (unexpanded) input bbox. The
1069
+ # bbox margin may contain non-valve dark spots (fixture bolts /
1070
+ # text) we must ignore.
1071
+ inner_x1, inner_y1 = x1 - cx1, y1 - cy1
1072
+ inner_x2, inner_y2 = x2 - cx1, y2 - cy1
1073
+ spots_in_bbox = [
1074
+ (x, y, r) for (x, y, r) in all_spots
1075
+ if inner_x1 <= x < inner_x2 and inner_y1 <= y < inner_y2
1076
+ ]
1077
+
1078
+ # Adaptive surround-brightness threshold: instead of a hard-coded
1079
+ # value (which fails on shadowed valves), require each spot's
1080
+ # surrounding ring to be at least as bright as the 45-th percentile
1081
+ # of neutral pixels inside the bbox. This is automatically calibrated
1082
+ # per-image so shadowed valves still pass.
1083
+ surround_L = int(max(80, min(160, q45 - 10)))
1084
+ spots_on_white = _filter_spots_on_bright_surface(
1085
+ spots_in_bbox, L, min_surround_L=surround_L,
1086
+ )
1087
+
1088
+ # Cluster the surviving spots. For a valve we expect 3+ spots in a
1089
+ # compact cluster (diameter ~ 15-30% of bbox short).
1090
+ clusters = _cluster_spots(
1091
+ spots_on_white,
1092
+ max_gap=0.18 * short,
1093
+ min_cluster_size=3,
1094
+ max_diameter=0.40 * short,
1095
+ )
1096
+
1097
+ spot_centre: tuple[float, float] | None = None
1098
+ spot_radius_hint: float = 0.18 * short
1099
+ n_cluster_spots = 0
1100
+ best = None
1101
+ five_petal_geom = _fit_five_petal_geometry(spots_on_white, bright.shape)
1102
+ five_petal_score = five_petal_geom.score if five_petal_geom is not None else 0.0
1103
+ five_petal_outer = five_petal_geom.matched_outer if five_petal_geom is not None else 0
1104
+ five_petal_inner = five_petal_geom.inner_spots if five_petal_geom is not None else 0
1105
+ use_five_petal_radial = (
1106
+ five_petal_geom is not None
1107
+ and five_petal_geom.score >= 0.62
1108
+ and (
1109
+ five_petal_geom.matched_outer >= 4
1110
+ or (
1111
+ five_petal_geom.matched_outer >= 3
1112
+ and five_petal_geom.inner_spots >= 1
1113
+ )
1114
+ )
1115
+ )
1116
+ if use_five_petal_radial and five_petal_geom is not None:
1117
+ spot_centre = five_petal_geom.center
1118
+ n_cluster_spots = len(spots_on_white)
1119
+ spot_radius_hint = min(
1120
+ 0.34 * short,
1121
+ max(
1122
+ 0.12 * short,
1123
+ (five_petal_geom.ring_radius + 2.90 * five_petal_geom.hole_radius) * 1.08,
1124
+ ),
1125
+ )
1126
+ if clusters and not use_five_petal_radial:
1127
+ # Pick the cluster whose centroid is closest to bbox centre.
1128
+ bcx_crop = (inner_x1 + inner_x2) / 2.0
1129
+ bcy_crop = (inner_y1 + inner_y2) / 2.0
1130
+ best_d = float("inf")
1131
+ for c in clusters:
1132
+ xs = np.array([s[0] for s in c], dtype=np.float32)
1133
+ ys = np.array([s[1] for s in c], dtype=np.float32)
1134
+ cx_c = float(xs.mean())
1135
+ cy_c = float(ys.mean())
1136
+ d = ((cx_c - bcx_crop) ** 2 + (cy_c - bcy_crop) ** 2) ** 0.5
1137
+ if d < best_d:
1138
+ best_d = d
1139
+ best = (cx_c, cy_c, c)
1140
+ if best is not None:
1141
+ cx_c, cy_c, c = best
1142
+ n_cluster_spots = len(c)
1143
+ xs = np.array([s[0] for s in c], dtype=np.float32)
1144
+ ys = np.array([s[1] for s in c], dtype=np.float32)
1145
+ # The *bbox centre* is usually closer to the true valve
1146
+ # geometric centre than the cluster centroid (which can be
1147
+ # pulled sideways when one half of the petals is in shadow
1148
+ # and a few dark-spot detections are missed). We blend
1149
+ # heavily toward the bbox centre.
1150
+ cx_final = 0.35 * cx_c + 0.65 * bcx_crop
1151
+ cy_final = 0.35 * cy_c + 0.65 * bcy_crop
1152
+ # Use the cluster extent relative to the blended centre so
1153
+ # the radius fully covers every detected petal-hole, then
1154
+ # pad out by ~2.0x to reach the petal tips.
1155
+ dists_final = np.sqrt((xs - cx_final) ** 2 +
1156
+ (ys - cy_final) ** 2)
1157
+ max_d = float(dists_final.max()) if dists_final.size else 0.0
1158
+ avg_r = float(np.mean([s[2] for s in c])) if c else 10.0
1159
+ # Petal-holes sit at ~60% of the valve radius. Enlarge by
1160
+ # ~2.0x to comfortably enclose every petal tip. Clamp to a
1161
+ # safe band so we never reach into background.
1162
+ spot_radius_hint = min(
1163
+ 0.22 * short,
1164
+ max(0.10 * short, (max_d + avg_r) * 2.0),
1165
+ )
1166
+ spot_centre = (cx_final, cy_final)
1167
+
1168
+ # --------------------------------------------------------------
1169
+ # Build the bright-valve mask. When a dark-spot cluster was found,
1170
+ # compute a *local* Otsu threshold on a disk around the cluster
1171
+ # centroid (this handles uneven illumination: one half of the valve
1172
+ # can be in shadow with half the luminance of the lit half). Then
1173
+ # only keep bright pixels within ``spot_radius_hint`` of the
1174
+ # centroid. Otherwise fall back to the erode / edge-removal trick.
1175
+ # --------------------------------------------------------------
1176
+ if spot_centre is not None:
1177
+ Ycoord, Xcoord = np.ogrid[:ch, :cw]
1178
+ radial = (Xcoord - spot_centre[0]) ** 2 + (Ycoord - spot_centre[1]) ** 2
1179
+ # Inner seed disk: very tight around cluster; any bright
1180
+ # component that overlaps this disk is presumed to belong to
1181
+ # the valve and is kept entirely (even petals that extend
1182
+ # outside ``spot_radius_hint``).
1183
+ seed_r = max(0.05 * short, spot_radius_hint * 0.55)
1184
+ seed_disk = (radial <= seed_r ** 2)
1185
+ # Outer reject disk: anything entirely outside this radius is
1186
+ # background and is dropped. Kept close to spot_radius_hint so
1187
+ # wall / ceiling blobs cannot extend far into the mask.
1188
+ outer_r = spot_radius_hint * 1.10
1189
+ outer_disk = (radial <= outer_r ** 2)
1190
+
1191
+ # Local Otsu threshold on the outer disk: separates valve
1192
+ # petals (bright) from the darker cylinder body / deep shadow.
1193
+ local_L_vals = L[outer_disk]
1194
+ if local_L_vals.size >= 200:
1195
+ lv = local_L_vals[(local_L_vals > 20) & (local_L_vals < 252)]
1196
+ if lv.size >= 100:
1197
+ otsu_thr, _ = cv2.threshold(
1198
+ lv.astype(np.uint8), 0, 255,
1199
+ cv2.THRESH_BINARY + cv2.THRESH_OTSU,
1200
+ )
1201
+ local_thresh = int(max(90, min(240, otsu_thr)))
1202
+
1203
+ valve_mask = ((L > local_thresh) & neutral).astype(np.uint8) * 255
1204
+
1205
+ # Break thin bright bridges that may connect the valve to the
1206
+ # surrounding wall / ceiling (the bolt region often spills
1207
+ # into background through single-pixel-thin links).
1208
+ _ok = max(3, int(0.010 * short))
1209
+ _ok = _ok if _ok % 2 == 1 else _ok + 1
1210
+ _open_k = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (_ok, _ok))
1211
+ valve_mask_clean = cv2.morphologyEx(valve_mask, cv2.MORPH_OPEN,
1212
+ _open_k)
1213
+
1214
+ # Intersect with the outer disk, then keep only connected
1215
+ # components that are *well centred* on the seed disk. We
1216
+ # measure this by: fraction of component area inside the tight
1217
+ # spot_radius_hint. Components that are mostly wall/ceiling
1218
+ # (i.e. reach far beyond the hint) are rejected even when they
1219
+ # happen to overlap the seed disk by a few pixels.
1220
+ valve_mask_outer = valve_mask_clean * outer_disk.astype(np.uint8)
1221
+ num_lb, labs = cv2.connectedComponents(valve_mask_outer)
1222
+ if num_lb > 1:
1223
+ tight_disk = (radial <= spot_radius_hint ** 2)
1224
+ keep = np.zeros_like(valve_mask_outer, dtype=bool)
1225
+ for lbl in range(1, num_lb):
1226
+ comp = (labs == lbl)
1227
+ area = int(comp.sum())
1228
+ if area == 0:
1229
+ continue
1230
+ # Require overlap with seed disk.
1231
+ if not np.any(comp & seed_disk):
1232
+ continue
1233
+ # Require that at least 55% of the component lies
1234
+ # inside the tight spot_radius_hint. Big walls fail
1235
+ # this because only a small tongue reaches the seed.
1236
+ inside = int((comp & tight_disk).sum())
1237
+ if inside / float(area) < 0.55:
1238
+ continue
1239
+ keep |= comp
1240
+ if keep.any():
1241
+ bright_interior = keep.astype(np.uint8) * 255
1242
+ else:
1243
+ # Nothing survived; fall back to the tight disk mask.
1244
+ bright_interior = valve_mask_clean * tight_disk.astype(np.uint8)
1245
+ else:
1246
+ bright_interior = valve_mask_clean * outer_disk.astype(np.uint8)
1247
+ else:
1248
+ # Fallback: erode bright, remove border-connected, dilate back.
1249
+ erode_k = max(3, int(bridge_erode_ratio * short))
1250
+ erode_k = erode_k if erode_k % 2 == 1 else erode_k + 1
1251
+ bridge_kernel = cv2.getStructuringElement(
1252
+ cv2.MORPH_ELLIPSE, (erode_k, erode_k),
1253
+ )
1254
+ bright_eroded = cv2.erode(bright, bridge_kernel, iterations=1)
1255
+
1256
+ num_b, labels_b = cv2.connectedComponents(bright_eroded)
1257
+ edge_mask = np.zeros_like(bright_eroded, dtype=bool)
1258
+ edge_mask[0, :] = True
1259
+ edge_mask[-1, :] = True
1260
+ edge_mask[:, 0] = True
1261
+ edge_mask[:, -1] = True
1262
+ edge_labels = np.unique(labels_b[edge_mask & (labels_b > 0)])
1263
+ if edge_labels.size > 0:
1264
+ keep_mask = ~np.isin(labels_b, edge_labels)
1265
+ bright_eroded = (bright_eroded * keep_mask.astype(np.uint8))
1266
+
1267
+ bright_interior = cv2.dilate(bright_eroded, bridge_kernel, iterations=1)
1268
+ if bright_interior.sum() < 100:
1269
+ bright_interior = bright
1270
+
1271
+ bbox_area = float(bw * bh)
1272
+
1273
+ if use_five_petal_radial and five_petal_geom is not None:
1274
+ edge_bright = ((L > local_thresh) & neutral).astype(np.uint8) * 255
1275
+ if cv2.countNonZero(bright_interior) >= 200:
1276
+ edge_bright = bright_interior
1277
+ cnt_local_radial = _build_radial_five_petal_contour(
1278
+ edge_bright, five_petal_geom,
1279
+ )
1280
+ if cnt_local_radial is not None:
1281
+ spots_inside = 0
1282
+ if require_dark_spots:
1283
+ for (sx, sy, sr) in all_spots:
1284
+ if cv2.pointPolygonTest(
1285
+ cnt_local_radial, (float(sx), float(sy)), False,
1286
+ ) >= 0:
1287
+ spots_inside += 1
1288
+ if spots_inside < min_dark_spots_inside:
1289
+ cnt_local_radial = None
1290
+ if cnt_local_radial is not None:
1291
+ cnt_global = cnt_local_radial.copy()
1292
+ cnt_global[:, 0, 0] += cx1
1293
+ cnt_global[:, 0, 1] += cy1
1294
+ area_global = float(cv2.contourArea(cnt_global))
1295
+ perimeter = float(cv2.arcLength(cnt_global, True))
1296
+ circularity = (4.0 * np.pi * area_global / (perimeter ** 2)
1297
+ if perimeter > 0 else 0.0)
1298
+ _, _, gbw, gbh = cv2.boundingRect(cnt_global)
1299
+ aspect = max(gbw, gbh) / max(1, min(gbw, gbh))
1300
+ bbox_cx = (x1 + x2) / 2.0
1301
+ bbox_cy = (y1 + y2) / 2.0
1302
+ gcx = five_petal_geom.center[0] + cx1
1303
+ gcy = five_petal_geom.center[1] + cy1
1304
+ d_centre = ((gcx - bbox_cx) ** 2 + (gcy - bbox_cy) ** 2) ** 0.5
1305
+ max_centre_d = 0.5 * (bw ** 2 + bh ** 2) ** 0.5
1306
+ centrality = max(0.0, 1.0 - d_centre / max_centre_d) if max_centre_d > 0 else 0.0
1307
+ score = (
1308
+ 0.18 * centrality
1309
+ + 0.22 * min(1.0, area_global / max(1.0, bbox_area))
1310
+ + 0.24 * min(1.0, spots_inside / 7.0)
1311
+ + 0.36 * min(1.0, five_petal_geom.score)
1312
+ )
1313
+ if debug_out is not None:
1314
+ radial_mask = np.zeros_like(edge_bright)
1315
+ cv2.drawContours(
1316
+ radial_mask, [cnt_local_radial], -1, 255,
1317
+ thickness=cv2.FILLED,
1318
+ )
1319
+ _dump_bbox_debug(
1320
+ crop, edge_bright, bright_interior, radial_mask,
1321
+ cnt_local_radial, all_spots, local_thresh, bbox_area,
1322
+ -2,
1323
+ f"OK radial5 area={int(area_global)} "
1324
+ f"spots_in={spots_inside} geom={five_petal_geom.score:.2f}",
1325
+ debug_out,
1326
+ )
1327
+ return ValveCandidate(
1328
+ contour=cnt_global,
1329
+ area=area_global,
1330
+ perimeter=perimeter,
1331
+ circularity=circularity,
1332
+ aspect=aspect,
1333
+ centrality=centrality,
1334
+ dark_center_ratio=min(
1335
+ 1.0,
1336
+ float(max(spots_inside, five_petal_outer + five_petal_inner)) / 7.0,
1337
+ ),
1338
+ score=float(min(1.0, score)),
1339
+ )
1340
+
1341
+ closed = cv2.morphologyEx(bright_interior, cv2.MORPH_CLOSE, kernel_close)
1342
+ cleaned = cv2.morphologyEx(closed, cv2.MORPH_OPEN, kernel_open)
1343
+
1344
+ # Fill interior holes so the 5 petals + bolt pocket form a solid shape.
1345
+ cnts_all, _ = cv2.findContours(cleaned, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
1346
+ if not cnts_all:
1347
+ return None
1348
+ filled = np.zeros_like(cleaned)
1349
+ cv2.drawContours(filled, cnts_all, -1, 255, thickness=cv2.FILLED)
1350
+
1351
+ # Pick the connected component whose centroid is nearest to the
1352
+ # bbox centre AND whose area is within bounds.
1353
+ num_labels, labels_img, stats, centroids = cv2.connectedComponentsWithStats(
1354
+ filled, 8,
1355
+ )
1356
+ if num_labels < 2:
1357
+ return None
1358
+
1359
+ min_area = min_area_ratio_of_bbox * bbox_area
1360
+ max_area = max_area_ratio_of_bbox * bbox_area
1361
+ # Bbox centre in crop coords.
1362
+ bcx_crop = (x1 + x2) / 2.0 - cx1
1363
+ bcy_crop = (y1 + y2) / 2.0 - cy1
1364
+
1365
+ best_label = -1
1366
+ best_score = -1.0
1367
+ for i in range(1, num_labels):
1368
+ area = float(stats[i, cv2.CC_STAT_AREA])
1369
+ if area < min_area or area > max_area:
1370
+ continue
1371
+ ccx, ccy = centroids[i]
1372
+ dist = ((ccx - bcx_crop) ** 2 + (ccy - bcy_crop) ** 2) ** 0.5
1373
+ # Prefer components whose centroid is close to the bbox centre
1374
+ # AND whose area is a sensible fraction of the bbox.
1375
+ norm_dist = dist / (0.5 * (bw ** 2 + bh ** 2) ** 0.5)
1376
+ area_score = min(area / bbox_area, 1.0)
1377
+ score = (1.0 - norm_dist) * 0.7 + area_score * 0.3
1378
+ if score > best_score:
1379
+ best_score = score
1380
+ best_label = i
1381
+
1382
+ if best_label < 0:
1383
+ return None
1384
+
1385
+ comp_mask = (labels_img == best_label).astype(np.uint8) * 255
1386
+
1387
+ # Ensure the mask unambiguously contains every detected cluster
1388
+ # spot (bolt + petal holes). Luminance thresholding sometimes
1389
+ # produces a C-shape that excludes the bolt; drawing filled disks
1390
+ # for the *chosen cluster's* spots patches these gaps so the
1391
+ # resulting contour wraps around the whole valve. We only patch
1392
+ # cluster spots (not every bright-surround spot in the crop) to
1393
+ # avoid latching onto fixture bolts or text.
1394
+ if spot_centre is not None and n_cluster_spots > 0:
1395
+ # ``best`` holds the chosen cluster's (cx, cy, [(x, y, r)]).
1396
+ cluster_spots = best[2] if best is not None else []
1397
+ for (sx, sy, sr) in cluster_spots:
1398
+ cv2.circle(comp_mask, (int(sx), int(sy)),
1399
+ int(sr * 1.3), 255, -1)
1400
+
1401
+ # Hard-clip to a disk around the blended valve centre. This
1402
+ # guarantees the final polygon cannot extend into background
1403
+ # through thin bright bridges (valve stem / neck / lit wall) that
1404
+ # survived the morphology. The clip radius is ~5% past the
1405
+ # petal-tip hint so valve tips aren't truncated but wall bleed is
1406
+ # bounded.
1407
+ if spot_centre is not None:
1408
+ clip_mask = np.zeros_like(comp_mask)
1409
+ cv2.circle(clip_mask,
1410
+ (int(round(spot_centre[0])), int(round(spot_centre[1]))),
1411
+ int(round(spot_radius_hint * 1.05)),
1412
+ 255, -1)
1413
+ comp_mask = cv2.bitwise_and(comp_mask, clip_mask)
1414
+
1415
+ if spot_centre is not None:
1416
+ five_petal = _build_five_petal_mask(
1417
+ comp_mask.shape,
1418
+ spots_in_bbox,
1419
+ spot_centre,
1420
+ spot_radius_hint,
1421
+ )
1422
+ if five_petal is not None:
1423
+ five_petal_mask, five_petal_score, five_petal_outer, five_petal_inner = five_petal
1424
+ geometry_ready = (
1425
+ five_petal_mask is not None
1426
+ and five_petal_score >= 0.50
1427
+ and five_petal_outer >= 3
1428
+ and five_petal_inner >= 1
1429
+ )
1430
+ prior_overlap = float(
1431
+ cv2.countNonZero(cv2.bitwise_and(comp_mask, five_petal_mask))
1432
+ ) / max(1.0, float(cv2.countNonZero(five_petal_mask)))
1433
+ if five_petal_score >= 0.58 and five_petal_outer >= 4:
1434
+ constrain_k = max(5, int(0.018 * short))
1435
+ constrain_k = constrain_k if constrain_k % 2 == 1 else constrain_k + 1
1436
+ constrain_kernel = cv2.getStructuringElement(
1437
+ cv2.MORPH_ELLIPSE, (constrain_k, constrain_k),
1438
+ )
1439
+ prior_band = cv2.dilate(five_petal_mask, constrain_kernel, iterations=1)
1440
+ comp_mask = cv2.bitwise_and(comp_mask, prior_band)
1441
+ if prior_overlap >= 0.20:
1442
+ comp_mask = cv2.bitwise_or(comp_mask, five_petal_mask)
1443
+
1444
+ cnts, _ = cv2.findContours(comp_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
1445
+ if not cnts:
1446
+ return None
1447
+ cnt_local = max(cnts, key=cv2.contourArea)
1448
+
1449
+ # If the contour has a large concavity such that >15% of its
1450
+ # convex-hull area lies OUTSIDE the contour, the valve outline is
1451
+ # likely C-shaped due to a missing lit petal. Replace with the
1452
+ # convex hull to restore a rounded flower-shape.
1453
+ hull_local = cv2.convexHull(cnt_local)
1454
+ cnt_area = float(cv2.contourArea(cnt_local))
1455
+ hull_area = float(cv2.contourArea(hull_local))
1456
+ strong_five_petal = (five_petal_score >= 0.58 and five_petal_outer >= 4)
1457
+ if (not strong_five_petal and hull_area > 0
1458
+ and (hull_area - cnt_area) / hull_area > 0.15):
1459
+ cnt_local = hull_local
1460
+
1461
+ # Translate contour back to full-image coordinates.
1462
+ cnt_global = cnt_local.copy()
1463
+ cnt_global[:, 0, 0] += cx1
1464
+ cnt_global[:, 0, 1] += cy1
1465
+
1466
+ # Validate: the valve should contain dark circular spots
1467
+ # (bolt + petal holes). This rejects bright but wrong blobs.
1468
+ # We reuse ``all_spots`` detected above.
1469
+ spots_inside = 0
1470
+ if require_dark_spots:
1471
+ for (sx, sy, sr) in all_spots:
1472
+ if cv2.pointPolygonTest(cnt_local, (float(sx), float(sy)), False) >= 0:
1473
+ spots_inside += 1
1474
+ if spots_inside < min_dark_spots_inside:
1475
+ if debug_out is not None:
1476
+ _dump_bbox_debug(
1477
+ crop, bright, cleaned, filled, cnt_local, all_spots,
1478
+ local_thresh, bbox_area, best_label,
1479
+ "REJ: spots<{} (have {})".format(
1480
+ min_dark_spots_inside, spots_inside,
1481
+ ),
1482
+ debug_out,
1483
+ )
1484
+ return None
1485
+
1486
+ # Compute shape metrics.
1487
+ area_global = float(cv2.contourArea(cnt_global))
1488
+ perimeter = float(cv2.arcLength(cnt_global, True))
1489
+ circularity = (4.0 * np.pi * area_global / (perimeter ** 2)
1490
+ if perimeter > 0 else 0.0)
1491
+ _, _, gbw, gbh = cv2.boundingRect(cnt_global)
1492
+ aspect = max(gbw, gbh) / max(1, min(gbw, gbh))
1493
+ bbox_cx = (x1 + x2) / 2.0
1494
+ bbox_cy = (y1 + y2) / 2.0
1495
+ M = cv2.moments(cnt_global)
1496
+ if M["m00"] > 0:
1497
+ gcx = M["m10"] / M["m00"]
1498
+ gcy = M["m01"] / M["m00"]
1499
+ else:
1500
+ gcx, gcy = bbox_cx, bbox_cy
1501
+ d_centre = ((gcx - bbox_cx) ** 2 + (gcy - bbox_cy) ** 2) ** 0.5
1502
+ max_centre_d = 0.5 * (bw ** 2 + bh ** 2) ** 0.5
1503
+ centrality = max(0.0, 1.0 - d_centre / max_centre_d) if max_centre_d > 0 else 0.0
1504
+ score = 0.44 * centrality + 0.18 * min(1.0, area_global / bbox_area) \
1505
+ + 0.18 * min(1.0, spots_inside / 7.0) \
1506
+ + 0.20 * min(1.0, five_petal_score)
1507
+
1508
+ if debug_out is not None:
1509
+ _dump_bbox_debug(
1510
+ crop, bright, cleaned, filled, cnt_local, all_spots,
1511
+ local_thresh, bbox_area, best_label,
1512
+ f"OK area={int(area_global)} circ={circularity:.2f} "
1513
+ f"spots_in={spots_inside} cluster_n={n_cluster_spots}",
1514
+ debug_out,
1515
+ )
1516
+
1517
+ return ValveCandidate(
1518
+ contour=cnt_global,
1519
+ area=area_global,
1520
+ perimeter=perimeter,
1521
+ circularity=circularity,
1522
+ aspect=aspect,
1523
+ centrality=centrality,
1524
+ dark_center_ratio=min(1.0, float(max(spots_inside, five_petal_outer + five_petal_inner)) / 7.0),
1525
+ score=float(min(1.0, score)),
1526
+ )
1527
+
1528
+
1529
+ def _dump_bbox_debug(
1530
+ crop: np.ndarray,
1531
+ bright: np.ndarray,
1532
+ cleaned: np.ndarray,
1533
+ filled: np.ndarray,
1534
+ cnt_local: np.ndarray,
1535
+ spots: list[tuple[int, int, int]],
1536
+ local_thresh: int,
1537
+ bbox_area: float,
1538
+ best_label: int,
1539
+ status: str,
1540
+ debug_out: Path,
1541
+ ) -> None:
1542
+ """Save a 2x2 debug panel for the bbox-guided detector."""
1543
+ to_bgr = lambda g: cv2.cvtColor(g, cv2.COLOR_GRAY2BGR)
1544
+
1545
+ panel_crop = crop.copy()
1546
+ for (sx, sy, sr) in spots:
1547
+ cv2.circle(panel_crop, (sx, sy), max(sr, 4), (0, 140, 255), 2)
1548
+ cv2.drawContours(panel_crop, [cnt_local], -1, (0, 255, 0), 3)
1549
+ cv2.putText(panel_crop, f"{status} thr={local_thresh}",
1550
+ (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 255), 2)
1551
+
1552
+ def resize_for_panel(im: np.ndarray) -> np.ndarray:
1553
+ h_, w_ = im.shape[:2]
1554
+ scale = 640.0 / max(h_, w_)
1555
+ if scale >= 1.0:
1556
+ return im
1557
+ return cv2.resize(im, (int(w_ * scale), int(h_ * scale)))
1558
+
1559
+ top = np.hstack([resize_for_panel(panel_crop),
1560
+ resize_for_panel(to_bgr(bright))])
1561
+ bot = np.hstack([resize_for_panel(to_bgr(cleaned)),
1562
+ resize_for_panel(to_bgr(filled))])
1563
+ # pad to same width if needed
1564
+ if top.shape[1] != bot.shape[1]:
1565
+ wmax = max(top.shape[1], bot.shape[1])
1566
+ top = cv2.copyMakeBorder(top, 0, 0, 0, wmax - top.shape[1],
1567
+ cv2.BORDER_CONSTANT, value=(0, 0, 0))
1568
+ bot = cv2.copyMakeBorder(bot, 0, 0, 0, wmax - bot.shape[1],
1569
+ cv2.BORDER_CONSTANT, value=(0, 0, 0))
1570
+ panel = np.vstack([top, bot])
1571
+ imwrite_unicode(debug_out, panel)
1572
+
1573
+
1574
+ def _find_valve_contour(
1575
+ img: np.ndarray,
1576
+ roi: CylinderROI | None,
1577
+ bright_percentile: float = 55.0,
1578
+ min_luminance: int = 135,
1579
+ neutral_tol: int = 90,
1580
+ # Scale-aware pixel params: relative to min(h, w). Tuned for any
1581
+ # image size from 640 up to 4K+.
1582
+ close_kernel_ratio: float = 0.035,
1583
+ open_kernel_ratio: float = 0.0035,
1584
+ min_area_ratio: float = 0.003,
1585
+ max_area_ratio: float = 0.14,
1586
+ max_aspect: float = 2.2,
1587
+ min_density: float = 0.25,
1588
+ border_margin: int = 3,
1589
+ dark_spot_min_radius_ratio: float = 0.0020,
1590
+ dark_spot_max_radius_ratio: float = 0.028,
1591
+ min_dark_spots_cluster: int = 3,
1592
+ spot_cluster_gap_ratio: float = 0.14,
1593
+ spot_cluster_max_diameter_ratio: float = 0.30,
1594
+ seed_growth_radius: float = 1.7,
1595
+ spot_bright_surround_L: int = 130,
1596
+ debug_out: Path | None = None,
1597
+ ) -> ValveCandidate | None:
1598
+ """Locate the white 5-petal valve using a spot-seeded approach:
1599
+
1600
+ 1. Detect small dark *circular* spots (bolt + petal holes) and
1601
+ keep only those whose immediate surroundings are bright (so
1602
+ that dark spots on a chain / wire / dark body are removed).
1603
+ 2. Cluster these spots by proximity. A valve shows 3~6 spots in
1604
+ a tight cluster. Walls / background / cables produce no such
1605
+ cluster after the "on bright surface" filter.
1606
+ 3. Each valid cluster seeds a circular ROI. Inside the ROI we
1607
+ isolate the bright petals with a LOCALLY-ADAPTIVE threshold.
1608
+ 4. Morph-close so the 5 petals fuse into one contour which is
1609
+ the valve edge we label.
1610
+
1611
+ All pixel-scale parameters are expressed as a ratio of
1612
+ ``min(height, width)`` so the method works at any image resolution.
1613
+ """
1614
+ h, w = img.shape[:2]
1615
+ short_edge = float(min(w, h))
1616
+ img_diag = float(w * w + h * h) ** 0.5
1617
+ img_cx, img_cy = w / 2.0, h / 2.0
1618
+ img_area = float(w * h)
1619
+
1620
+ # Resolve all scale-aware parameters to concrete pixel values.
1621
+ dark_spot_min_radius = max(3, int(dark_spot_min_radius_ratio * short_edge))
1622
+ dark_spot_max_radius = max(dark_spot_min_radius + 2,
1623
+ int(dark_spot_max_radius_ratio * short_edge))
1624
+ spot_cluster_gap = max(40.0, spot_cluster_gap_ratio * short_edge)
1625
+ close_kernel = max(9, int(close_kernel_ratio * short_edge))
1626
+ open_kernel = max(3, int(open_kernel_ratio * short_edge))
1627
+ min_abs_area = int(min_area_ratio * img_area)
1628
+ max_area_ratio_eff = max_area_ratio if roi is not None else min(max_area_ratio, 0.08)
1629
+ max_abs_area = int(max_area_ratio_eff * img_area)
1630
+
1631
+ # ---- 0. dark spot detection & clustering -----------------------
1632
+ gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
1633
+ gray_blur = cv2.GaussianBlur(gray, (5, 5), 0)
1634
+ dark_spots_raw = _find_dark_spots(
1635
+ gray_blur, dark_spot_min_radius, dark_spot_max_radius,
1636
+ )
1637
+
1638
+ # Pre-compute LAB once (needed both for spot filter and threshold).
1639
+ lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
1640
+ L, A, B = cv2.split(lab)
1641
+ a_diff = np.abs(A.astype(np.int16) - 128)
1642
+ b_diff = np.abs(B.astype(np.int16) - 128)
1643
+ neutral = (a_diff + b_diff) < neutral_tol
1644
+
1645
+ # Keep only spots that sit on a bright surface (the white handwheel).
1646
+ dark_spots = _filter_spots_on_bright_surface(
1647
+ dark_spots_raw, L, spot_bright_surround_L,
1648
+ )
1649
+
1650
+ spot_cluster_max_diameter = spot_cluster_max_diameter_ratio * short_edge
1651
+ clusters = _cluster_spots(
1652
+ dark_spots, spot_cluster_gap, min_dark_spots_cluster,
1653
+ max_diameter=spot_cluster_max_diameter,
1654
+ )
1655
+
1656
+ # Cylinder hint centroid (if available) - rewards clusters near it.
1657
+ if roi is not None:
1658
+ rx1, ry1, rx2, ry2 = roi.bbox
1659
+ hint_cx = (rx1 + rx2) / 2.0
1660
+ hint_cy = (ry1 + ry2) / 2.0
1661
+ else:
1662
+ hint_cx, hint_cy = img_cx, img_cy
1663
+
1664
+ candidates: list[ValveCandidate] = []
1665
+ rejects: list[tuple[np.ndarray, str]] = []
1666
+ bright_total = np.zeros_like(L, dtype=np.uint8) # for debug only
1667
+ filled_total = np.zeros_like(L, dtype=np.uint8)
1668
+
1669
+ ck = close_kernel if close_kernel % 2 == 1 else close_kernel + 1
1670
+ ok = open_kernel if open_kernel % 2 == 1 else open_kernel + 1
1671
+ kernel_close = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (ck, ck))
1672
+ kernel_open = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (ok, ok))
1673
+
1674
+ global_thresh_val = 0
1675
+
1676
+ for cluster in clusters:
1677
+ xs = np.array([s[0] for s in cluster], dtype=np.float32)
1678
+ ys = np.array([s[1] for s in cluster], dtype=np.float32)
1679
+ cx_c = float(xs.mean())
1680
+ cy_c = float(ys.mean())
1681
+ five_petal_mask = None
1682
+ five_petal_score = 0.0
1683
+ five_petal_outer = 0
1684
+ five_petal_inner = 0
1685
+
1686
+ # Cluster extent: max spot-to-centre distance.
1687
+ dists = np.sqrt((xs - cx_c) ** 2 + (ys - cy_c) ** 2)
1688
+ max_dist = float(dists.max()) if dists.size > 0 else 10.0
1689
+ avg_spot_r = float(np.mean([s[2] for s in cluster])) if cluster else 10.0
1690
+ min_seed_r = 0.03 * short_edge # absolute minimum ROI radius
1691
+ seed_r = max(min_seed_r, seed_growth_radius * max(max_dist + avg_spot_r, min_seed_r * 0.6))
1692
+ seed_r = min(seed_r, 0.30 * short_edge)
1693
+ five_petal = _build_five_petal_mask(
1694
+ (h, w), dark_spots, (cx_c, cy_c), seed_r,
1695
+ )
1696
+ if five_petal is not None:
1697
+ five_petal_mask, five_petal_score, five_petal_outer, five_petal_inner = five_petal
1698
+ geometry_ready = (
1699
+ roi is not None
1700
+ and five_petal_mask is not None
1701
+ and five_petal_score >= 0.50
1702
+ and five_petal_outer >= 3
1703
+ and five_petal_inner >= 1
1704
+ )
1705
+
1706
+ # Build seed ROI mask (circular) and compute local threshold on it.
1707
+ roi_mask = np.zeros_like(L, dtype=np.uint8)
1708
+ cv2.circle(roi_mask, (int(cx_c), int(cy_c)), int(seed_r), 255, -1)
1709
+ inside = L[roi_mask > 0]
1710
+ if inside.size < 500:
1711
+ continue
1712
+
1713
+ # Local luminance threshold: we want a value that separates the
1714
+ # bright valve petals from the surrounding cylinder body. Use
1715
+ # the LOWER quartile + margin so the threshold is never higher
1716
+ # than the petal brightness even when the ROI happens to
1717
+ # include a lot of over-exposed wall.
1718
+ inside_clipped = inside[inside < 252] # drop overexposed pixels
1719
+ if inside_clipped.size < 100:
1720
+ inside_clipped = inside
1721
+ q25 = float(np.percentile(inside_clipped, 25))
1722
+ q70 = float(np.percentile(inside_clipped, 70))
1723
+ # Aim for a threshold 15-25 above the local median that is still
1724
+ # lower than the petal brightness (~q70).
1725
+ local_thresh = int(min(
1726
+ max(min_luminance, q25 + 18),
1727
+ q70 - 3,
1728
+ ))
1729
+ global_thresh_val = max(global_thresh_val, local_thresh)
1730
+
1731
+ bright_local = ((L > local_thresh) & neutral & (roi_mask > 0)).astype(np.uint8) * 255
1732
+
1733
+ # Close within ROI so petals fuse.
1734
+ closed = cv2.morphologyEx(bright_local, cv2.MORPH_CLOSE, kernel_close)
1735
+ cleaned = cv2.morphologyEx(closed, cv2.MORPH_OPEN, kernel_open)
1736
+
1737
+ # Fill internal holes.
1738
+ cnts_all, _ = cv2.findContours(cleaned, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
1739
+ filled = np.zeros_like(cleaned)
1740
+ cv2.drawContours(filled, cnts_all, -1, 255, thickness=cv2.FILLED)
1741
+
1742
+ # Update debug totals.
1743
+ bright_total = cv2.bitwise_or(bright_total, bright_local)
1744
+ filled_total = cv2.bitwise_or(filled_total, filled)
1745
+
1746
+ # Pick the component that contains the cluster centroid.
1747
+ num_labels, labels_img, stats, centroids = cv2.connectedComponentsWithStats(
1748
+ filled, connectivity=8
1749
+ )
1750
+ selected_label = -1
1751
+ cx_i, cy_i = int(cx_c), int(cy_c)
1752
+ if 0 <= cy_i < h and 0 <= cx_i < w:
1753
+ candidate_label = int(labels_img[cy_i, cx_i])
1754
+ if candidate_label > 0:
1755
+ selected_label = candidate_label
1756
+ if selected_label < 0:
1757
+ # Fallback: largest component inside roi.
1758
+ best = -1
1759
+ best_area = 0
1760
+ for lbl in range(1, num_labels):
1761
+ a = stats[lbl, cv2.CC_STAT_AREA]
1762
+ if a > best_area:
1763
+ best_area = a
1764
+ best = lbl
1765
+ selected_label = best
1766
+
1767
+ if selected_label <= 0:
1768
+ rejects.append((np.array([[[cx_i, cy_i]]], dtype=np.int32),
1769
+ "no_component"))
1770
+ continue
1771
+
1772
+ comp_mask = (labels_img == selected_label).astype(np.uint8) * 255
1773
+ if geometry_ready:
1774
+ prior_overlap = float(
1775
+ cv2.countNonZero(cv2.bitwise_and(comp_mask, five_petal_mask))
1776
+ ) / max(1.0, float(cv2.countNonZero(five_petal_mask)))
1777
+ constrain_k = max(5, int(0.014 * short_edge))
1778
+ constrain_k = constrain_k if constrain_k % 2 == 1 else constrain_k + 1
1779
+ constrain_kernel = cv2.getStructuringElement(
1780
+ cv2.MORPH_ELLIPSE, (constrain_k, constrain_k),
1781
+ )
1782
+ prior_band = cv2.dilate(five_petal_mask, constrain_kernel, iterations=1)
1783
+ comp_mask = cv2.bitwise_and(comp_mask, prior_band)
1784
+ if prior_overlap >= 0.20:
1785
+ comp_mask = cv2.bitwise_or(comp_mask, five_petal_mask)
1786
+ comp_cnts, _ = cv2.findContours(comp_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
1787
+ if not comp_cnts:
1788
+ continue
1789
+ cnt = max(comp_cnts, key=cv2.contourArea)
1790
+
1791
+ area = float(cv2.contourArea(cnt))
1792
+ if area < min_abs_area:
1793
+ rejects.append((cnt, f"A<{min_abs_area}"))
1794
+ continue
1795
+ if area > max_abs_area:
1796
+ rejects.append((cnt, f"A>{max_abs_area}"))
1797
+ continue
1798
+
1799
+ bx, by, bw_c, bh_c = cv2.boundingRect(cnt)
1800
+ if (bx <= border_margin or by <= border_margin
1801
+ or bx + bw_c >= w - border_margin
1802
+ or by + bh_c >= h - border_margin):
1803
+ rejects.append((cnt, "border"))
1804
+ continue
1805
+
1806
+ aspect = max(bw_c, bh_c) / max(1, min(bw_c, bh_c))
1807
+ if aspect > max_aspect:
1808
+ rejects.append((cnt, f"asp={aspect:.1f}"))
1809
+ continue
1810
+
1811
+ density = area / float(bw_c * bh_c + 1)
1812
+ if density < min_density:
1813
+ rejects.append((cnt, f"dens={density:.2f}"))
1814
+ continue
1815
+
1816
+ perimeter = float(cv2.arcLength(cnt, True))
1817
+ if perimeter <= 0:
1818
+ continue
1819
+ circularity = 4.0 * np.pi * area / (perimeter * perimeter)
1820
+
1821
+ # Dark-delta signal (bolt darker than ring).
1822
+ cmask = np.zeros((h, w), dtype=np.uint8)
1823
+ cv2.drawContours(cmask, [cnt], -1, 255, -1)
1824
+ er_k = max(5, int(min(bw_c, bh_c) * 0.35))
1825
+ er_k = er_k if er_k % 2 == 1 else er_k + 1
1826
+ eroded = cv2.erode(
1827
+ cmask, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (er_k, er_k))
1828
+ )
1829
+ ring_mask = cv2.subtract(cmask, eroded)
1830
+ dark_delta = 0.0
1831
+ if (eroded > 0).any() and (ring_mask > 0).any():
1832
+ L_inner = float(L[eroded > 0].mean())
1833
+ L_ring = float(L[ring_mask > 0].mean())
1834
+ dark_delta = L_ring - L_inner
1835
+
1836
+ # Centrality
1837
+ M = cv2.moments(cnt)
1838
+ if M["m00"] == 0:
1839
+ continue
1840
+ cnt_cx = M["m10"] / M["m00"]
1841
+ cnt_cy = M["m01"] / M["m00"]
1842
+ d_img = ((cnt_cx - img_cx) ** 2 + (cnt_cy - img_cy) ** 2) ** 0.5 / img_diag
1843
+ d_hint = ((cnt_cx - hint_cx) ** 2 + (cnt_cy - hint_cy) ** 2) ** 0.5 / img_diag
1844
+ img_cent = max(0.0, 1.0 - d_img / 0.55)
1845
+ hint_cent = max(0.0, 1.0 - d_hint / 0.45)
1846
+ hub_dist = min(
1847
+ float(((sx - cnt_cx) ** 2 + (sy - cnt_cy) ** 2) ** 0.5)
1848
+ for (sx, sy, _) in cluster
1849
+ )
1850
+ eq_r = float((area / np.pi) ** 0.5) if area > 0 else 0.0
1851
+ hub_score = max(0.0, 1.0 - hub_dist / max(8.0, eq_r * 0.42))
1852
+ cluster_radii = np.array([s[2] for s in cluster], dtype=np.float32)
1853
+ median_spot_r = float(np.median(cluster_radii)) if cluster_radii.size > 0 else 0.0
1854
+ hub_spots = [
1855
+ (sx, sy, sr)
1856
+ for (sx, sy, sr) in cluster
1857
+ if ((sx - cnt_cx) ** 2 + (sy - cnt_cy) ** 2) ** 0.5 <= max(10.0, eq_r * 0.28)
1858
+ ]
1859
+ outer_ring_spots = sum(
1860
+ 1
1861
+ for (sx, sy, _) in cluster
1862
+ if max(10.0, eq_r * 0.32) <= ((sx - cnt_cx) ** 2 + (sy - cnt_cy) ** 2) ** 0.5 <= max(14.0, eq_r * 0.95)
1863
+ )
1864
+ hub_radius = max((float(sr) for (_, _, sr) in hub_spots), default=0.0)
1865
+ if roi is None and (
1866
+ hub_radius < max(float(dark_spot_min_radius) * 1.05, median_spot_r * 1.12)
1867
+ or outer_ring_spots < 3
1868
+ ):
1869
+ rejects.append((cnt.copy(), "weak_hub"))
1870
+ continue
1871
+
1872
+ circ_score = max(0.20, 1.0 - abs(circularity - 0.58) / 0.58)
1873
+ aspect_score = 1.0 if aspect <= 1.55 else max(0.4, 1.75 - 0.60 * aspect)
1874
+ spots_score = max(
1875
+ min(1.0, len(cluster) / 5.0),
1876
+ min(1.0, (five_petal_outer + min(2, five_petal_inner)) / 7.0)
1877
+ if geometry_ready else 0.0,
1878
+ )
1879
+ dark_score = min(1.0, max(0.0, dark_delta) / 40.0)
1880
+ geometry_score = min(1.0, five_petal_score) if geometry_ready else 0.0
1881
+
1882
+ score = (
1883
+ 0.22 * spots_score
1884
+ + 0.16 * geometry_score
1885
+ + 0.12 * circ_score
1886
+ + 0.12 * aspect_score
1887
+ + 0.14 * img_cent
1888
+ + 0.08 * hint_cent
1889
+ + 0.10 * dark_score
1890
+ + 0.06 * hub_score
1891
+ )
1892
+
1893
+ candidates.append(ValveCandidate(
1894
+ contour=cnt,
1895
+ area=area,
1896
+ perimeter=perimeter,
1897
+ circularity=circularity,
1898
+ aspect=aspect,
1899
+ centrality=img_cent,
1900
+ dark_center_ratio=min(1.0, float(max(len(cluster), five_petal_outer + five_petal_inner)) / 7.0),
1901
+ score=score,
1902
+ ))
1903
+
1904
+ if debug_out is not None:
1905
+ _dump_debug(
1906
+ img, roi, bright_total, filled_total, filled_total,
1907
+ candidates, rejects, global_thresh_val, dark_spots, debug_out,
1908
+ )
1909
+
1910
+ if not candidates:
1911
+ return None
1912
+
1913
+ candidates.sort(key=lambda c: c.score, reverse=True)
1914
+ return candidates[0]
1915
+
1916
+
1917
+ # ----------------------------------------------------------------------
1918
+ # YOLO-seg label formatting
1919
+ # ----------------------------------------------------------------------
1920
+ def contour_to_yolo_seg(
1921
+ contour: np.ndarray,
1922
+ image_w: int,
1923
+ image_h: int,
1924
+ class_id: int,
1925
+ simplify_eps: float = 0.002,
1926
+ max_points: int = 120,
1927
+ ) -> tuple[str, np.ndarray]:
1928
+ perimeter = cv2.arcLength(contour, True)
1929
+ eps = max(1.5, simplify_eps * perimeter)
1930
+ simplified = cv2.approxPolyDP(contour, eps, True)
1931
+
1932
+ # If still too many points, increase eps until under max_points.
1933
+ step = 0
1934
+ while len(simplified) > max_points and step < 6:
1935
+ eps *= 1.4
1936
+ simplified = cv2.approxPolyDP(contour, eps, True)
1937
+ step += 1
1938
+
1939
+ if len(simplified) < 3:
1940
+ simplified = contour
1941
+
1942
+ tokens: list[str] = [str(class_id)]
1943
+ for pt in simplified.reshape(-1, 2):
1944
+ nx = float(pt[0]) / float(image_w)
1945
+ ny = float(pt[1]) / float(image_h)
1946
+ nx = min(1.0, max(0.0, nx))
1947
+ ny = min(1.0, max(0.0, ny))
1948
+ tokens.append(f"{nx:.6f}")
1949
+ tokens.append(f"{ny:.6f}")
1950
+
1951
+ return " ".join(tokens), simplified
1952
+
1953
+
1954
+ # ----------------------------------------------------------------------
1955
+ # Visualization helpers
1956
+ # ----------------------------------------------------------------------
1957
+ def draw_main_visualization(
1958
+ img: np.ndarray,
1959
+ roi: CylinderROI | None,
1960
+ valve: ValveCandidate | None,
1961
+ simplified_contour: np.ndarray | None,
1962
+ thresh_val: int | None,
1963
+ ) -> np.ndarray:
1964
+ vis = img.copy()
1965
+ h, w = vis.shape[:2]
1966
+
1967
+ # Cylinder outline (light blue).
1968
+ if roi is not None:
1969
+ pts = (roi.polygon_norm * np.array([w, h])).astype(np.int32).reshape(-1, 1, 2)
1970
+ cv2.polylines(vis, [pts], True, (255, 180, 0), 2)
1971
+ cv2.putText(
1972
+ vis, f"cylinder:{roi.cls_name} {roi.conf:.2f}",
1973
+ (pts[0][0][0], max(30, int(pts[0][0][1]) - 10)),
1974
+ cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 180, 0), 2,
1975
+ )
1976
+
1977
+ # Valve polygon (green fill + thick green outline).
1978
+ if valve is not None and simplified_contour is not None:
1979
+ overlay = vis.copy()
1980
+ cv2.fillPoly(overlay, [simplified_contour], (0, 255, 0))
1981
+ cv2.addWeighted(overlay, 0.35, vis, 0.65, 0, vis)
1982
+ cv2.polylines(vis, [simplified_contour], True, (0, 255, 0), 3)
1983
+
1984
+ bx, by, bw, bh = cv2.boundingRect(simplified_contour)
1985
+ label = (
1986
+ f"valve score={valve.score:.2f} "
1987
+ f"circ={valve.circularity:.2f} "
1988
+ f"area={valve.area / (w * h):.3f}"
1989
+ )
1990
+ cv2.putText(
1991
+ vis, label, (bx, max(30, by - 12)),
1992
+ cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2,
1993
+ )
1994
+ else:
1995
+ msg = "NO VALVE DETECTED"
1996
+ cv2.putText(
1997
+ vis, msg, (30, 60),
1998
+ cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0, 0, 255), 3,
1999
+ )
2000
+
2001
+ if thresh_val is not None:
2002
+ cv2.putText(
2003
+ vis, f"L_thresh={thresh_val}", (30, h - 30),
2004
+ cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2,
2005
+ )
2006
+
2007
+ return vis
2008
+
2009
+
2010
+ def _dump_debug(
2011
+ img: np.ndarray,
2012
+ roi: CylinderROI | None,
2013
+ bright: np.ndarray,
2014
+ cleaned: np.ndarray,
2015
+ filled: np.ndarray,
2016
+ candidates: list[ValveCandidate],
2017
+ rejects: list[tuple[np.ndarray, str]],
2018
+ thresh_val: int,
2019
+ dark_spots: list[tuple[int, int, int]],
2020
+ out_path: Path,
2021
+ ) -> None:
2022
+ """Save a 2x2 debug panel (input / bright / morphed / candidates)."""
2023
+ h, w = img.shape[:2]
2024
+
2025
+ def to_bgr(gray: np.ndarray) -> np.ndarray:
2026
+ return cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
2027
+
2028
+ panel_img = img.copy()
2029
+ if roi is not None:
2030
+ cv2.polylines(
2031
+ panel_img,
2032
+ [(roi.polygon_norm * np.array([w, h])).astype(np.int32).reshape(-1, 1, 2)],
2033
+ True, (255, 180, 0), 2,
2034
+ )
2035
+ # Show the dark spots we found (= candidate bolt + petal holes).
2036
+ for (sx, sy, sr) in dark_spots:
2037
+ cv2.circle(panel_img, (sx, sy), max(sr, 3), (0, 140, 255), 2)
2038
+ cv2.putText(
2039
+ panel_img, f"Lthr={thresh_val} spots={len(dark_spots)}", (30, 40),
2040
+ cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 255), 2,
2041
+ )
2042
+
2043
+ cand_img = img.copy()
2044
+ # Draw rejected blobs in red with their reason.
2045
+ for cnt, reason in rejects:
2046
+ cv2.drawContours(cand_img, [cnt], -1, (60, 60, 255), 1)
2047
+ bx, by, _, _ = cv2.boundingRect(cnt)
2048
+ cv2.putText(
2049
+ cand_img, reason, (bx, max(15, by - 4)),
2050
+ cv2.FONT_HERSHEY_SIMPLEX, 0.45, (60, 60, 255), 1,
2051
+ )
2052
+ for i, c in enumerate(candidates):
2053
+ color = (0, 255, 0) if i == 0 else (0, 200, 220)
2054
+ thick = 3 if i == 0 else 2
2055
+ cv2.drawContours(cand_img, [c.contour], -1, color, thick)
2056
+ bx, by, _, _ = cv2.boundingRect(c.contour)
2057
+ cv2.putText(
2058
+ cand_img,
2059
+ f"s={c.score:.2f} c={c.circularity:.2f}",
2060
+ (bx, max(20, by - 5)),
2061
+ cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2,
2062
+ )
2063
+
2064
+ def resize_for_panel(im: np.ndarray) -> np.ndarray:
2065
+ scale = 640.0 / max(im.shape[:2])
2066
+ return cv2.resize(im, (int(im.shape[1] * scale), int(im.shape[0] * scale)))
2067
+
2068
+ p1 = resize_for_panel(panel_img)
2069
+ p2 = resize_for_panel(to_bgr(bright))
2070
+ p3 = resize_for_panel(to_bgr(cleaned))
2071
+ p4 = resize_for_panel(cand_img)
2072
+
2073
+ for tile, txt in [(p1, "input+cylinder"), (p2, "bright+neutral"),
2074
+ (p3, "morphed"), (p4, "candidates/rejects")]:
2075
+ cv2.putText(
2076
+ tile, txt, (10, 25),
2077
+ cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 255), 2,
2078
+ )
2079
+
2080
+ row1 = np.hstack([p1, p2])
2081
+ row2 = np.hstack([p3, p4])
2082
+ panel = np.vstack([row1, row2])
2083
+ imwrite_unicode(out_path, panel)
2084
+
2085
+
2086
+ # ----------------------------------------------------------------------
2087
+ # Main driver
2088
+ # ----------------------------------------------------------------------
2089
+ def parse_args() -> argparse.Namespace:
2090
+ p = argparse.ArgumentParser(
2091
+ description=(
2092
+ "Auto-label valve handwheels as YOLO polygon segmentation "
2093
+ "labels (class_id=1 by default)."
2094
+ )
2095
+ )
2096
+ p.add_argument("--image-dir", type=Path, default=DEFAULT_IMAGE_DIR)
2097
+ p.add_argument("--labels-dir", type=Path, default=None,
2098
+ help="Where to write .txt labels (default: next to images).")
2099
+ p.add_argument("--vis-dir", type=Path, default=DEFAULT_VIS_DIR,
2100
+ help="Where to save visualization overlays.")
2101
+ p.add_argument("--debug-dir", type=Path, default=DEFAULT_DEBUG_DIR,
2102
+ help="Where to save 2x2 debug panels (--debug).")
2103
+ p.add_argument("--model", default=DEFAULT_MODEL)
2104
+ p.add_argument("--device", default="cpu",
2105
+ help="Ultralytics device string, e.g. cpu or 0.")
2106
+ p.add_argument("--class-id", type=int, default=1)
2107
+ p.add_argument("--limit", type=int, default=0,
2108
+ help="If > 0, only process the first N images (useful for quick check).")
2109
+ p.add_argument("--names", nargs="*", default=None,
2110
+ help="Only process images whose stem is in this list.")
2111
+ p.add_argument("--debug", action="store_true",
2112
+ help="Save a 4-panel debug image per processed image.")
2113
+ p.add_argument("--overwrite", action="store_true",
2114
+ help="Overwrite existing non-empty labels.")
2115
+ p.add_argument("--skip-visualizations", action="store_true")
2116
+ # Tuning knobs (all ratios are relative to min(image width, height)):
2117
+ p.add_argument("--min-luminance", type=int, default=135)
2118
+ p.add_argument("--neutral-tol", type=int, default=90,
2119
+ help="|a-128|+|b-128| limit; smaller = stricter 'white'.")
2120
+ p.add_argument("--close-kernel-ratio", type=float, default=0.035,
2121
+ help="Morph-close kernel as fraction of min(H,W).")
2122
+ p.add_argument("--open-kernel-ratio", type=float, default=0.0035)
2123
+ p.add_argument("--min-area-ratio", type=float, default=0.003,
2124
+ help="Min valve area as fraction of image area.")
2125
+ p.add_argument("--max-area-ratio", type=float, default=0.14)
2126
+ p.add_argument("--max-aspect", type=float, default=2.2)
2127
+ p.add_argument("--min-density", type=float, default=0.25)
2128
+ p.add_argument("--dark-spot-min-radius-ratio", type=float, default=0.0020)
2129
+ p.add_argument("--dark-spot-max-radius-ratio", type=float, default=0.028)
2130
+ p.add_argument("--min-dark-spots", type=int, default=3,
2131
+ help="Min dark spots in one cluster to be a valve candidate.")
2132
+ p.add_argument("--spot-cluster-gap-ratio", type=float, default=0.14,
2133
+ help="Max spot-pair distance, as fraction of min(H,W).")
2134
+ p.add_argument("--spot-cluster-max-diameter-ratio", type=float, default=0.30,
2135
+ help="Max cluster diameter, as fraction of min(H,W). "
2136
+ "Rejects diffuse clusters on cables/wires.")
2137
+ p.add_argument("--seed-growth-radius", type=float, default=1.7,
2138
+ help="Multiplier for seed-ROI radius around spot cluster.")
2139
+ p.add_argument("--spot-bright-surround-L", type=int, default=130,
2140
+ help="Min mean L of a ring around each dark spot for "
2141
+ "it to count (rejects spots on chains/wires).")
2142
+ p.add_argument("--no-yolo", action="store_true",
2143
+ help="Skip the YOLO cylinder hint stage (faster).")
2144
+ # Bbox-prior mode (primary path when bbox labels are present):
2145
+ p.add_argument("--bbox-dir", type=Path, default=None,
2146
+ help="Directory containing YOLO-format *bbox* labels "
2147
+ "(class cx cy w h) used as a prior. Defaults to "
2148
+ "--image-dir when omitted.")
2149
+ p.add_argument("--no-bbox-prior", action="store_true",
2150
+ help="Ignore any existing bbox labels and run the "
2151
+ "global spot-seeded detector on every image.")
2152
+ p.add_argument("--bbox-expand-ratio", type=float, default=0.08,
2153
+ help="Extra margin added around the input bbox before "
2154
+ "cropping, as a fraction of the bbox size.")
2155
+ p.add_argument("--bbox-require-spots", type=int, default=3,
2156
+ help="Min dark circular spots (bolt + petal holes) "
2157
+ "that must fall inside the polygon for it to be "
2158
+ "accepted. Set 0 to disable validation.")
2159
+ return p.parse_args()
2160
+
2161
+
2162
+ def should_skip_label(label_path: Path, overwrite: bool) -> bool:
2163
+ if overwrite:
2164
+ return False
2165
+ if not label_path.exists():
2166
+ return False
2167
+ return label_path.stat().st_size > 0
2168
+
2169
+
2170
+ def main() -> None:
2171
+ args = parse_args()
2172
+
2173
+ image_dir: Path = args.image_dir
2174
+ labels_dir: Path = args.labels_dir if args.labels_dir is not None else image_dir
2175
+ bbox_dir: Path = args.bbox_dir if args.bbox_dir is not None else image_dir
2176
+ vis_dir: Path = args.vis_dir
2177
+ debug_dir: Path = args.debug_dir
2178
+
2179
+ if not image_dir.exists():
2180
+ raise FileNotFoundError(f"Image folder not found: {image_dir}")
2181
+
2182
+ labels_dir.mkdir(parents=True, exist_ok=True)
2183
+ if not args.skip_visualizations:
2184
+ vis_dir.mkdir(parents=True, exist_ok=True)
2185
+ if args.debug:
2186
+ debug_dir.mkdir(parents=True, exist_ok=True)
2187
+
2188
+ files = sorted(
2189
+ p for p in image_dir.iterdir()
2190
+ if p.is_file() and p.suffix.lower() in IMAGE_SUFFIXES
2191
+ )
2192
+ if args.names:
2193
+ name_set = {n for n in args.names}
2194
+ files = [p for p in files if p.stem in name_set]
2195
+ if args.limit > 0:
2196
+ files = files[: args.limit]
2197
+
2198
+ if not files:
2199
+ print(f"No images found in: {image_dir}", flush=True)
2200
+ return
2201
+
2202
+ # Device auto-upgrade if CUDA available and user left default cpu.
2203
+ device = args.device
2204
+ try:
2205
+ import torch
2206
+ if torch.cuda.is_available() and device == "cpu":
2207
+ device = "0"
2208
+ print(f"Using GPU: {torch.cuda.get_device_name(0)}", flush=True)
2209
+ elif device == "cpu":
2210
+ print("Using CPU (no GPU detected)", flush=True)
2211
+ except Exception:
2212
+ pass
2213
+
2214
+ print("Initializing valve auto-labeler (polygon mode)...", flush=True)
2215
+ print(f" image-dir : {image_dir}", flush=True)
2216
+ print(f" labels-dir : {labels_dir}", flush=True)
2217
+ print(f" vis-dir : {vis_dir}", flush=True)
2218
+ print(f" model : {args.model if not args.no_yolo else '(skipped)'}", flush=True)
2219
+ print(f" device : {device}", flush=True)
2220
+ print(f" class-id : {args.class_id}", flush=True)
2221
+ print(f" images : {len(files)}", flush=True)
2222
+
2223
+ locator = None
2224
+ if not args.no_yolo:
2225
+ try:
2226
+ locator = CylinderLocator(args.model, device=device)
2227
+ except Exception as e:
2228
+ print(f"[Cylinder] Failed to load YOLO ({e}); continuing without hint.",
2229
+ flush=True)
2230
+ locator = None
2231
+
2232
+ n_ok = 0
2233
+ n_hint_missing = 0
2234
+ n_valve_fail = 0
2235
+ n_read_fail = 0
2236
+ n_skip = 0
2237
+ n_bbox_prior_used = 0
2238
+ n_bbox_prior_fallback = 0
2239
+ t_start = time.time()
2240
+ failures: list[str] = []
2241
+
2242
+ for idx, image_path in enumerate(files, 1):
2243
+ label_path = labels_dir / f"{image_path.stem}.txt"
2244
+ if should_skip_label(label_path, args.overwrite):
2245
+ print(f"[{idx}/{len(files)}] SKIP {image_path.name}", flush=True)
2246
+ n_skip += 1
2247
+ continue
2248
+
2249
+ img = imread_unicode(image_path)
2250
+ if img is None:
2251
+ print(f"[{idx}/{len(files)}] READ-FAIL {image_path.name}", flush=True)
2252
+ n_read_fail += 1
2253
+ failures.append(image_path.name)
2254
+ continue
2255
+
2256
+ h, w = img.shape[:2]
2257
+
2258
+ # Stage 0 (primary path): try the bbox prior if available.
2259
+ bbox_prior: tuple[int, int, int, int] | None = None
2260
+ if not args.no_bbox_prior:
2261
+ bbox_label_path = bbox_dir / f"{image_path.stem}.txt"
2262
+ bbox_prior = read_yolo_bbox(
2263
+ bbox_label_path, w, h, class_id=args.class_id,
2264
+ )
2265
+
2266
+ bbox_debug = (debug_dir / f"{image_path.stem}_bbox.png"
2267
+ if args.debug else None)
2268
+ spot_debug = (debug_dir / f"{image_path.stem}.png"
2269
+ if args.debug else None)
2270
+
2271
+ valve: ValveCandidate | None = None
2272
+ mode_tag = ""
2273
+
2274
+ if bbox_prior is not None:
2275
+ valve = _find_valve_polygon_in_bbox(
2276
+ img, bbox_prior,
2277
+ bbox_expand_ratio=args.bbox_expand_ratio,
2278
+ neutral_tol=args.neutral_tol,
2279
+ min_dark_spots_inside=args.bbox_require_spots,
2280
+ require_dark_spots=args.bbox_require_spots > 0,
2281
+ debug_out=bbox_debug,
2282
+ )
2283
+ if valve is not None:
2284
+ mode_tag = "bbox"
2285
+ n_bbox_prior_used += 1
2286
+ else:
2287
+ n_bbox_prior_fallback += 1
2288
+
2289
+ # Stage 1 (optional) & Stage 2 fallback: cylinder hint + spot-seeded
2290
+ # global search. Only used when the bbox-prior path was unavailable
2291
+ # or failed validation.
2292
+ roi: CylinderROI | None = None
2293
+ if valve is None:
2294
+ if locator is not None:
2295
+ roi = locator.locate(img)
2296
+ if roi is None:
2297
+ n_hint_missing += 1
2298
+
2299
+ valve = _find_valve_contour(
2300
+ img, roi,
2301
+ min_luminance=args.min_luminance,
2302
+ neutral_tol=args.neutral_tol,
2303
+ close_kernel_ratio=args.close_kernel_ratio,
2304
+ open_kernel_ratio=args.open_kernel_ratio,
2305
+ min_area_ratio=args.min_area_ratio,
2306
+ max_area_ratio=args.max_area_ratio,
2307
+ max_aspect=args.max_aspect,
2308
+ min_density=args.min_density,
2309
+ dark_spot_min_radius_ratio=args.dark_spot_min_radius_ratio,
2310
+ dark_spot_max_radius_ratio=args.dark_spot_max_radius_ratio,
2311
+ min_dark_spots_cluster=args.min_dark_spots,
2312
+ spot_cluster_gap_ratio=args.spot_cluster_gap_ratio,
2313
+ spot_cluster_max_diameter_ratio=args.spot_cluster_max_diameter_ratio,
2314
+ seed_growth_radius=args.seed_growth_radius,
2315
+ spot_bright_surround_L=args.spot_bright_surround_L,
2316
+ debug_out=spot_debug,
2317
+ )
2318
+ if valve is not None:
2319
+ mode_tag = "spot"
2320
+
2321
+ roi_tag = (
2322
+ f"bbox=prior" if mode_tag == "bbox"
2323
+ else (f"cyl={roi.cls_name}:{roi.conf:.2f}" if roi else "cyl=none")
2324
+ )
2325
+
2326
+ if valve is None:
2327
+ n_valve_fail += 1
2328
+ label_path.write_text("", encoding="utf-8")
2329
+ failures.append(image_path.name)
2330
+ print(f"[{idx}/{len(files)}] FAIL {image_path.name} ({roi_tag})",
2331
+ flush=True)
2332
+ if not args.skip_visualizations:
2333
+ vis = draw_main_visualization(img, roi, None, None, None)
2334
+ imwrite_unicode(vis_dir / image_path.name, vis)
2335
+ continue
2336
+
2337
+ label_line, simplified = contour_to_yolo_seg(
2338
+ valve.contour, w, h, args.class_id,
2339
+ )
2340
+ label_path.write_text(label_line + "\n", encoding="utf-8")
2341
+
2342
+ if not args.skip_visualizations:
2343
+ vis = draw_main_visualization(img, roi, valve, simplified, None)
2344
+ imwrite_unicode(vis_dir / image_path.name, vis)
2345
+
2346
+ n_ok += 1
2347
+ area_frac = valve.area / float(w * h)
2348
+ print(
2349
+ f"[{idx}/{len(files)}] OK {image_path.name} "
2350
+ f"mode={mode_tag} score={valve.score:.2f} "
2351
+ f"circ={valve.circularity:.2f} area/img={area_frac:.3f} "
2352
+ f"pts={len(simplified)} ({roi_tag})",
2353
+ flush=True,
2354
+ )
2355
+
2356
+ elapsed = time.time() - t_start
2357
+ print("", flush=True)
2358
+ print("=" * 60, flush=True)
2359
+ print("Valve auto-label finished.", flush=True)
2360
+ print(f" success : {n_ok}", flush=True)
2361
+ print(f" via bbox prior : {n_bbox_prior_used}", flush=True)
2362
+ print(f" via spot search: {n_ok - n_bbox_prior_used}", flush=True)
2363
+ print(f" bbox prior rejected (fell back): {n_bbox_prior_fallback}",
2364
+ flush=True)
2365
+ print(f" valve not found : {n_valve_fail}", flush=True)
2366
+ print(f" cylinder hint missing : {n_hint_missing}", flush=True)
2367
+ print(f" read failures : {n_read_fail}", flush=True)
2368
+ print(f" skipped : {n_skip}", flush=True)
2369
+ print(f" elapsed : {elapsed/60:.1f} min ({elapsed:.1f} s)", flush=True)
2370
+ print("=" * 60, flush=True)
2371
+
2372
+ if failures:
2373
+ print("Images needing attention:", flush=True)
2374
+ for n in failures[:40]:
2375
+ print(f" - {n}", flush=True)
2376
+ if len(failures) > 40:
2377
+ print(f" ... {len(failures) - 40} more", flush=True)
2378
+
2379
+
2380
+ if __name__ == "__main__":
2381
+ main()