ksdd2 / ksdd2.py
OliverOnHF's picture
Upload ksdd2.py
7c9838c verified
# ksdd2.py — KSDD2 loader (manual-download)
# Configs:
# - image_only
# - classification_from_masks (recommended)
# - classification_from_pyb (auto-fallback to masks if all-positive)
# - classification_from_pyb_any (union, K=1)
from pathlib import Path
from typing import Dict, Iterable, Tuple, Optional, Set, List
import os
import re
import collections
import datasets
try:
import pickletools # safe scan
except Exception:
pickletools = None
try:
import pickle # fallback
except Exception:
pickle = None
IMG_EXTS = {".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff"}
MASK_DIR_CANDS = ["masks", "masks_defect", "ground_truth", "gt", "label", "labels"]
_DESCRIPTION = "KSDD2: Kolektor Surface-Defect Dataset 2. Binary classification via GT masks or weak splits."
_HOMEPAGE = "https://www.vicos.si/resources/kolektorsdd2/"
_CITATION = "KSDD2 by ViCoS Lab / Kolektor Group. See official page for citation."
def _is_gt_file(p: Path) -> bool:
s = p.stem.lower()
return s.endswith("_gt") or s.endswith("_mask")
def _to_num(s: str) -> Optional[int]:
return int(s) if s.isdigit() else None
def _extract_numbers(stem: str):
for m in re.finditer(r"\d+", stem):
yield int(m.group(0))
class KSDD2Config(datasets.BuilderConfig):
def __init__(self, mode="masks", min_votes: Optional[int]=None, **kw):
super().__init__(version=datasets.Version("2.0.0"), **kw)
self.mode = mode
self.min_votes = min_votes # used for pyb/pyb_any
class KSDD2(datasets.GeneratorBasedBuilder):
BUILDER_CONFIG_CLASS = KSDD2Config
BUILDER_CONFIGS = [
KSDD2Config(name="image_only", description="Flat train/test, images only", mode="image_only"),
KSDD2Config(name="classification_from_masks",
description="Label via *_GT.* masks (non-black=>defect). Excludes *_GT.* from inputs.",
mode="masks"),
KSDD2Config(name="classification_from_pyb",
description="Weak splits via split_weakly_*.pyb (vote; fallback to masks on all-positive).",
mode="pyb", min_votes=2),
KSDD2Config(name="classification_from_pyb_any",
description="Weak splits union (K=1).", mode="pyb_any", min_votes=1),
]
DEFAULT_CONFIG_NAME = "classification_from_masks"
# ---------- info ----------
def _info(self):
if self.config.mode == "image_only":
feats = {"image": datasets.Image(), "path": datasets.Value("string")}
else:
feats = {
"image": datasets.Image(),
"label": datasets.ClassLabel(names=["good", "defect"]),
"path": datasets.Value("string"),
}
return datasets.DatasetInfo(description=_DESCRIPTION,
features=datasets.Features(feats),
citation=_CITATION,
homepage=_HOMEPAGE)
# ---------- splits ----------
def _split_generators(self, dl_manager):
root = Path(self.config.data_dir or "")
if not root.exists():
raise FileNotFoundError(f"Please download KSDD2 and set data_dir. Looked for: {root}")
gens = []
for sp in ("train", "test"):
if (root/sp).exists():
gens.append(datasets.SplitGenerator(
name=getattr(datasets.Split, sp.upper()),
gen_kwargs={"root": root, "split": sp}))
if not gens:
gens.append(datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"root": root, "split": None}))
return gens
# ---------- helpers ----------
def _iter_images(self, base: Path):
for p in sorted(base.rglob("*")):
if p.is_file() and p.suffix.lower() in IMG_EXTS:
if _is_gt_file(p):
continue
yield p
def _find_mask_for(self, img_path: Path) -> Optional[Path]:
for ext in IMG_EXTS:
cand = img_path.with_name(img_path.stem + "_GT" + ext)
if cand.exists():
return cand
parent = img_path.parent
for d in MASK_DIR_CANDS:
mdir = parent / d
if mdir.exists():
for ext in IMG_EXTS:
cand = mdir / (img_path.stem + "_GT" + ext)
if cand.exists():
return cand
return None
def _mask_is_defect(self, mask_path: Optional[Path]) -> int:
if not mask_path or not mask_path.exists():
return 0
try:
from PIL import Image
with Image.open(mask_path) as im:
im = im.convert("L")
ex = im.getextrema()
if not ex:
return 0
lo, hi = ex
return 1 if hi > 0 else 0
except Exception:
return 0
# ---- PYB parsing (list of IDs) ----
def _pyb_vote_defects(self, base: Path, min_votes: int, only_files: Optional[List[str]] = None) -> Set[str]:
root = base.parent
pybs = sorted(root.glob("split_weakly_*.pyb"))
if only_files:
allow = {x.lower().strip() for x in only_files}
pybs = [p for p in pybs if p.name.lower() in allow]
names_present: Set[str] = set()
num_map: Dict[int, Set[str]] = {}
for img in self._iter_images(base):
bn = img.name.lower()
names_present.add(bn)
n = _to_num(img.stem)
if n is not None and n >= 1000:
num_map.setdefault(n, set()).add(bn)
votes = collections.Counter()
for f in pybs:
data = f.read_bytes()
ids: Set[int] = set()
used_pickletools = False
if pickletools is not None:
try:
tmp: List[int] = []
cur = []
for op, arg, pos in pickletools.genops(data):
if op.name in ("BININT", "BININT1", "BININT2", "LONG1", "LONG4"):
try:
x = int(arg)
if x >= 1000:
tmp.append(x)
except Exception:
pass
elif op.name in ("EMPTY_LIST", "APPENDS", "LIST"):
pass
used_pickletools = True
except Exception:
used_pickletools = False
if not used_pickletools and pickle is not None:
try:
obj = pickle.loads(data) # [ [(id, True), ...], [(id, True), ...] ]
for part in obj:
for pair in part:
if isinstance(pair, (list, tuple)) and pair:
n = int(pair[0])
if n >= 1000:
ids.add(n)
except Exception:
pass
hit = set()
for n in ids:
hit.update(num_map.get(n, []))
for bn in hit:
votes[bn] += 1
return {bn for bn, v in votes.items() if v >= max(1, min_votes)}
# ---------- generator ----------
def _generate_examples(self, root: Path, split: Optional[str]):
base = root / split if split else root
# A) images only
if self.config.mode == "image_only":
for p in self._iter_images(base):
yield str(p), {"image": str(p), "path": str(p)}
return
# B) classification from masks
if self.config.mode == "masks":
for img in self._iter_images(base):
mask = self._find_mask_for(img)
label = self._mask_is_defect(mask)
yield str(img), {"image": str(img), "label": label, "path": str(img)}
return
# C1) from pyb
if self.config.mode in ("pyb", "pyb_any"):
min_votes = self.config.min_votes or (2 if self.config.mode == "pyb" else 1)
try:
min_votes = int(os.getenv("KSDD2_MIN_VOTES", min_votes))
except Exception:
pass
only = os.getenv("KSDD2_PYB_FILES", "")
only_files = [s for s in only.split(",") if s.strip()] if only else None
defect_names = self._pyb_vote_defects(base, min_votes=min_votes, only_files=only_files)
total = good = defect = 0
cache = []
for img in self._iter_images(base):
bn = img.name.lower()
y = 1 if bn in defect_names else 0
cache.append((img, y))
total += 1; defect += y; good += (1 - y)
if total > 0 and defect / total > 0.95:
for img, _ in cache:
mask = self._find_mask_for(img)
y = self._mask_is_defect(mask)
yield str(img), {"image": str(img), "label": y, "path": str(img)}
else:
for img, y in cache:
yield str(img), {"image": str(img), "label": y, "path": str(img)}
return