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