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/hashing.py ADDED
@@ -0,0 +1,226 @@
1
+ """Perceptual image hashes (dHash, pHash) and a banded index for near-duplicate search.
2
+
3
+ Both hashes are 64 bit integers computed from a tiny grayscale version of the image (the image is
4
+ reduced with area averaging, so the cost is one pass over the pixels). pHash is the sign of the
5
+ 8x8 low-frequency block of a 32x32 DCT against its median (robust to resizing, re-encoding and
6
+ small brightness changes); dHash compares horizontally adjacent cells of a 9x8 version (cheaper,
7
+ sensitive to local structure). No third-party hashing library is used.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import cv2
13
+ import numpy as np
14
+
15
+ HASH_BITS = 64
16
+ PHASH_SIZE = 32 # DCT input side; the 8x8 low-frequency corner gives 64 bits
17
+
18
+
19
+ REDUCED_SIDE = 64 # both hashes are derived from one 64x64 area-averaged copy of the image
20
+
21
+
22
+ def _bits_to_int(bits: np.ndarray) -> int:
23
+ """Row-major bit array (len 64) -> int, first element is the most significant bit."""
24
+ v = 0
25
+ for b in bits.ravel().tolist():
26
+ v = (v << 1) | int(b)
27
+ return v
28
+
29
+
30
+ def _reduced_gray(image: np.ndarray) -> np.ndarray:
31
+ """64x64 uint8 grayscale of the image. The single pass over the full-size pixels is one
32
+ area-averaging resize (averaging is linear, so doing it before the gray conversion gives the
33
+ same result as after it, at a fraction of the cost on large images)."""
34
+ img = np.ascontiguousarray(image)
35
+ if img.dtype != np.uint8:
36
+ img = cv2.normalize(img.astype(np.float32), None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8)
37
+ small = cv2.resize(img, (REDUCED_SIDE, REDUCED_SIDE), interpolation=cv2.INTER_AREA)
38
+ if small.ndim == 3:
39
+ small = cv2.cvtColor(small, cv2.COLOR_RGB2GRAY) if small.shape[2] >= 3 else small[..., 0]
40
+ return small
41
+
42
+
43
+ def _phash_from(gray64: np.ndarray) -> int:
44
+ small = cv2.resize(gray64, (PHASH_SIZE, PHASH_SIZE), interpolation=cv2.INTER_AREA)
45
+ low = cv2.dct(small.astype(np.float32))[:8, :8]
46
+ return _bits_to_int(low > np.median(low))
47
+
48
+
49
+ def _dhash_from(gray64: np.ndarray) -> int:
50
+ small = cv2.resize(gray64, (9, 8), interpolation=cv2.INTER_AREA).astype(np.int16)
51
+ return _bits_to_int(small[:, 1:] > small[:, :-1])
52
+
53
+
54
+ def phash(image: np.ndarray) -> int:
55
+ """64-bit DCT perceptual hash of an HxW or HxWx3 image."""
56
+ return _phash_from(_reduced_gray(image))
57
+
58
+
59
+ def dhash(image: np.ndarray) -> int:
60
+ """64-bit difference hash: is each cell of a 9x8 version darker than its right neighbour."""
61
+ return _dhash_from(_reduced_gray(image))
62
+
63
+
64
+ def hamming(a: int, b: int) -> int:
65
+ return (a ^ b).bit_count()
66
+
67
+
68
+ def band_masks(k: int) -> list[tuple[int, int]]:
69
+ """(shift, mask) of the k+1 bands (as equal as possible) that split a 64-bit hash."""
70
+ n = max(1, min(k + 1, HASH_BITS))
71
+ base, extra = divmod(HASH_BITS, n)
72
+ out, shift = [], 0
73
+ for i in range(n):
74
+ width = base + (1 if i < extra else 0)
75
+ out.append((shift, (1 << width) - 1))
76
+ shift += width
77
+ return out
78
+
79
+
80
+ def find_near_pairs(hashes: list[int], k: int) -> list[tuple[int, int, int]]:
81
+ """All pairs (i, j, distance), i < j, with Hamming distance <= k, sorted by (i, j).
82
+
83
+ Pigeonhole: split the hash into k+1 bands; two hashes that differ in at most k bits agree
84
+ exactly on at least one band. Hashes sharing a band value are candidates and only those are
85
+ compared in full, so no O(n^2) scan over all pairs. Identical hashes are collapsed first.
86
+ """
87
+ if k < 0 or len(hashes) < 2:
88
+ return []
89
+ groups: dict[int, list[int]] = {}
90
+ for i, h in enumerate(hashes):
91
+ groups.setdefault(h, []).append(i)
92
+ uniq = list(groups)
93
+ cand: set[tuple[int, int]] = set()
94
+ for shift, mask in band_masks(k):
95
+ buckets: dict[int, list[int]] = {}
96
+ for u, h in enumerate(uniq):
97
+ buckets.setdefault((h >> shift) & mask, []).append(u)
98
+ for members in buckets.values():
99
+ for a in range(len(members)):
100
+ for b in range(a + 1, len(members)):
101
+ cand.add((members[a], members[b]))
102
+ pairs: list[tuple[int, int, int]] = []
103
+ for members in groups.values(): # exact copies of one hash value: distance 0
104
+ for a in range(len(members)):
105
+ for b in range(a + 1, len(members)):
106
+ pairs.append((members[a], members[b], 0))
107
+ for ua, ub in cand:
108
+ d = hamming(uniq[ua], uniq[ub])
109
+ if d <= k:
110
+ for i in groups[uniq[ua]]:
111
+ for j in groups[uniq[ub]]:
112
+ pairs.append((min(i, j), max(i, j), d))
113
+ pairs.sort()
114
+ return pairs
115
+
116
+
117
+ def brute_force_pairs(hashes: list[int], k: int) -> list[tuple[int, int, int]]:
118
+ """Reference O(n^2) implementation (tests only)."""
119
+ return [
120
+ (i, j, d)
121
+ for i in range(len(hashes))
122
+ for j in range(i + 1, len(hashes))
123
+ if (d := hamming(hashes[i], hashes[j])) <= k
124
+ ]
125
+
126
+
127
+ # --- dihedral transforms -----------------------------------------------------------------------
128
+ # The 8 symmetries of the square. `apply_dihedral(a, t)` on an array a: B ~ T_t(A) means that B
129
+ # looks like A mirrored/rotated by t. Hashes of all 8 variants of an image come from its 64x64
130
+ # reduction (area averaging commutes with these symmetries), so mirrored/rotated copies are found
131
+ # without touching the pixels again.
132
+ DIHEDRAL_NAMES = (
133
+ "identity", "flipH", "flipV", "rot90", "rot180", "rot270", "transpose", "antitranspose",
134
+ ) # fmt: skip
135
+ DIHEDRAL_INVERSE = (0, 1, 2, 5, 4, 3, 6, 7)
136
+
137
+
138
+ def apply_dihedral(a: np.ndarray, t: int) -> np.ndarray:
139
+ """Symmetry `t` (0..7) of an HxW or HxWxC array: only the first two axes are moved."""
140
+ if t == 0:
141
+ return a
142
+ if t == 1:
143
+ return a[:, ::-1]
144
+ if t == 2:
145
+ return a[::-1]
146
+ if t == 3:
147
+ return np.rot90(a, 1)
148
+ if t == 4:
149
+ return a[::-1, ::-1]
150
+ if t == 5:
151
+ return np.rot90(a, 3)
152
+ if t == 6:
153
+ return a.swapaxes(0, 1)
154
+ if t == 7:
155
+ return a[::-1, ::-1].swapaxes(0, 1)
156
+ raise ValueError(f"dihedral transform id must be 0..7, got {t}")
157
+
158
+
159
+ def image_hash_set(image: np.ndarray) -> tuple[int, int, tuple[tuple[int, int], ...]]:
160
+ """(pHash, dHash, ((pHash, dHash) of the 7 non-identity dihedral variants))."""
161
+ g = _reduced_gray(image)
162
+ variants = tuple(
163
+ (_phash_from(v), _dhash_from(v))
164
+ for v in (np.ascontiguousarray(apply_dihedral(g, t)) for t in range(1, 8))
165
+ )
166
+ return _phash_from(g), _dhash_from(g), variants
167
+
168
+
169
+ class BandedIndex:
170
+ """Banded pHash index over `hashes`; `query(h)` returns every (index, distance <= k)."""
171
+
172
+ def __init__(self, hashes: list[int], k: int):
173
+ self.k = k
174
+ self.groups: dict[int, list[int]] = {}
175
+ for i, h in enumerate(hashes):
176
+ self.groups.setdefault(h, []).append(i)
177
+ self.bands = band_masks(k)
178
+ self.tables: list[dict[int, list[int]]] = [{} for _ in self.bands]
179
+ for h in self.groups:
180
+ for (shift, mask), table in zip(self.bands, self.tables, strict=True):
181
+ table.setdefault((h >> shift) & mask, []).append(h)
182
+
183
+ def query(self, h: int) -> list[tuple[int, int]]:
184
+ if self.k < 0:
185
+ return []
186
+ seen: set[int] = set()
187
+ out: list[tuple[int, int]] = []
188
+ for (shift, mask), table in zip(self.bands, self.tables, strict=True):
189
+ for cand in table.get((h >> shift) & mask, ()):
190
+ if cand in seen:
191
+ continue
192
+ seen.add(cand)
193
+ d = hamming(h, cand)
194
+ if d <= self.k:
195
+ out.extend((i, d) for i in self.groups[cand])
196
+ return out
197
+
198
+
199
+ def find_near_pairs_dihedral(
200
+ hashes: list[int], variants: list[tuple[int, ...]], k: int
201
+ ) -> list[tuple[int, int, int, int]]:
202
+ """(i, j, t, distance): the pHash of variant t of sample i is within k bits of sample j's own
203
+ pHash (i != j, t in 0..7). The index holds only the original hashes; each sample is queried
204
+ with its 8 variant hashes (`variants[i]` = the 7 non-identity ones). Sorted."""
205
+ index = BandedIndex(hashes, k)
206
+ out = []
207
+ for i, h in enumerate(hashes):
208
+ for t, vh in enumerate((h, *variants[i])):
209
+ for j, d in index.query(vh):
210
+ if j != i:
211
+ out.append((i, j, t, d))
212
+ out.sort()
213
+ return out
214
+
215
+
216
+ def brute_force_dihedral(
217
+ hashes: list[int], variants: list[tuple[int, ...]], k: int
218
+ ) -> list[tuple[int, int, int, int]]:
219
+ """Reference O(n^2 * 8) implementation (tests only)."""
220
+ return sorted(
221
+ (i, j, t, d)
222
+ for i in range(len(hashes))
223
+ for t, vh in enumerate((hashes[i], *variants[i]))
224
+ for j in range(len(hashes))
225
+ if j != i and (d := hamming(vh, hashes[j])) <= k
226
+ )
File without changes
@@ -0,0 +1,29 @@
1
+ """Loader interface."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Protocol
7
+
8
+ from seglint.models import Sample
9
+
10
+
11
+ class DatasetNotFoundError(Exception):
12
+ """The dataset path / layout could not be resolved."""
13
+
14
+
15
+ @dataclass
16
+ class LoadResult:
17
+ samples: list[Sample]
18
+ layout: str # "A" | "B" | "C"
19
+ splits: list[str] = field(default_factory=list)
20
+ classes: dict[int, str] = field(default_factory=dict) # index -> name (COCO categories)
21
+ skipped_junk: int = 0 # hidden/OS junk files that were ignored (._*, .DS_Store, ...)
22
+ # Files that were not used because another file had the same pairing name: per entry
23
+ # {"kind": "mask" | "image", "sample": id, "used": rel. path, "ignored": [rel. paths]}.
24
+ # Reported as a notice only; which file is used does not depend on it.
25
+ duplicates: list[dict] = field(default_factory=list)
26
+
27
+
28
+ class Loader(Protocol):
29
+ def discover(self) -> LoadResult: ...
@@ -0,0 +1,158 @@
1
+ """COCO instance-segmentation loader: annotations are rasterized into class-index masks.
2
+
3
+ Category ids are mapped to contiguous class indices 1..N in ascending category id order (0 is
4
+ the background). Polygons are filled with `cv2.fillPoly`; uncompressed RLE (`counts` a list) is
5
+ decoded here; compressed RLE (`counts` a string) needs `pycocotools` (extra `seglint[coco]`),
6
+ which is imported lazily so the core works without it. Annotations are painted largest area first
7
+ so small objects stay visible on top of big ones. Crowd annotations (`iscrowd=1`) are painted
8
+ first as `ignore_index` (COCO evaluates them as "ignore" regions), so real instances overwrite
9
+ them where they overlap.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ from dataclasses import dataclass
16
+ from pathlib import Path
17
+
18
+ import cv2
19
+ import numpy as np
20
+
21
+ from seglint.loaders.base import DatasetNotFoundError, LoadResult
22
+ from seglint.models import Sample
23
+
24
+ PYCOCOTOOLS_HINT = "compressed RLE segmentations need pycocotools: pip install 'seglint[coco]'"
25
+
26
+
27
+ class CocoError(DatasetNotFoundError):
28
+ """The COCO file is unreadable or uses a feature that is not available."""
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class CocoAnn:
33
+ segmentation: object # polygon list, or RLE dict
34
+ class_index: int
35
+ iscrowd: bool
36
+ area: float
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class CocoRef:
41
+ """Everything needed to build one image's mask (small and picklable for worker processes)."""
42
+
43
+ height: int
44
+ width: int
45
+ anns: tuple[CocoAnn, ...]
46
+
47
+
48
+ def _pycocotools():
49
+ try:
50
+ from pycocotools import mask as mask_utils
51
+ except ImportError as e:
52
+ raise CocoError(PYCOCOTOOLS_HINT) from e
53
+ return mask_utils
54
+
55
+
56
+ def decode_uncompressed_rle(counts: list[int], h: int, w: int) -> np.ndarray:
57
+ """COCO RLE: alternating runs of 0 and 1 over the column-major (Fortran order) mask."""
58
+ flat = np.zeros(h * w, np.uint8)
59
+ pos, val = 0, 0
60
+ for run in counts:
61
+ if val:
62
+ flat[pos : pos + run] = 1
63
+ pos += run
64
+ val ^= 1
65
+ return flat.reshape((w, h)).T # column-major -> rows
66
+
67
+
68
+ def decode_rle(seg: dict, h: int, w: int) -> np.ndarray:
69
+ counts = seg["counts"]
70
+ size = seg.get("size", [h, w])
71
+ if isinstance(counts, list):
72
+ m = decode_uncompressed_rle(counts, int(size[0]), int(size[1]))
73
+ else:
74
+ mu = _pycocotools()
75
+ rle = {"size": list(size), "counts": counts}
76
+ if isinstance(counts, str):
77
+ rle["counts"] = counts.encode("ascii")
78
+ m = mu.decode(rle)
79
+ if m.shape != (h, w):
80
+ raise ValueError(f"RLE size {m.shape[1]}x{m.shape[0]} differs from the image {w}x{h}")
81
+ return m.astype(bool)
82
+
83
+
84
+ def _polygon_mask(polys, h: int, w: int) -> np.ndarray:
85
+ m = np.zeros((h, w), np.uint8)
86
+ for poly in polys:
87
+ pts = np.asarray(poly, np.float64).reshape(-1, 2)
88
+ if len(pts) >= 1:
89
+ cv2.fillPoly(m, [np.round(pts).astype(np.int32)], 1)
90
+ return m.astype(bool)
91
+
92
+
93
+ def rasterize(ref: CocoRef, ignore_index: int = 255) -> np.ndarray:
94
+ """HxW class-index mask (uint8 when the ids fit, else int32)."""
95
+ h, w = ref.height, ref.width
96
+ top = max([a.class_index for a in ref.anns] + [ignore_index, 0])
97
+ mask = np.zeros((h, w), np.uint8 if top < 256 else np.int32)
98
+ order = sorted(ref.anns, key=lambda a: (not a.iscrowd, -a.area)) # crowd first, big first
99
+ for a in order:
100
+ seg = a.segmentation
101
+ m = decode_rle(seg, h, w) if isinstance(seg, dict) else _polygon_mask(seg, h, w)
102
+ mask[m] = ignore_index if a.iscrowd else a.class_index
103
+ return mask
104
+
105
+
106
+ def _ann_area(a: dict) -> float:
107
+ if a.get("area"):
108
+ return float(a["area"])
109
+ seg = a.get("segmentation")
110
+ if isinstance(seg, list) and seg:
111
+ return float(sum(cv2.contourArea(np.asarray(p, np.float32).reshape(-1, 1, 2)) for p in seg))
112
+ return 0.0
113
+
114
+
115
+ def discover_coco(coco_json: Path | None, images_dir: Path | None = None) -> LoadResult:
116
+ """Samples for every image in the COCO file; `LoadResult.classes` maps index -> name."""
117
+ if coco_json is None:
118
+ raise CocoError("no COCO annotation file given: use --coco-json FILE")
119
+ if not coco_json.is_file():
120
+ raise CocoError(f"COCO annotation file not found: {coco_json}")
121
+ try:
122
+ data = json.loads(coco_json.read_text(encoding="utf-8"))
123
+ images, annotations, cats = data["images"], data["annotations"], data["categories"]
124
+ except (OSError, ValueError, KeyError, TypeError) as e:
125
+ raise CocoError(f"cannot read COCO file {coco_json}: {e}") from e
126
+ if images_dir is None:
127
+ sub = coco_json.parent / "images"
128
+ images_dir = sub if sub.is_dir() else coco_json.parent
129
+ if not images_dir.is_dir():
130
+ raise CocoError(f"image directory not found: {images_dir}")
131
+ cat_ids = sorted({int(c["id"]) for c in cats})
132
+ index = {cid: i + 1 for i, cid in enumerate(cat_ids)}
133
+ names = {0: "background", **{index[int(c["id"])]: str(c.get("name", c["id"])) for c in cats}}
134
+ by_image: dict[int, list[CocoAnn]] = {}
135
+ needs_tools = False
136
+ for a in annotations:
137
+ cid = int(a["category_id"])
138
+ if cid not in index:
139
+ raise CocoError(f"annotation {a.get('id')} uses unknown category_id {cid}")
140
+ seg = a.get("segmentation")
141
+ if not seg:
142
+ continue # bbox-only annotation: nothing to rasterize
143
+ if isinstance(seg, dict) and not isinstance(seg.get("counts"), list):
144
+ needs_tools = True
145
+ by_image.setdefault(int(a["image_id"]), []).append(
146
+ CocoAnn(seg, index[cid], bool(a.get("iscrowd", 0)), _ann_area(a))
147
+ )
148
+ if needs_tools:
149
+ _pycocotools() # fail early with a clear message
150
+ samples = []
151
+ for im in sorted(images, key=lambda d: str(d["file_name"])):
152
+ h, w = int(im["height"]), int(im["width"])
153
+ rel = Path(str(im["file_name"]))
154
+ ref = CocoRef(h, w, tuple(by_image.get(int(im["id"]), ())))
155
+ samples.append(Sample(rel.with_suffix("").as_posix(), None, images_dir / rel, None, ref))
156
+ if not samples:
157
+ raise CocoError(f"no images in {coco_json}")
158
+ return LoadResult(samples, "COCO", [], names)
@@ -0,0 +1,274 @@
1
+ """Image/mask-pair loader for file-based datasets (PNG masks, layouts A/B/C)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+
8
+ import numpy as np
9
+ from PIL import Image
10
+
11
+ from seglint.loaders.base import DatasetNotFoundError, LoadResult
12
+ from seglint.models import Sample
13
+
14
+ IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".bmp", ".tif", ".tiff", ".webp"}
15
+ COMMON_MASK_SUFFIXES = ("_mask", "_segmentation", "_gt")
16
+ LOSSY_FORMATS = {"JPEG", "MPO"}
17
+
18
+
19
+ JUNK_FILE_NAMES = {"thumbs.db", "desktop.ini"}
20
+ JUNK_DIR_NAMES = {"__macosx"}
21
+
22
+
23
+ def is_junk_name(name: str, is_dir: bool = False) -> bool:
24
+ """Hidden or OS-generated entries that are never dataset files.
25
+
26
+ Covers macOS AppleDouble files (``._x.png``), ``.DS_Store``, ``__MACOSX`` folders, and the
27
+ Windows ``Thumbs.db`` / ``desktop.ini``.
28
+ """
29
+ low = name.lower()
30
+ if name.startswith("."):
31
+ return True
32
+ return low in JUNK_DIR_NAMES if is_dir else low in JUNK_FILE_NAMES
33
+
34
+
35
+ def _is_junk_path(p: Path, root: Path) -> bool:
36
+ parts = p.relative_to(root).parts
37
+ return any(is_junk_name(d, is_dir=True) for d in parts[:-1]) or is_junk_name(parts[-1])
38
+
39
+
40
+ def _scan(directory: Path) -> tuple[list[Path], int]:
41
+ """(image-like files under directory, number of hidden/junk files skipped)."""
42
+ keep, junk = [], 0
43
+ for p in directory.rglob("*"):
44
+ if not p.is_file():
45
+ continue
46
+ if _is_junk_path(p, directory):
47
+ junk += 1
48
+ elif p.suffix.lower() in IMAGE_EXTS:
49
+ keep.append(p)
50
+ return sorted(keep), junk
51
+
52
+
53
+ def _subdirs(directory: Path) -> list[Path]:
54
+ return sorted(p for p in directory.iterdir() if p.is_dir() and not is_junk_name(p.name, True))
55
+
56
+
57
+ def detect_layout(root: Path) -> str:
58
+ """Return "A" (split/images), "B" (images/split) or "C" (flat images + masks dirs)."""
59
+ for d in _subdirs(root):
60
+ if (d / "images").is_dir() and (d / "masks").is_dir():
61
+ return "A"
62
+ if (root / "images").is_dir() and (root / "masks").is_dir():
63
+ imgs = root / "images"
64
+ has_direct = any(
65
+ p.is_file() and p.suffix.lower() in IMAGE_EXTS and not is_junk_name(p.name)
66
+ for p in imgs.iterdir()
67
+ )
68
+ if not has_direct and _subdirs(imgs) and _subdirs(root / "masks"):
69
+ return "B"
70
+ return "C"
71
+ raise DatasetNotFoundError(
72
+ f"could not detect the dataset layout under {root}: expected the folders images/ and "
73
+ "masks/ (optionally with one subfolder per split inside each), or <split>/images and "
74
+ "<split>/masks; or pass --images DIR --masks DIR"
75
+ )
76
+
77
+
78
+ def _pairs(
79
+ images: list[Path],
80
+ masks: list[Path],
81
+ img_root: Path,
82
+ mask_root: Path,
83
+ split: str | None,
84
+ mask_suffix: str,
85
+ duplicates: list[dict] | None = None,
86
+ ) -> list[Sample]:
87
+ """Pair images and masks by name. When several files share a pairing name, the first in
88
+ sorted order is used and the others are recorded in `duplicates` (a notice, not a finding)."""
89
+ prefix = f"{split}/" if split else ""
90
+ dup_img: dict[str, list[Path]] = {}
91
+ dup_mask: dict[str, list[Path]] = {}
92
+
93
+ def rel_key(p: Path, root: Path) -> str:
94
+ return p.relative_to(root).with_suffix("").as_posix()
95
+
96
+ img_by_key: dict[str, Path] = {}
97
+ for p in images:
98
+ k = rel_key(p, img_root).lower()
99
+ if k in img_by_key:
100
+ dup_img.setdefault(k, []).append(p)
101
+ img_by_key.setdefault(k, p)
102
+ suffixes = ([mask_suffix] if mask_suffix else []) + [
103
+ s for s in COMMON_MASK_SUFFIXES if s != mask_suffix
104
+ ]
105
+
106
+ def strip(key: str) -> str:
107
+ """Map a mask key onto an image key (exact match wins over suffix stripping)."""
108
+ if key in img_by_key:
109
+ return key
110
+ for suf in suffixes:
111
+ if key.endswith(suf.lower()) and key[: -len(suf)] in img_by_key:
112
+ return key[: -len(suf)]
113
+ return key
114
+
115
+ mask_by_key: dict[str, Path] = {}
116
+ mask_orig: dict[str, str] = {}
117
+ for p in masks:
118
+ raw = rel_key(p, mask_root)
119
+ k = strip(raw.lower())
120
+ if k not in mask_by_key:
121
+ mask_by_key[k] = p
122
+ mask_orig[k] = raw
123
+ else:
124
+ dup_mask.setdefault(k, []).append(p)
125
+ samples = []
126
+ for k in sorted(set(img_by_key) | set(mask_by_key)):
127
+ ip = img_by_key.get(k)
128
+ sid = rel_key(ip, img_root) if ip else mask_orig[k]
129
+ samples.append(Sample(f"{prefix}{sid}", split, ip, mask_by_key.get(k)))
130
+ if duplicates is not None:
131
+ for kind, extra, used, root in (("mask", dup_mask, mask_by_key, mask_root),
132
+ ("image", dup_img, img_by_key, img_root)): # fmt: skip
133
+ for k in sorted(extra):
134
+ ip = img_by_key.get(k)
135
+ sid = rel_key(ip, img_root) if ip else mask_orig.get(k, k)
136
+ duplicates.append({
137
+ "kind": kind,
138
+ "sample": f"{prefix}{sid}",
139
+ "used": prefix + used[k].relative_to(root).as_posix(),
140
+ "ignored": [prefix + q.relative_to(root).as_posix() for q in extra[k]],
141
+ }) # fmt: skip
142
+ return samples
143
+
144
+
145
+ def discover(
146
+ path: Path | None,
147
+ layout: str | None = None,
148
+ images: Path | None = None,
149
+ masks: Path | None = None,
150
+ mask_suffix: str = "",
151
+ ) -> LoadResult:
152
+ """Find image/mask pairs. Orphans appear as samples with one path set to None.
153
+
154
+ Hidden/OS junk files (._*, .DS_Store, __MACOSX/, Thumbs.db, desktop.ini) are skipped and
155
+ counted in ``LoadResult.skipped_junk``.
156
+ """
157
+ junk = 0
158
+ dups: list[dict] = []
159
+
160
+ def files(d: Path) -> list[Path]:
161
+ nonlocal junk
162
+ found, n = _scan(d)
163
+ junk += n
164
+ return found
165
+
166
+ layout = layout.upper() if layout else None
167
+ if layout not in (None, "A", "B", "C"):
168
+ raise DatasetNotFoundError(f"unknown layout {layout!r} (expected A, B or C)")
169
+ if images is not None or masks is not None:
170
+ if images is None or masks is None:
171
+ raise DatasetNotFoundError("--images and --masks must be given together")
172
+ for d in (images, masks):
173
+ if not d.is_dir():
174
+ raise DatasetNotFoundError(f"directory not found: {d}")
175
+ s = _pairs(files(images), files(masks), images, masks, None, mask_suffix, dups)
176
+ return LoadResult(s, "C", skipped_junk=junk, duplicates=dups)
177
+ if path is None:
178
+ raise DatasetNotFoundError(
179
+ "no dataset given: seglint check <DATASET>, or --images DIR --masks DIR"
180
+ )
181
+ if not path.is_dir():
182
+ raise DatasetNotFoundError(f"dataset path not found: {path}")
183
+ layout = layout or detect_layout(path)
184
+ samples: list[Sample] = []
185
+ splits: list[str] = []
186
+ if layout == "A":
187
+ for d in _subdirs(path):
188
+ if (d / "images").is_dir() and (d / "masks").is_dir():
189
+ splits.append(d.name)
190
+ samples += _pairs(
191
+ files(d / "images"),
192
+ files(d / "masks"),
193
+ d / "images",
194
+ d / "masks",
195
+ d.name,
196
+ mask_suffix,
197
+ dups,
198
+ )
199
+ elif layout == "B":
200
+ ir, mr = path / "images", path / "masks"
201
+ if not (ir.is_dir() and mr.is_dir()):
202
+ raise DatasetNotFoundError(f"layout B needs {ir} and {mr}")
203
+ names = sorted({d.name for d in _subdirs(ir)} | {d.name for d in _subdirs(mr)})
204
+ for name in names:
205
+ di, dm = ir / name, mr / name
206
+ splits.append(name)
207
+ samples += _pairs(
208
+ files(di) if di.is_dir() else [],
209
+ files(dm) if dm.is_dir() else [],
210
+ di,
211
+ dm,
212
+ name,
213
+ mask_suffix,
214
+ dups,
215
+ )
216
+ else:
217
+ ir, mr = path / "images", path / "masks"
218
+ if not (ir.is_dir() and mr.is_dir()):
219
+ raise DatasetNotFoundError(f"layout C needs {ir} and {mr} (or --images/--masks)")
220
+ samples = _pairs(files(ir), files(mr), ir, mr, None, mask_suffix, dups)
221
+ return LoadResult(samples, layout, splits, skipped_junk=junk, duplicates=dups)
222
+
223
+
224
+ # --- pixel loading -------------------------------------------------------------------------
225
+
226
+
227
+ @dataclass(frozen=True)
228
+ class MaskInfo:
229
+ """Header-level facts about a mask file (cheap; no full decode)."""
230
+
231
+ format: str | None # "PNG", "JPEG", ...
232
+ mode: str # PIL mode: "P", "L", "I;16", "RGB", ...
233
+ size: tuple[int, int] # (width, height)
234
+
235
+
236
+ def inspect_mask(path: Path) -> MaskInfo:
237
+ with Image.open(path) as im:
238
+ return MaskInfo(im.format, im.mode, im.size)
239
+
240
+
241
+ def read_exif_orientation(path: Path) -> int:
242
+ """EXIF orientation tag (1 when absent)."""
243
+ with Image.open(path) as im:
244
+ return int(im.getexif().get(0x0112, 1))
245
+
246
+
247
+ def load_image(path: Path) -> np.ndarray:
248
+ """Image as HxWx3 uint8 RGB, in raw (non-EXIF-transposed) orientation."""
249
+ with Image.open(path) as im:
250
+ return np.asarray(im.convert("RGB"))
251
+
252
+
253
+ def load_mask(
254
+ path: Path,
255
+ binary: bool = False,
256
+ palette: dict[tuple[int, int, int], int] | None = None,
257
+ ignore_index: int = 255,
258
+ ) -> np.ndarray:
259
+ """Mask as HxW integer class ids; RGB masks are mapped via `palette` when given.
260
+
261
+ Without a palette, RGB/multichannel masks are returned as HxWxC (checks flag S006).
262
+ Unmapped palette colors become `ignore_index`.
263
+ """
264
+ with Image.open(path) as im:
265
+ if im.mode in ("RGB", "RGBA") and palette:
266
+ rgb = np.asarray(im.convert("RGB"))
267
+ out = np.full(rgb.shape[:2], ignore_index, dtype=np.int32)
268
+ for color, cls in palette.items():
269
+ out[np.all(rgb == np.array(color, dtype=rgb.dtype), axis=-1)] = cls
270
+ return out
271
+ arr = np.array(im) # P -> index values; L / I;16 -> values
272
+ if binary and arr.ndim == 2:
273
+ arr = (arr == 255).astype(np.uint8)
274
+ return arr