seglint 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
seglint/config.py ADDED
@@ -0,0 +1,297 @@
1
+ """Configuration: seglint.toml or [tool.seglint] in pyproject.toml (CLI flags override)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field, fields
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from seglint._toml import tomllib
10
+
11
+
12
+ class ConfigError(Exception):
13
+ """Invalid or unreadable configuration."""
14
+
15
+
16
+ @dataclass
17
+ class Thresholds:
18
+ speckle_max_area_frac: float = 0.0001
19
+ max_components_per_class: int = 10
20
+ near_dup_hamming: int = 6 # pHash; was 4 (initial default), see docs/checks.md (L002)
21
+ near_dup_dhash_hamming: int = 8 # dHash confirmation of a pHash candidate pair
22
+ # a match after a flip/rotation (7 extra chances for a coincidence) needs tighter limits
23
+ near_dup_dihedral_hamming: int = 4
24
+ near_dup_dihedral_dhash_hamming: int = 4
25
+ # tight limits = tier "near_identical" (L002 WARNING, L003 ERROR, L004 runs on these only);
26
+ # pairs within the limits above but not these are tier "similar" (L002 INFO, L003 WARNING)
27
+ near_identical_hamming: int = 4
28
+ near_identical_dhash_hamming: int = 4
29
+ near_identical_dihedral_hamming: int = 2
30
+ near_identical_dihedral_dhash_hamming: int = 4
31
+ mask_iou_warn: float = 0.5 # L004: IoU below this is a WARNING (provisional)
32
+ mask_iou_info: float = 0.9 # L004: IoU below this (and >= warn) is an INFO
33
+ jagged_mad_z: float = 10.0
34
+ small_hole_max_area_frac: float = 0.0005
35
+ speckle_warn_count: int = 3
36
+ small_hole_warn_area_frac: float = 0.002 # was small_hole_warn_count = 1000 (provisional)
37
+ rare_class_pixel_frac: float = 0.0003
38
+ resolution_mad_z: float = 5.0
39
+ resolution_min_rel_dev: float = 0.5
40
+ split_drift_z: float = 5.0
41
+ split_drift_min_tv: float = 0.03
42
+ min_split_samples: int = 30
43
+ # T005/T006 (absolute, fixed): foreground share of the whole image
44
+ near_empty_info_frac: float = 0.001 # 0 < share < this: INFO (near-empty)
45
+ near_empty_warn_frac: float = 0.0001 # 0 < share < this: WARNING
46
+ full_mask_info_frac: float = 0.95 # share >= this: INFO (mask covers almost the whole image)
47
+ full_mask_warn_frac: float = 0.99 # share >= this: WARNING
48
+ # R001-R004 (relative to the dataset): normal range = median +- k * scaled MAD
49
+ relative_k: float = 3.5 # the one global knob (3.5 = conventional modified-z cut-off)
50
+ relative_k_area_frac: float = 0.0 # per-check override of relative_k (0 = use relative_k)
51
+ relative_k_position: float = 0.0
52
+ relative_k_shape: float = 0.0
53
+ relative_k_object_count: float = 0.0
54
+ relative_k_holes: float = 0.0 # G003 relative tier
55
+ relative_k_speckles: float = 0.0 # G002 relative tier
56
+ relative_warn_factor: float = 2.0 # WARNING instead of INFO beyond this many times k
57
+ relative_min_scale_log: float = 0.2 # floor of the scale of log-transformed measures
58
+ relative_min_scale_unit: float = 0.03 # floor of the scale of measures in [0, 1]
59
+ min_class_samples: int = 30 # fewer samples of a class: fall back to all-class statistics
60
+ min_relative_samples: int = 50 # fewer samples in the dataset: relative checks are skipped
61
+ # Notice (no effect on findings or exit code) when one relative check flags more than this
62
+ # share of the samples: its notion of "normal" may have shifted.
63
+ majority_warn_fraction: float = 0.20
64
+ # class id -> overrides of the fields above
65
+ per_class: dict[int, dict[str, Any]] = field(default_factory=dict)
66
+
67
+ def for_class(self, class_id: int, name: str) -> Any:
68
+ return self.per_class.get(class_id, {}).get(name, getattr(self, name))
69
+
70
+
71
+ @dataclass
72
+ class Reference:
73
+ """Frozen statistics of a calibration run: measure -> {class id | None (global): stats}."""
74
+
75
+ n_samples: int # samples with usable masks in the reference set
76
+ stats: dict[str, dict[int | None, Any]] = field(default_factory=dict) # RobustStats values
77
+
78
+
79
+ @dataclass
80
+ class Config:
81
+ ignore_index: int = 255
82
+ mask_suffix: str = ""
83
+ classes: dict[int, str] = field(default_factory=dict)
84
+ binary: bool = False
85
+ palette: dict[tuple[int, int, int], int] = field(default_factory=dict)
86
+ allow_empty_masks: bool = False
87
+ # Class id treated as background by T001 and the G checks (-1 = no background class).
88
+ background_index: int = 0
89
+ # Component analysis runs on masks downscaled (nearest-neighbour) so the longer side is at
90
+ # most this many pixels; 0 disables downscaling. Areas stay relative, see docs/checks.md.
91
+ analysis_max_side: int = 1024
92
+ # Example cards per check in the HTML report (and files per check for --export-examples).
93
+ max_examples: int = 50
94
+ # Profile checks (G004 border contact, T003 resolution outliers) are off by default; their
95
+ # facts appear in the dataset profile instead. True turns them back on as findings.
96
+ include_profile_checks: bool = False
97
+ # Experimental checks (G005 jagged boundary) run only when this is true or --experimental.
98
+ experimental: bool = False
99
+ thresholds: Thresholds = field(default_factory=Thresholds)
100
+ # Frozen reference statistics written by `seglint calibrate` (None: statistics are computed
101
+ # from the scanned dataset itself).
102
+ reference: Reference | None = None
103
+ # Provenance of every value that was not left at its default: "classes", "binary", ...,
104
+ # "thresholds.<name>" -> "cli" | "user config" | "calibrated" (absent = "default").
105
+ sources: dict[str, str] = field(default_factory=dict)
106
+
107
+ @property
108
+ def known_classes(self) -> set[int] | None:
109
+ """Declared class ids, or None when no class list was configured."""
110
+ return set(self.classes) if self.classes else None
111
+
112
+
113
+ def parse_classes(raw: Any) -> dict[int, str]:
114
+ if isinstance(raw, list):
115
+ return {i: str(n) for i, n in enumerate(raw)}
116
+ if not isinstance(raw, dict):
117
+ raise ConfigError("'classes' must be a table or list")
118
+ try:
119
+ return {int(k): str(v) for k, v in raw.items()}
120
+ except ValueError as e:
121
+ raise ConfigError(f"invalid class id in 'classes': {e}") from e
122
+
123
+
124
+ def parse_palette(raw: Any) -> dict[tuple[int, int, int], int]:
125
+ """Palette JSON: {"0": [0,0,0], ...} (class -> rgb) or {"r,g,b": class}."""
126
+ if not isinstance(raw, dict):
127
+ raise ConfigError("palette must be a JSON object")
128
+ out: dict[tuple[int, int, int], int] = {}
129
+ try:
130
+ for k, v in raw.items():
131
+ if isinstance(v, list):
132
+ out[tuple(int(c) for c in v)] = int(k) # type: ignore[assignment]
133
+ else:
134
+ out[tuple(int(c) for c in k.split(","))] = int(v) # type: ignore[assignment]
135
+ except (ValueError, TypeError) as e:
136
+ raise ConfigError(f"invalid palette: {e}") from e
137
+ if any(len(c) != 3 for c in out):
138
+ raise ConfigError("palette colors must have 3 channels")
139
+ return out
140
+
141
+
142
+ _TOP_KEYS = {"ignore_index", "mask_suffix", "classes", "binary", "allow_empty_masks",
143
+ "thresholds", "background_index", "analysis_max_side", "include_profile_checks",
144
+ "experimental", "max_examples"} # fmt: skip
145
+
146
+
147
+ def _apply(cfg: Config, data: dict[str, Any], source: str) -> None:
148
+ """Write the values of one config layer into `cfg` and record their `source`."""
149
+ unknown = set(data) - _TOP_KEYS
150
+ if unknown:
151
+ raise ConfigError(f"unknown config keys: {', '.join(sorted(unknown))}")
152
+ try:
153
+ for key, conv in (("ignore_index", int), ("mask_suffix", str), ("binary", bool),
154
+ ("background_index", int), ("allow_empty_masks", bool),
155
+ ("include_profile_checks", bool), ("experimental", bool)): # fmt: skip
156
+ if key in data:
157
+ setattr(cfg, key, conv(data[key]))
158
+ cfg.sources[key] = source
159
+ if "analysis_max_side" in data:
160
+ cfg.analysis_max_side = max(0, int(data["analysis_max_side"]))
161
+ cfg.sources["analysis_max_side"] = source
162
+ if "max_examples" in data:
163
+ cfg.max_examples = max(0, int(data["max_examples"]))
164
+ cfg.sources["max_examples"] = source
165
+ except (TypeError, ValueError) as e:
166
+ raise ConfigError(f"invalid config value: {e}") from e
167
+ if "classes" in data:
168
+ cfg.classes = parse_classes(data["classes"])
169
+ cfg.sources["classes"] = source
170
+ th = dict(data.get("thresholds", {}))
171
+ per_class = th.pop("per_class", None)
172
+ t_known = {f.name for f in fields(Thresholds)} - {"per_class"}
173
+ bad = set(th) - t_known
174
+ if bad:
175
+ raise ConfigError(f"unknown thresholds: {', '.join(sorted(bad))}")
176
+ for k, v in th.items():
177
+ try:
178
+ setattr(cfg.thresholds, k, type(getattr(cfg.thresholds, k))(v))
179
+ except (TypeError, ValueError) as e:
180
+ raise ConfigError(f"invalid value for thresholds.{k}: {e}") from e
181
+ cfg.sources[f"thresholds.{k}"] = source
182
+ if per_class is not None:
183
+ try:
184
+ cfg.thresholds.per_class = {int(k): dict(v) for k, v in per_class.items()}
185
+ except (ValueError, TypeError) as e:
186
+ raise ConfigError(f"invalid thresholds.per_class: {e}") from e
187
+ cfg.sources["thresholds.per_class"] = source
188
+
189
+
190
+ def parse_reference(cal: dict[str, Any]) -> Reference | None:
191
+ """`[calibrated.stats.<measure>.<global|class_N>]` tables -> Reference (None: no stats)."""
192
+ from seglint.relative import MEASURES, PERCENTILES, RobustStats
193
+
194
+ raw = cal.get("stats")
195
+ if not raw:
196
+ return None
197
+ try:
198
+ n_samples = int(cal.get("n_valid", 0))
199
+ stats: dict[str, dict[int | None, Any]] = {}
200
+ for measure, per in raw.items():
201
+ if measure not in MEASURES:
202
+ raise ConfigError(f"unknown measure in calibrated.stats: {measure}")
203
+ out: dict[int | None, Any] = {}
204
+ for key, t in per.items():
205
+ if key == "global":
206
+ cls: int | None = None
207
+ elif key.startswith("class_"):
208
+ cls = int(key[6:])
209
+ else:
210
+ raise ConfigError(f"bad calibrated.stats.{measure} table: {key}")
211
+ out[cls] = RobustStats(
212
+ int(t["n"]), float(t["median"]), float(t["scaled_mad"]), float(t["scale"]),
213
+ str(t["scale_rule"]), str(t["transform"]),
214
+ {p: float(t[f"p{p}"]) for p in PERCENTILES if f"p{p}" in t},
215
+ "global" if cls is None else "class",
216
+ ) # fmt: skip
217
+ stats[measure] = out
218
+ except (KeyError, TypeError, ValueError, AttributeError) as e:
219
+ raise ConfigError(f"invalid [calibrated] statistics: {e!r}") from e
220
+ return Reference(n_samples, stats)
221
+
222
+
223
+ def config_from_dict(data: dict[str, Any]) -> Config:
224
+ """Layers, weakest first: defaults < `[calibrated]` (written by `seglint calibrate`) < the
225
+ user's own keys. CLI flags are applied on top by the caller."""
226
+ cfg = Config()
227
+ data = dict(data)
228
+ cal = data.pop("calibrated", None)
229
+ if cal is not None:
230
+ if not isinstance(cal, dict):
231
+ raise ConfigError("'calibrated' must be a table")
232
+ layer = {**cal.get("options", {}), "thresholds": cal.get("thresholds", {})}
233
+ _apply(cfg, layer, "calibrated")
234
+ cfg.reference = parse_reference(cal)
235
+ _apply(cfg, data, "user config")
236
+ return cfg
237
+
238
+
239
+ SENSITIVITY_K = {"strict": 2.5, "balanced": 3.5, "relaxed": 5.0}
240
+
241
+
242
+ def apply_sensitivity(cfg: Config, name: str, source: str = "cli") -> None:
243
+ """`--sensitivity`: set `relative_k` to the preset and clear the per-check overrides, so one
244
+ flag moves every relative check. strict = 2.5 (flags more), balanced = 3.5, relaxed = 5.0."""
245
+ if name not in SENSITIVITY_K:
246
+ raise ConfigError(f"unknown sensitivity {name!r} (strict, balanced or relaxed)")
247
+ th = cfg.thresholds
248
+ th.relative_k = SENSITIVITY_K[name]
249
+ cfg.sources["thresholds.relative_k"] = f"{source} (--sensitivity {name})"
250
+ for f in fields(Thresholds):
251
+ if f.name.startswith("relative_k_"):
252
+ setattr(th, f.name, 0.0)
253
+ cfg.sources.pop(f"thresholds.{f.name}", None)
254
+
255
+
256
+ def source_of(cfg: Config, key: str) -> str:
257
+ return cfg.sources.get(key, "default")
258
+
259
+
260
+ def effective_values(cfg: Config) -> list[tuple[str, Any, str]]:
261
+ """(key, effective value, source) of every config value, for `check --explain-config`."""
262
+ rows: list[tuple[str, Any, str]] = []
263
+ for key in ("ignore_index", "mask_suffix", "binary", "background_index", "analysis_max_side",
264
+ "allow_empty_masks", "classes", "experimental",
265
+ "include_profile_checks", "max_examples"): # fmt: skip
266
+ rows.append((key, getattr(cfg, key), source_of(cfg, key)))
267
+ for f in fields(Thresholds):
268
+ v = getattr(cfg.thresholds, f.name)
269
+ if f.name == "per_class" and not v:
270
+ continue
271
+ rows.append((f"thresholds.{f.name}", v, source_of(cfg, f"thresholds.{f.name}")))
272
+ return rows
273
+
274
+
275
+ def _read_toml(path: Path) -> dict[str, Any]:
276
+ try:
277
+ with path.open("rb") as f:
278
+ return tomllib.load(f)
279
+ except (OSError, tomllib.TOMLDecodeError) as e:
280
+ raise ConfigError(f"cannot read {path}: {e}") from e
281
+
282
+
283
+ def load_config(start: Path | None, explicit: Path | None = None) -> Config:
284
+ """Load config from `explicit`, else seglint.toml / pyproject.toml in `start` or cwd."""
285
+ if explicit is not None:
286
+ data = _read_toml(explicit)
287
+ return config_from_dict(data.get("tool", {}).get("seglint", data))
288
+ dirs = [d for d in (start, Path.cwd()) if d is not None and d.is_dir()]
289
+ for d in dirs:
290
+ if (d / "seglint.toml").is_file():
291
+ data = _read_toml(d / "seglint.toml")
292
+ return config_from_dict(data.get("tool", {}).get("seglint", data))
293
+ if (d / "pyproject.toml").is_file():
294
+ section = _read_toml(d / "pyproject.toml").get("tool", {}).get("seglint")
295
+ if section is not None:
296
+ return config_from_dict(section)
297
+ return Config()
seglint/demo.py ADDED
@@ -0,0 +1,152 @@
1
+ """`seglint demo`: a small synthetic dataset with planted defects, checked end to end.
2
+
3
+ The dataset is deterministic for a given seed, needs no download and no network, and is written
4
+ in layout A (``<out>/data/{train,val}/{images,masks}``). Every planted defect is recorded in an
5
+ answer key (``demo_answer_key.json``) together with the check expected to report it, so the
6
+ report can be verified against it. The report itself does not reveal the answer key.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import shutil
13
+ from dataclasses import asdict, dataclass
14
+ from pathlib import Path
15
+
16
+ import cv2
17
+ import numpy as np
18
+ from PIL import Image
19
+
20
+ SIZE = 128 # image and mask side, px
21
+ N_TRAIN = 40
22
+ N_VAL = 16
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class PlantedDefect:
27
+ """One defect put into the demo dataset on purpose."""
28
+
29
+ sample_id: str # as seglint names it: "<split>/<file stem>"
30
+ defect: str
31
+ expected_check: str
32
+ files: tuple[str, ...] # paths relative to the dataset root
33
+
34
+
35
+ def _texture(rng: np.random.Generator) -> np.ndarray:
36
+ """A smooth random RGB image: unrelated images get unrelated perceptual hashes."""
37
+ small = rng.integers(0, 256, size=(8, 8, 3)).astype(np.float32)
38
+ img = cv2.resize(small, (SIZE, SIZE), interpolation=cv2.INTER_CUBIC)
39
+ noise = rng.normal(0, 6, size=(SIZE, SIZE, 3))
40
+ return np.clip(img + noise, 0, 255).astype(np.uint8)
41
+
42
+
43
+ def _blob(rng: np.random.Generator, cx: float | None = None, cy: float | None = None) -> np.ndarray:
44
+ """An ellipse near the centre (the dataset's 'normal' mask), values 0/1."""
45
+ m = np.zeros((SIZE, SIZE), np.uint8)
46
+ cx = SIZE / 2 + rng.uniform(-3, 3) if cx is None else cx
47
+ cy = SIZE / 2 + rng.uniform(-3, 3) if cy is None else cy
48
+ axes = (int(rng.uniform(22, 30)), int(rng.uniform(18, 26)))
49
+ cv2.ellipse(m, (int(cx), int(cy)), axes, rng.uniform(0, 180), 0, 360, 1, -1)
50
+ return m
51
+
52
+
53
+ def _save(path: Path, arr: np.ndarray) -> None:
54
+ path.parent.mkdir(parents=True, exist_ok=True)
55
+ Image.fromarray(arr).save(path)
56
+
57
+
58
+ def build_dataset(root: Path, seed: int = 0) -> list[PlantedDefect]:
59
+ """Write the demo dataset under `root` and return the planted defects.
60
+
61
+ Args:
62
+ root: Dataset root; ``train/`` and ``val/`` are created inside (existing content of
63
+ those two folders is replaced).
64
+ seed: Random seed; the same seed always gives the same files.
65
+
66
+ Returns:
67
+ The planted defects, one per affected sample.
68
+ """
69
+ rng = np.random.default_rng(seed)
70
+ for split in ("train", "val"):
71
+ shutil.rmtree(root / split, ignore_errors=True)
72
+ names = [("train", f"img_{i:03d}") for i in range(N_TRAIN)]
73
+ names += [("val", f"img_{i:03d}") for i in range(N_TRAIN, N_TRAIN + N_VAL)]
74
+ images = {n: _texture(rng) for n in names}
75
+ masks = {n: _blob(rng) for n in names}
76
+ planted: list[PlantedDefect] = []
77
+
78
+ def plant(split: str, stem: str, defect: str, check: str, *files: str) -> None:
79
+ planted.append(PlantedDefect(f"{split}/{stem}", defect, check, tuple(files)))
80
+
81
+ def mpath(split: str, stem: str) -> str:
82
+ return f"{split}/masks/{stem}.png"
83
+
84
+ # 1. empty mask
85
+ masks[("train", "img_001")][:] = 0
86
+ plant("train", "img_001", "empty mask", "T001", mpath("train", "img_001"))
87
+ # 2. mask (almost) filling the image: >= 99% foreground
88
+ m = np.ones((SIZE, SIZE), np.uint8)
89
+ m[:6, :6] = 0
90
+ masks[("train", "img_002")] = m
91
+ plant("train", "img_002", "mask fills the image", "T006", mpath("train", "img_002"))
92
+ # 3. small holes inside the mask (>= 0.2% of the class area; each hole <= 4 px)
93
+ m = masks[("train", "img_003")]
94
+ for dy, dx in ((-8, -8), (-8, 8), (8, -8), (8, 8), (0, 0)):
95
+ y, x = SIZE // 2 + dy, SIZE // 2 + dx
96
+ m[y : y + 2, x : x + 2] = 0
97
+ plant("train", "img_003", "small holes", "G003", mpath("train", "img_003"))
98
+ # 4. specks outside the mask (single pixels, far from the object)
99
+ m = masks[("train", "img_004")]
100
+ for y, x in ((6, 6), (6, 120), (120, 6), (120, 120), (6, 64)):
101
+ m[y, x] = 1
102
+ plant("train", "img_004", "speckles", "G002", mpath("train", "img_004"))
103
+ # 5. mask broken into many pieces (12 squares of 5x5 px)
104
+ m = np.zeros((SIZE, SIZE), np.uint8)
105
+ for k in range(12):
106
+ y, x = 30 + (k // 4) * 25, 20 + (k % 4) * 25
107
+ m[y : y + 5, x : x + 5] = 1
108
+ masks[("train", "img_005")] = m
109
+ plant("train", "img_005", "fragmented mask", "G001", mpath("train", "img_005"))
110
+ # 6. mask moved far from where this dataset puts its object
111
+ masks[("train", "img_006")] = _blob(rng, cx=20, cy=20)
112
+ plant("train", "img_006", "mask far from its usual position", "R002", mpath("train", "img_006"))
113
+ # 7. mask with another size than its image
114
+ masks[("train", "img_007")] = cv2.resize(
115
+ masks[("train", "img_007")], (SIZE // 2, SIZE // 2), interpolation=cv2.INTER_NEAREST
116
+ )
117
+ plant("train", "img_007", "image/mask size mismatch", "S003", mpath("train", "img_007"))
118
+ # 8. image without a mask
119
+ del masks[("train", "img_008")]
120
+ plant("train", "img_008", "image without a mask", "S001", "train/images/img_008.png")
121
+ # 9. byte-identical image twice in the same split (and the same mask)
122
+ images[("train", "img_010")] = images[("train", "img_009")]
123
+ masks[("train", "img_010")] = masks[("train", "img_009")]
124
+ plant("train", "img_009", "exact duplicate image (pair with train/img_010)", "L001",
125
+ "train/images/img_009.png", "train/images/img_010.png") # fmt: skip
126
+ # 10. train/val leakage: a slightly brighter copy of a training image in val
127
+ src = images[("train", "img_011")].astype(np.int16)
128
+ images[("val", "img_050")] = np.clip(src + 12, 0, 255).astype(np.uint8)
129
+ masks[("val", "img_050")] = masks[("train", "img_011")]
130
+ plant("train", "img_011", "near-duplicate across train/val (pair with val/img_050)", "L003",
131
+ "train/images/img_011.png", "val/images/img_050.png") # fmt: skip
132
+
133
+ for (split, stem), img in images.items():
134
+ _save(root / split / "images" / f"{stem}.png", img)
135
+ for (split, stem), m in masks.items():
136
+ _save(root / split / "masks" / f"{stem}.png", m)
137
+ return planted
138
+
139
+
140
+ def write_answer_key(path: Path, planted: list[PlantedDefect], seed: int) -> None:
141
+ data = {"seed": seed, "planted": [asdict(p) for p in planted]}
142
+ path.write_text(json.dumps(data, indent=2), encoding="utf-8")
143
+
144
+
145
+ def caught(planted: list[PlantedDefect], issues) -> dict[str, bool]:
146
+ """sample id -> whether the expected check reported that sample (pairs: either member)."""
147
+ seen = {(i.check_id, i.sample_id) for i in issues}
148
+ for i in issues:
149
+ for key in ("sample_a", "sample_b"):
150
+ if i.data.get(key):
151
+ seen.add((i.check_id, i.data[key]))
152
+ return {p.sample_id: (p.expected_check, p.sample_id) in seen for p in planted}
seglint/features.py ADDED
@@ -0,0 +1,86 @@
1
+ """Mask-only per-class features (pass 1): area fraction, centroid, object count, shape.
2
+
3
+ Everything is measured on the analysis grid except the area fraction, which uses the true-size
4
+ class pixel counts. All outputs are dimensionless, so they are comparable across resolutions.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import math
10
+
11
+ import cv2
12
+ import numpy as np
13
+
14
+ from seglint.checks._limits import speckle_limit
15
+ from seglint.models import ClassFeatures, ComponentStat
16
+
17
+ PIXEL_VARIANCE = 1 / 12 # variance of a unit pixel; keeps the PCA axis ratio finite for 1-px lines
18
+
19
+
20
+ def shape_features(binm: np.ndarray) -> tuple[float, float, float] | None:
21
+ """(solidity, elongation, circularity) of the largest 8-connected component of `binm`.
22
+
23
+ - solidity = component pixels / pixels of the rasterised convex hull (<= 1; a filled
24
+ rectangle is exactly 1, holes and concavities lower it).
25
+ - elongation = sqrt(l1 / l2) of the covariance of the pixel coordinates (PCA axis ratio),
26
+ with 1/12 added to both eigenvalues (pixel variance): disc/square ~1, an a:b ellipse a/b.
27
+ PCA was chosen over the min-area rectangle because it is smooth in the shape (no rotation
28
+ jumps) and uses every pixel instead of the hull vertices only.
29
+ - circularity = 4*pi*A/P^2 with P = cv2.arcLength of the outer contour (through pixel
30
+ centres), clipped to 1 (the discrete contour can be shorter than the ideal circle).
31
+ """
32
+ n, labels, stats, _ = cv2.connectedComponentsWithStats(binm, connectivity=8)
33
+ if n < 2:
34
+ return None
35
+ lab = 1 + int(np.argmax(stats[1:, cv2.CC_STAT_AREA]))
36
+ comp = (labels == lab).astype(np.uint8)
37
+ area = float(stats[lab, cv2.CC_STAT_AREA])
38
+ contours, _ = cv2.findContours(comp, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
39
+ contour = max(contours, key=len)
40
+ perim = float(cv2.arcLength(contour, True))
41
+ hull = np.zeros_like(comp)
42
+ cv2.fillConvexPoly(hull, cv2.convexHull(contour), 1)
43
+ solidity = min(1.0, area / max(1, int(hull.sum())))
44
+ ys, xs = np.nonzero(comp)
45
+ cov = (
46
+ np.cov(np.vstack([xs, ys]).astype(np.float64), bias=True) if area > 1 else np.zeros((2, 2))
47
+ )
48
+ ev = np.sort(np.linalg.eigvalsh(cov))[::-1] + PIXEL_VARIANCE
49
+ elong = math.sqrt(ev[0] / ev[1])
50
+ circ = min(1.0, 4 * math.pi * area / (perim * perim)) if perim > 0 else 1.0
51
+ return solidity, elong, circ
52
+
53
+
54
+ def extract_class_features(
55
+ grid: np.ndarray,
56
+ comps: dict[int, list[ComponentStat]],
57
+ cfg,
58
+ true_counts: dict[int, int],
59
+ true_area: int,
60
+ ) -> dict[int, ClassFeatures]:
61
+ """Features of every foreground class in `comps` (the grid's components, background and
62
+ ignore already excluded)."""
63
+ gh, gw = grid.shape
64
+ lim_area = gh * gw
65
+ out: dict[int, ClassFeatures] = {}
66
+ for cls, cs in comps.items():
67
+ if not cs or true_counts.get(cls, 0) == 0:
68
+ continue
69
+ x0 = min(c.bbox[0] for c in cs)
70
+ y0 = min(c.bbox[1] for c in cs)
71
+ x1 = max(c.bbox[0] + c.bbox[2] for c in cs)
72
+ y1 = max(c.bbox[1] + c.bbox[3] for c in cs)
73
+ ys, xs = np.nonzero(grid[y0:y1, x0:x1] == cls)
74
+ cx = (float(xs.mean()) + x0 + 0.5) / gw
75
+ cy = (float(ys.mean()) + y0 + 0.5) / gh
76
+ lim = speckle_limit(cfg, cls, lim_area)
77
+ objects = [c for c in cs if c.area > lim]
78
+ shape = None
79
+ if objects:
80
+ big = max(objects, key=lambda c: c.area)
81
+ x, y, w, h = big.bbox
82
+ shape = shape_features((grid[y : y + h, x : x + w] == cls).astype(np.uint8))
83
+ out[cls] = ClassFeatures(
84
+ true_counts[cls] / true_area, cx, cy, len(objects), *(shape or (None, None, None))
85
+ )
86
+ return out