#!/usr/bin/env python3 """Class-wise, background-free domain-gap analysis for IASSET. Every YOLO bounding box becomes one sample (the pixels under the box only). Metrics are computed per class (real crops of class c vs. synthetic crops of class c), pooled over all classes ("ALL"), and macro-averaged over classes ("MEAN_OVER_CLASSES"). Class ids are mapped to canonical names taken from the real test set, so datasets with a different class order are handled by name. This file reuses encoders, metrics and reduction code from iasset_embeddings_analysis.py (keep both files in the same folder). Stages index : parse labels, map classes, write index.csv + class_stats.csv (run this first and check it) features : hashes + DINOv2 + Inception embeddings of the crops metrics : per-class similarity metrics (metrics_long.csv) reduce : offline PCA / t-SNE / UMAP projections verify : class-mapping sanity check (needs dinov2 features; not part of "all") all : features + metrics + reduce Example python iasset_embeddings_classwise.py index --root /media/rtx5090/IASSET python iasset_embeddings_classwise.py all --root /media/rtx5090/IASSET """ import argparse import json import os import re from concurrent.futures import ProcessPoolExecutor from pathlib import Path import numpy as np import pandas as pd import torch from PIL import Image from torch.utils.data import DataLoader, Dataset from tqdm import tqdm from iasset_embeddings_analysis import (HASH_SIZES, SKIP_DATASETS, THUMB, _compare, list_images, load_dinov2, load_inception, reduce_features, sample_ids) DEFAULT_OUT = "/media/rtx5090/IASSET/Scripts/embeddings_results_classwise" FILL = (124, 116, 104) # ImageNet mean colour, used for letterbox padding _norm = lambda s: re.sub(r"[^a-z0-9]", "", str(s).lower()) # --------------------------------------------------------------------------- crops def get_crop(img, box, pad=0.0, mode="letterbox"): """Pixels under a (x1, y1, x2, y2) box. letterbox: pad to a square with FILL; squash: raw crop.""" x1, y1, x2, y2 = box dx, dy = pad * (x2 - x1), pad * (y2 - y1) W, H = img.size l, t = max(0, int(np.floor(x1 - dx))), max(0, int(np.floor(y1 - dy))) r, b = min(W, int(np.ceil(x2 + dx))), min(H, int(np.ceil(y2 + dy))) c = img.crop((l, t, max(r, l + 1), max(b, t + 1))) if mode == "letterbox": s = max(c.size) canvas = Image.new("RGB", (s, s), FILL) canvas.paste(c, ((s - c.width) // 2, (s - c.height) // 2)) return canvas return c # --------------------------------------------------------------------------- labels and classes def _walk(root, max_depth=3, skip=("images", "depth", "rgb")): root = Path(root) base = len(root.parts) for dp, dn, fn in os.walk(root): depth = len(Path(dp).parts) - base dn[:] = sorted(d for d in dn if d.lower() not in skip) if depth < max_depth else [] for f in sorted(fn): yield Path(dp) / f def read_names(root): """Class names (list, index = id) from a YOLO yaml with 'names' or from classes.txt.""" import yaml files = list(_walk(root)) yamls = sorted((f for f in files if f.suffix.lower() in (".yaml", ".yml")), key=lambda f: f.name.lower() not in ("dataset.yaml", "data.yaml")) # these first for f in yamls: try: d = yaml.safe_load(f.read_text()) except Exception: continue if isinstance(d, dict) and "names" in d: n = d["names"] if isinstance(n, dict): n = [n[k] for k in sorted(n, key=int)] return [str(x) for x in n], f for f in files: if f.name.lower() in ("classes.txt", "names.txt", "obj.names"): return [l.strip() for l in f.read_text().splitlines() if l.strip()], f return None, None def build_map(names, canon, override=None): """source class id -> canonical class id (matched by normalized name).""" cn = {_norm(n): i for i, n in enumerate(canon)} if override: return {int(k): cn[_norm(v)] for k, v in override.items()} if names is None: return {i: i for i in range(len(canon))} return {sid: cn[_norm(n)] for sid, n in enumerate(names) if _norm(n) in cn} def parse_label(p): """YOLO txt -> [(class, x1, y1, x2, y2)] normalized. Handles boxes and polygons.""" out = [] for line in Path(p).read_text().splitlines(): t = line.split() if len(t) < 5: continue try: cid, v = int(float(t[0])), [float(x) for x in t[1:]] except ValueError: continue if len(v) == 4: cx, cy, w, h = v out.append((cid, cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2)) else: xs, ys = v[0::2], v[1::2] out.append((cid, min(xs), min(ys), max(xs), max(ys))) return out class LabelFinder: """Find the YOLO label file of an image: images->labels swap, sibling folders, then unique-stem lookup.""" def __init__(self, ds_root): self.root, self.stems = Path(ds_root), None def __call__(self, img): parts = list(img.relative_to(self.root).with_suffix(".txt").parts) for i in range(len(parts) - 2, -1, -1): if parts[i].lower() == "images": c = self.root.joinpath(*(parts[:i] + ["labels"] + parts[i + 1:])) if c.exists(): return c for c in (img.with_suffix(".txt"), img.parent.parent / "labels" / (img.stem + ".txt"), img.parent.parent / "labels" / img.parent.name / (img.stem + ".txt")): if c.exists(): return c if self.stems is None: seen, self.stems = {}, {} for f in _walk(self.root, max_depth=5): if f.suffix == ".txt" and f.name.lower() not in ("classes.txt", "names.txt"): seen[f.stem] = None if f.stem in seen else f self.stems = {k: v for k, v in seen.items() if v is not None} return self.stems.get(img.stem) def build_crop_index(a): root = Path(a.root) real_root = root / "Real_Test_Set" sets = [("REAL", "Real", "real", real_root / "images" / "full" / "rgb", real_root)] synth = root / "Synthetic_Train_Sets" for g in sorted(p for p in synth.iterdir() if p.is_dir() and p.name not in a.skip_groups): for d in sorted(p for p in g.iterdir() if p.is_dir() and p.name not in SKIP_DATASETS): sets.append((f"{g.name}/{d.name}", g.name, "synthetic", d, d)) canon, src = read_names(real_root) if canon is None: raise SystemExit(f"No class names found under {real_root} (dataset.yaml 'names' or classes.txt).") print(f"Canonical classes from {src}: {dict(enumerate(canon))}") override = json.load(open(a.class_map)) if a.class_map else {} rng = np.random.default_rng(a.seed) cols = ["dataset", "group", "domain", "path", "class_id", "class_name", "src_class_id", "x1", "y1", "x2", "y2", "img_w", "img_h"] frames = [] for name, group, domain, img_dir, ds_root in sets: files = list_images(img_dir) if a.max_images_per_set and len(files) > a.max_images_per_set: files = [files[i] for i in sorted(rng.choice(len(files), a.max_images_per_set, replace=False))] names, nsrc = (canon, src) if domain == "real" else read_names(ds_root) if names is None and name not in override: print(f"[warn] {name}: no class names file, assuming the real-set class order") cmap = build_map(names, canon, override.get(name)) if names is not None and [_norm(n) for n in names] != [_norm(n) for n in canon]: print(f"[info] {name}: class list differs from the real set; remapped by name " f"({len(cmap)}/{len(names)} matched)") find, rows, n_lab, unmatched = LabelFinder(ds_root), [], 0, set() for f in tqdm(files, desc=name[:60], leave=False): lp = find(f) boxes = parse_label(lp) if lp else [] if not boxes: continue n_lab += 1 with Image.open(f) as im: W, H = im.size for cid, x1, y1, x2, y2 in boxes: if cid not in cmap: unmatched.add(cid) continue px = [max(0.0, x1 * W), max(0.0, y1 * H), min(float(W), x2 * W), min(float(H), y2 * H)] if min(px[2] - px[0], px[3] - px[1]) < a.min_box_px: continue rows.append((name, group, domain, str(f), cmap[cid], canon[cmap[cid]], cid, *px, W, H)) df = pd.DataFrame(rows, columns=cols) if a.max_per_class and len(df): keep = [] for _, g in df.groupby("class_id"): ii = g.index.values keep += list(rng.choice(ii, a.max_per_class, replace=False) if len(ii) > a.max_per_class else ii) df = df.loc[sorted(keep)] print(f"{name:75s} images {len(files):6d} | labelled {n_lab:6d} | crops {len(df):6d}" + (f" | unmatched src class ids {sorted(unmatched)}" if unmatched else "")) frames.append(df) idx = pd.concat(frames, ignore_index=True) idx.insert(0, "crop_id", np.arange(len(idx))) return idx def get_index(a): out = Path(a.out) out.mkdir(parents=True, exist_ok=True) f = out / "index.csv" if f.exists() and not a.overwrite: return pd.read_csv(f) idx = build_crop_index(a) idx.to_csv(f, index=False) stats = idx.groupby(["dataset", "class_name"]).size().unstack(fill_value=0) stats.to_csv(out / "class_stats.csv") with pd.option_context("display.width", 250, "display.max_columns", 50, "display.max_rows", 200): print("\nCrops per dataset and class:\n", stats) return idx # --------------------------------------------------------------------------- hashes (raw crops) def _hash_img(img): import imagehash img.thumbnail((THUMB, THUMB), Image.LANCZOS) fn = {"ahash": imagehash.average_hash, "phash": imagehash.phash, "dhash": imagehash.dhash, "whash": imagehash.whash} out = {} for t, sizes in HASH_SIZES.items(): for s in sizes: h = imagehash.colorhash(img, binbits=s) if t == "colorhash" else fn[t](img, hash_size=s) out[f"hash_{t}_{s}"] = h.hash.flatten().astype(np.uint8) return out def _hash_group(task): path, boxes, pad = task with Image.open(path) as im: img = im.convert("RGB") return [_hash_img(get_crop(img, b, pad, "squash")) for b in boxes] def run_hashes(idx, fd, a): groups = list(idx.groupby("path", sort=False)) tasks = [(p, g[["x1", "y1", "x2", "y2"]].values.tolist(), a.pad) for p, g in groups] order = np.concatenate([g.index.values for _, g in groups]) with ProcessPoolExecutor(a.workers) as ex: res = [r for rs in tqdm(ex.map(_hash_group, tasks, chunksize=8), total=len(tasks), desc="hashes") for r in rs] inv = np.argsort(order) hex_cols = {} for key in res[0]: arr = np.stack([r[key] for r in res])[inv] # back to index order np.save(fd / f"{key}.npy", arr) hex_cols[key] = [np.packbits(r).tobytes().hex() for r in arr] df = pd.DataFrame(hex_cols) df.insert(0, "crop_id", idx.crop_id.values) df.to_csv(fd.parent / "hashes.csv", index=False) # --------------------------------------------------------------------------- deep features (crops) class CropDataset(Dataset): def __init__(self, idx, tf, pad, mode): self.p = idx.path.values self.b = idx[["x1", "y1", "x2", "y2"]].values self.tf, self.pad, self.mode = tf, pad, mode self._p, self._img = None, None # per-worker cache: consecutive crops share one image def __len__(self): return len(self.p) def __getitem__(self, i): if self.p[i] != self._p: with Image.open(self.p[i]) as im: self._img = im.convert("RGB") self._p = self.p[i] return self.tf(get_crop(self._img, self.b[i], self.pad, self.mode)) def extract_crops(idx, fwd, tf, a): dl = DataLoader(CropDataset(idx, tf, a.pad, a.crop_mode), batch_size=a.batch_size, num_workers=a.workers, pin_memory=a.device.startswith("cuda"), persistent_workers=a.workers > 0) acc = {} with torch.no_grad(), torch.autocast("cuda", dtype=torch.float16, enabled=(a.fp16 and a.device.startswith("cuda"))): for x in tqdm(dl, desc="encode crops"): for k, v in fwd(x.to(a.device, non_blocking=True)).items(): acc.setdefault(k, []).append(v.float().cpu()) return {k: torch.cat(v).numpy() for k, v in acc.items()} def stage_features(a): idx = get_index(a) fd = Path(a.out) / "features" fd.mkdir(exist_ok=True) if "hash" in a.encoders: keys = [f"hash_{t}_{s}" for t, ss in HASH_SIZES.items() for s in ss] if a.overwrite or not all((fd / f"{k}.npy").exists() for k in keys): run_hashes(idx, fd, a) jobs = [] if "dinov2" in a.encoders: for size in a.dinov2_sizes: jobs.append(([f"dinov2_{size}_cls", f"dinov2_{size}_patchmean"], lambda s=size: load_dinov2(s, a))) if "inception" in a.encoders: jobs.append((["inception_pool3"], lambda: load_inception(a))) for names, loader in jobs: if not a.overwrite and all((fd / f"{n}.npy").exists() for n in names): continue fwd, tf = loader() for k, arr in extract_crops(idx, fwd, tf, a).items(): np.save(fd / f"{k}.npy", arr) if a.csv_deep: df = pd.DataFrame(arr, columns=[f"d{i}" for i in range(arr.shape[1])]) df.insert(0, "crop_id", idx.crop_id.values) df.to_csv(fd / f"{k}.csv", index=False) # --------------------------------------------------------------------------- metrics def stage_metrics(a): out = Path(a.out) idx = pd.read_csv(out / "index.csv") rng = np.random.default_rng(a.seed) pairs, skipped = [], 0 for cls in ["ALL"] + sorted(idx.class_name.unique()): sel = idx if cls == "ALL" else idx[idx.class_name == cls] real = sel.index[sel.domain == "real"].to_numpy() half = rng.permutation(real) cands = [("REAL_vs_REAL_split", "Baseline", half[: len(half) // 2], half[len(half) // 2:])] cands += [(n, g_, real, d.index.to_numpy()) for (n, g_), d in sel[sel.domain == "synthetic"].groupby(["dataset", "group"])] for n, g_, xi, yi in cands: if min(len(xi), len(yi)) >= a.min_crops: pairs.append((cls, n, g_, xi, yi)) else: skipped += 1 print(f"{len(pairs)} comparisons ({skipped} skipped: fewer than {a.min_crops} crops on one side)") rows = [] for f in sorted((out / "features").glob("*.npy")): if a.only and not any(o in f.stem for o in a.only): continue kind = "hash" if f.stem.startswith("hash_") else "deep" F = torch.tensor(np.load(f), dtype=torch.float32, device=a.device) for cls, name, group, xi, yi in tqdm(pairs, desc=f.stem): for metric, (mu, sd) in _compare(F, kind, xi, yi, a, rng).items(): if metric == "fd" and min(len(xi), len(yi)) < a.fd_min_n: continue # covariance estimate dominated by sample size rows.append((f.stem, cls, name, group, len(xi), len(yi), metric, mu, sd, "subsample")) cols = ["feature", "class_name", "dataset", "group", "n_ref", "n_cand", "metric", "mean", "std", "std_kind"] df = pd.DataFrame(rows, columns=cols) cl = df[df.class_name != "ALL"] macro = (cl.groupby(["feature", "dataset", "group", "metric"]) .agg(n_ref=("n_ref", "sum"), n_cand=("n_cand", "sum"), std=("mean", "std"), mean=("mean", "mean")) .reset_index()) macro["class_name"], macro["std_kind"] = "MEAN_OVER_CLASSES", "across_classes" pd.concat([df, macro[cols]], ignore_index=True).to_csv(out / "metrics_long.csv", index=False) # --------------------------------------------------------------------------- reduction def stage_reduce(a): out = Path(a.out) rd = out / "reductions" rd.mkdir(exist_ok=True) idx = pd.read_csv(out / "index.csv") ids = sample_ids(idx, idx.dataset.unique(), a.reduce_per_set, a.seed) for f in sorted((out / "features").glob("*.npy")): if a.only and not any(o in f.stem for o in a.only): continue kind = "hash" if f.stem.startswith("hash_") else "deep" X = np.load(f, mmap_mode="r")[ids] for method in a.methods: for nc in a.dims: Z = reduce_features(X, kind, method, nc, a.pre_dims, seed=a.seed) df = pd.DataFrame(Z, columns=[f"c{i + 1}" for i in range(nc)]) df.insert(0, "crop_id", ids) df.to_csv(rd / f"{f.stem}__{method}_{nc}d.csv", index=False) print("saved", f.stem, method, nc) # --------------------------------------------------------------------------- class-mapping check def _centroids(X, sel, min_n=5): out = {} for c, g in sel.groupby("class_name"): if len(g) >= min_n: m = X[g.index.values].mean(0) out[c] = m / np.linalg.norm(m) return out def stage_verify(a): """Sanity check of the class mapping with DINOv2 CLS centroids: a synthetic class should be nearest to the real class of the same name. Perfect agreement is not expected (similar parts, e.g. O-ring sizes), so read every dataset against the REAL_split row (real half B vs. real half A).""" out = Path(a.out) idx = pd.read_csv(out / "index.csv") fs = sorted((out / "features").glob("dinov2_*_cls.npy")) if not fs: raise SystemExit("Run the features stage with the dinov2 encoder first.") X = np.load(fs[0]) X = X / np.linalg.norm(X, axis=1, keepdims=True) rng = np.random.default_rng(a.seed) real = idx[idx.domain == "real"] perm = rng.permutation(real.index.values) ha, hb = perm[: len(perm) // 2], perm[len(perm) // 2:] jobs = [("REAL_split", idx.loc[hb], _centroids(X, idx.loc[ha]))] R = _centroids(X, real) jobs += [(n, g, R) for n, g in idx[idx.domain == "synthetic"].groupby("dataset")] rows = [] for name, sel, ref in jobs: keys = list(ref) RM = np.stack([ref[k] for k in keys]) for c, cen in _centroids(X, sel).items(): if c not in ref: continue s = RM @ cen best = keys[int(s.argmax())] rows.append((name, c, best, best == c, float(s[keys.index(c)]), float(s.max()))) df = pd.DataFrame(rows, columns=["dataset", "class_name", "nearest_real_class", "match", "cos_same", "cos_best"]) df.to_csv(out / "class_mapping_check.csv", index=False) with pd.option_context("display.width", 250, "display.max_rows", 200): print("Top-1 centroid agreement per dataset (lowest first):") print(df.groupby("dataset").match.agg(["mean", "size"]).rename(columns={"mean": "agreement", "size": "n_classes"}) .sort_values("agreement").to_string()) print(f"Details: {out / 'class_mapping_check.csv'}") # --------------------------------------------------------------------------- CLI def main(): p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument("stage", choices=["index", "features", "metrics", "reduce", "verify", "all"]) p.add_argument("--root", default="/media/rtx5090/IASSET") p.add_argument("--out", default=DEFAULT_OUT) p.add_argument("--seed", type=int, default=0) p.add_argument("--overwrite", action="store_true") p.add_argument("--only", nargs="*", help="restrict metrics/reduce to features containing these substrings") g = p.add_argument_group("crops") g.add_argument("--min-box-px", type=float, default=16, help="drop boxes whose shorter side is below this") g.add_argument("--pad", type=float, default=0.0, help="box margin as a fraction of box size (0 = strictly inside)") g.add_argument("--crop-mode", choices=["letterbox", "squash"], default="letterbox", help="deep encoders: pad crop to a square (letterbox) or resize directly (squash)") g.add_argument("--max-per-class", type=int, default=1000, help="cap crops per (dataset, class); 0 = all. Subsample metrics use at most min(n_real, " "n_synthetic, --subset-size) crops, so large synthetic classes add cost, not information") g.add_argument("--max-images-per-set", type=int, default=0, help="randomly keep at most this many images per dataset (0 = all); for quick test runs") g.add_argument("--skip-groups", nargs="*", default=["Training_Set_Size_Ablation"], help="folders under Synthetic_Train_Sets to ignore") g.add_argument("--class-map", help='JSON {"dataset": {"src_id": "canonical class name"}} overriding name matching') g = p.add_argument_group("features") g.add_argument("--encoders", nargs="+", default=["hash", "dinov2", "inception"]) g.add_argument("--dinov2-sizes", nargs="+", default=["base"], choices=["small", "base", "large", "giant"]) g.add_argument("--batch-size", type=int, default=128) g.add_argument("--workers", type=int, default=8) g.add_argument("--device", default="cuda") g.add_argument("--fp16", action="store_true") g.add_argument("--csv-deep", action="store_true", help="also write deep features as CSV (large)") g = p.add_argument_group("metrics") g.add_argument("--subset-size", type=int, default=1000) g.add_argument("--repeats", type=int, default=10) g.add_argument("--k", type=int, default=5) g.add_argument("--min-crops", type=int, default=20, help="skip comparisons with fewer crops on either side") g.add_argument("--fd-min-n", type=int, default=100, help="report FD only if both sides have at least this many crops") g = p.add_argument_group("reduce") g.add_argument("--methods", nargs="+", default=["pca", "tsne", "umap"]) g.add_argument("--dims", nargs="+", type=int, default=[2, 3]) g.add_argument("--pre-dims", type=int, default=50) g.add_argument("--reduce-per-set", type=int, default=500) a = p.parse_args() a.crop = "none" # crops are already square (letterbox) or deliberately squashed: no centre-crop if a.stage == "index": get_index(a) if a.stage == "verify": stage_verify(a) if a.stage in ("features", "all"): stage_features(a) if a.stage in ("metrics", "all"): stage_metrics(a) if a.stage in ("reduce", "all"): stage_reduce(a) if __name__ == "__main__": main()