fix pretrained gas auto label filtering notebooks/colab_gas_valve_auto_label_train.py
Browse files
notebooks/colab_gas_valve_auto_label_train.py
CHANGED
|
@@ -298,13 +298,14 @@ print(f"Raw gas-extra images: {len(list_images(RAW_GAS_EXTRA_DIR))}")
|
|
| 298 |
|
| 299 |
class GasCylinderSegmenter:
|
| 300 |
CLASS_WEIGHTS = {
|
| 301 |
-
39: 2.
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
|
|
|
| 308 |
}
|
| 309 |
|
| 310 |
def __init__(self, model_path: str = "yolo11x-seg.pt", class_id: int = 0) -> None:
|
|
@@ -314,15 +315,31 @@ class GasCylinderSegmenter:
|
|
| 314 |
self.class_id = class_id
|
| 315 |
self.model = YOLO(model_path)
|
| 316 |
self.conf = 0.01
|
| 317 |
-
self.min_area = 0.
|
| 318 |
-
self.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 319 |
print(f"Gas label model: {model_path}, device={self.device}, class_id={class_id}")
|
| 320 |
|
| 321 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 322 |
h, w = img.shape[:2]
|
| 323 |
-
cx, cy = w / 2.0, h / 2.0
|
| 324 |
area = float(w * h)
|
| 325 |
-
diag = float(w * w + h * h) ** 0.5
|
| 326 |
|
| 327 |
result = self.model(img, conf=self.conf, device=self.device, verbose=False)[0]
|
| 328 |
candidates = []
|
|
@@ -335,30 +352,56 @@ class GasCylinderSegmenter:
|
|
| 335 |
|
| 336 |
conf = float(result.boxes.conf[i])
|
| 337 |
x1, y1, x2, y2 = result.boxes.xyxy[i].tolist()
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
area_ratio =
|
| 341 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 342 |
|
| 343 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 344 |
continue
|
| 345 |
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
|
|
|
|
|
|
| 349 |
|
| 350 |
if not candidates:
|
| 351 |
-
return
|
| 352 |
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 356 |
|
| 357 |
-
|
| 358 |
-
for
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 362 |
|
| 363 |
|
| 364 |
def auto_label_gas_folder(
|
|
@@ -388,8 +431,8 @@ def auto_label_gas_folder(
|
|
| 388 |
continue
|
| 389 |
|
| 390 |
try:
|
| 391 |
-
|
| 392 |
-
write_lines(label_path,
|
| 393 |
stats["ok" if ok else "failed"] += 1
|
| 394 |
except Exception as exc:
|
| 395 |
print(f"Gas label error: {image_path.name}: {exc}")
|
|
@@ -407,11 +450,12 @@ def auto_label_gas_folder(
|
|
| 407 |
|
| 408 |
# %%
|
| 409 |
# @title Step 6 - 自动标注补充气瓶数据
|
|
|
|
| 410 |
# @markdown 会给补充气瓶图片生成气瓶标签,也会给阀门图片中的气瓶区域生成气瓶标签。
|
| 411 |
# @markdown 这样训练时阀门图片里的气瓶不会被当成背景。
|
| 412 |
|
| 413 |
-
GAS_LABEL_MODEL = "yolo11x-seg.pt"
|
| 414 |
-
REGENERATE_GAS_LABELS =
|
| 415 |
GAS_LABEL_LIMIT = 0 # 0 表示处理全部图片。
|
| 416 |
|
| 417 |
GAS_EXTRA_LABEL_DIR = LABEL_WORK_DIR / "gas_extra"
|
|
@@ -1099,6 +1143,16 @@ delete_button = widgets.Button(
|
|
| 1099 |
button_style="danger",
|
| 1100 |
layout=widgets.Layout(width="280px"),
|
| 1101 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1102 |
summary_label = widgets.HTML(
|
| 1103 |
value="<b>操作提示:</b>删除后不用重新跑 Step 10,直接运行 Step 12 训练即可。"
|
| 1104 |
)
|
|
@@ -1157,6 +1211,20 @@ def on_delete_clicked(_button):
|
|
| 1157 |
checkboxes[idx].disabled = True
|
| 1158 |
|
| 1159 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1160 |
delete_button.on_click(on_delete_clicked)
|
| 1161 |
|
| 1162 |
grid = widgets.GridBox(
|
|
@@ -1168,7 +1236,12 @@ grid = widgets.GridBox(
|
|
| 1168 |
),
|
| 1169 |
)
|
| 1170 |
|
| 1171 |
-
display(widgets.VBox([
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1172 |
|
| 1173 |
|
| 1174 |
# %% [markdown]
|
|
|
|
| 298 |
|
| 299 |
class GasCylinderSegmenter:
|
| 300 |
CLASS_WEIGHTS = {
|
| 301 |
+
39: 2.4, # bottle
|
| 302 |
+
75: 1.8, # vase
|
| 303 |
+
61: 1.4, # toilet
|
| 304 |
+
10: 1.4, # fire hydrant
|
| 305 |
+
72: 1.1, # refrigerator, often matches large partial cylinders
|
| 306 |
+
41: 0.7, # cup
|
| 307 |
+
56: 0.5, # chair
|
| 308 |
+
71: 0.25, # sink is noisy; keep only if geometry is strong
|
| 309 |
}
|
| 310 |
|
| 311 |
def __init__(self, model_path: str = "yolo11x-seg.pt", class_id: int = 0) -> None:
|
|
|
|
| 315 |
self.class_id = class_id
|
| 316 |
self.model = YOLO(model_path)
|
| 317 |
self.conf = 0.01
|
| 318 |
+
self.min_area = 0.045
|
| 319 |
+
self.max_area = 0.70
|
| 320 |
+
self.min_aspect = 0.20
|
| 321 |
+
self.max_aspect = 1.25
|
| 322 |
+
self.min_score = 0.012
|
| 323 |
+
self.max_outputs = 3
|
| 324 |
+
self.iou_threshold = 0.35
|
| 325 |
print(f"Gas label model: {model_path}, device={self.device}, class_id={class_id}")
|
| 326 |
|
| 327 |
+
@staticmethod
|
| 328 |
+
def _box_iou(a: tuple[float, float, float, float], b: tuple[float, float, float, float]) -> float:
|
| 329 |
+
ax1, ay1, ax2, ay2 = a
|
| 330 |
+
bx1, by1, bx2, by2 = b
|
| 331 |
+
ix1, iy1 = max(ax1, bx1), max(ay1, by1)
|
| 332 |
+
ix2, iy2 = min(ax2, bx2), min(ay2, by2)
|
| 333 |
+
iw, ih = max(0.0, ix2 - ix1), max(0.0, iy2 - iy1)
|
| 334 |
+
inter = iw * ih
|
| 335 |
+
area_a = max(0.0, ax2 - ax1) * max(0.0, ay2 - ay1)
|
| 336 |
+
area_b = max(0.0, bx2 - bx1) * max(0.0, by2 - by1)
|
| 337 |
+
denom = area_a + area_b - inter
|
| 338 |
+
return inter / denom if denom > 0 else 0.0
|
| 339 |
+
|
| 340 |
+
def annotate(self, img: np.ndarray) -> tuple[list[str], bool]:
|
| 341 |
h, w = img.shape[:2]
|
|
|
|
| 342 |
area = float(w * h)
|
|
|
|
| 343 |
|
| 344 |
result = self.model(img, conf=self.conf, device=self.device, verbose=False)[0]
|
| 345 |
candidates = []
|
|
|
|
| 352 |
|
| 353 |
conf = float(result.boxes.conf[i])
|
| 354 |
x1, y1, x2, y2 = result.boxes.xyxy[i].tolist()
|
| 355 |
+
bw = max(1.0, x2 - x1)
|
| 356 |
+
bh = max(1.0, y2 - y1)
|
| 357 |
+
area_ratio = bw * bh / area
|
| 358 |
+
aspect = bw / bh
|
| 359 |
+
edge_contact = max(
|
| 360 |
+
1.0 - x1 / max(1.0, w * 0.18),
|
| 361 |
+
1.0 - (w - x2) / max(1.0, w * 0.18),
|
| 362 |
+
0.0,
|
| 363 |
+
)
|
| 364 |
+
|
| 365 |
+
if area_ratio < self.min_area or area_ratio > self.max_area:
|
| 366 |
+
continue
|
| 367 |
+
if aspect < self.min_aspect or aspect > self.max_aspect:
|
| 368 |
+
continue
|
| 369 |
|
| 370 |
+
vertical_bonus = min(1.8, 1.0 / max(aspect, 0.35))
|
| 371 |
+
area_bonus = 1.0 + min(area_ratio / 0.35, 1.0)
|
| 372 |
+
edge_bonus = 1.0 + 0.25 * min(edge_contact, 1.0)
|
| 373 |
+
score = conf * self.CLASS_WEIGHTS[cls_id] * vertical_bonus * area_bonus * edge_bonus
|
| 374 |
+
if score < self.min_score:
|
| 375 |
continue
|
| 376 |
|
| 377 |
+
candidates.append({
|
| 378 |
+
"score": score,
|
| 379 |
+
"box": (x1, y1, x2, y2),
|
| 380 |
+
"polygon": result.masks.xyn[i],
|
| 381 |
+
})
|
| 382 |
|
| 383 |
if not candidates:
|
| 384 |
+
return [], False
|
| 385 |
|
| 386 |
+
selected = []
|
| 387 |
+
for cand in sorted(candidates, key=lambda x: x["score"], reverse=True):
|
| 388 |
+
if len(selected) >= self.max_outputs:
|
| 389 |
+
break
|
| 390 |
+
if any(self._box_iou(cand["box"], prev["box"]) > self.iou_threshold for prev in selected):
|
| 391 |
+
continue
|
| 392 |
+
selected.append(cand)
|
| 393 |
|
| 394 |
+
lines = []
|
| 395 |
+
for cand in selected:
|
| 396 |
+
poly = cand["polygon"]
|
| 397 |
+
if len(poly) < 3:
|
| 398 |
+
continue
|
| 399 |
+
tokens = [str(self.class_id)]
|
| 400 |
+
for x, y in poly:
|
| 401 |
+
tokens.append(f"{float(x):.6f}")
|
| 402 |
+
tokens.append(f"{float(y):.6f}")
|
| 403 |
+
lines.append(" ".join(tokens))
|
| 404 |
+
return lines, bool(lines)
|
| 405 |
|
| 406 |
|
| 407 |
def auto_label_gas_folder(
|
|
|
|
| 431 |
continue
|
| 432 |
|
| 433 |
try:
|
| 434 |
+
labels, ok = segmenter.annotate(img)
|
| 435 |
+
write_lines(label_path, labels if ok else [])
|
| 436 |
stats["ok" if ok else "failed"] += 1
|
| 437 |
except Exception as exc:
|
| 438 |
print(f"Gas label error: {image_path.name}: {exc}")
|
|
|
|
| 450 |
|
| 451 |
# %%
|
| 452 |
# @title Step 6 - 自动标注补充气瓶数据
|
| 453 |
+
# @markdown 使用 `yolo11x-seg.pt` 预训练模型,并用几何规则过滤掉常见错检区域。
|
| 454 |
# @markdown 会给补充气瓶图片生成气瓶标签,也会给阀门图片中的气瓶区域生成气瓶标签。
|
| 455 |
# @markdown 这样训练时阀门图片里的气瓶不会被当成背景。
|
| 456 |
|
| 457 |
+
GAS_LABEL_MODEL = "yolo11x-seg.pt"
|
| 458 |
+
REGENERATE_GAS_LABELS = True # 必须覆盖之前旧筛选逻辑产生的错误气瓶标签。
|
| 459 |
GAS_LABEL_LIMIT = 0 # 0 表示处理全部图片。
|
| 460 |
|
| 461 |
GAS_EXTRA_LABEL_DIR = LABEL_WORK_DIR / "gas_extra"
|
|
|
|
| 1143 |
button_style="danger",
|
| 1144 |
layout=widgets.Layout(width="280px"),
|
| 1145 |
)
|
| 1146 |
+
select_gas_extra_button = widgets.Button(
|
| 1147 |
+
description="一键勾选全部 gas_extra",
|
| 1148 |
+
button_style="warning",
|
| 1149 |
+
layout=widgets.Layout(width="180px"),
|
| 1150 |
+
)
|
| 1151 |
+
clear_selection_button = widgets.Button(
|
| 1152 |
+
description="清空勾选",
|
| 1153 |
+
button_style="",
|
| 1154 |
+
layout=widgets.Layout(width="120px"),
|
| 1155 |
+
)
|
| 1156 |
summary_label = widgets.HTML(
|
| 1157 |
value="<b>操作提示:</b>删除后不用重新跑 Step 10,直接运行 Step 12 训练即可。"
|
| 1158 |
)
|
|
|
|
| 1211 |
checkboxes[idx].disabled = True
|
| 1212 |
|
| 1213 |
|
| 1214 |
+
def on_select_gas_extra_clicked(_button):
|
| 1215 |
+
for idx, checkbox in checkboxes.items():
|
| 1216 |
+
if not checkbox.disabled:
|
| 1217 |
+
checkbox.value = training_review_df.loc[idx, "source"] == "gas_extra"
|
| 1218 |
+
|
| 1219 |
+
|
| 1220 |
+
def on_clear_selection_clicked(_button):
|
| 1221 |
+
for checkbox in checkboxes.values():
|
| 1222 |
+
if not checkbox.disabled:
|
| 1223 |
+
checkbox.value = False
|
| 1224 |
+
|
| 1225 |
+
|
| 1226 |
+
select_gas_extra_button.on_click(on_select_gas_extra_clicked)
|
| 1227 |
+
clear_selection_button.on_click(on_clear_selection_clicked)
|
| 1228 |
delete_button.on_click(on_delete_clicked)
|
| 1229 |
|
| 1230 |
grid = widgets.GridBox(
|
|
|
|
| 1236 |
),
|
| 1237 |
)
|
| 1238 |
|
| 1239 |
+
display(widgets.VBox([
|
| 1240 |
+
summary_label,
|
| 1241 |
+
widgets.HBox([select_gas_extra_button, clear_selection_button, delete_button]),
|
| 1242 |
+
delete_output,
|
| 1243 |
+
grid,
|
| 1244 |
+
]))
|
| 1245 |
|
| 1246 |
|
| 1247 |
# %% [markdown]
|