"""Score a model's predictions on a manga-layout split. python score.py [--text T] [--onomatopoeia T] Predictions are COCO results: a list of {"image_id", "category_id", "bbox": [x, y, w, h], "score", "segmentation": RLE (optional)}, with the split file's image ids. --text and --onomatopoeia are the model's own published thresholds for its kept lettering (0.25 and 0.4 if not given); never tune them on a test split. Reports, on the kept text and onomatopoeia: - page accuracy (PA): the share of pages with no story text or onomatopoeia missed and no false positive; - text recall and SFX recall: the share of labels (dialogue, narration, aside or title text; onomatopoeia) at least half covered by kept boxes of either lettering class, since both are removed for inpainting; - false positives per image (FPPI): kept boxes with under a tenth of their area on the page's lettering labels and ignore regions, summed; - on onomatopoeia with a reviewed mask: the full-coverage rate (FCR), the share at least 99% covered by the kept masks after growing them by `grow`; residual ink (RI), the share of their ink left uncovered; and the excess mask ratio (EMR), the grown masks' area outside the page's grown lettering over that grown lettering's area. Then COCO AP per class, boxes and masks; labels without a mask are ignore regions for mask AP. Pages listed in danbooru/unavailable.json are left out. """ import argparse import json from collections import defaultdict from pathlib import Path import cv2 import numpy as np from pycocotools import mask as rle from pycocotools.coco import COCO from pycocotools.cocoeval import COCOeval ROOT = Path(__file__).resolve().parent STORY = {"dialogue", "narration", "aside", "title"} LETTERING = (1, 2) REVIEWED = {"gold_reviewed", "gold_zenodo_refined"} FOUND, ON_ART, CLEAN = 0.5, 0.1, 0.99 def grow(width: int, height: int) -> int: """Koharu's mask growth: 2 px per 1024 px of the long side, at least 1, plus 3.""" return min(max(round(max(width, height) / 1024 * 2), 1), 127) + 3 def dilate(mask: np.ndarray, by: int) -> np.ndarray: return cv2.dilate(mask.astype(np.uint8), np.ones((2 * by + 1, 2 * by + 1), np.uint8)).astype(bool) def decode(segmentation: dict) -> np.ndarray: counts = segmentation["counts"] return rle.decode({"size": segmentation["size"], "counts": counts.encode() if isinstance(counts, str) else counts}).astype(bool) def overlap(a: list[float], b: list[float]) -> float: """Intersection area of two [x, y, w, h] boxes.""" return max(0.0, min(a[0] + a[2], b[0] + b[2]) - max(a[0], b[0])) * max(0.0, min(a[1] + a[3], b[1] + b[3]) - max(a[1], b[1])) def box_mask(bbox: list[float], height: int, width: int) -> np.ndarray: m = np.zeros((height, width), bool) x, y, w, h = bbox m[int(y) : int(np.ceil(y + h)), int(x) : int(np.ceil(x + w))] = True return m def main(subset: str, split: str, predictions: str, text: float, onomatopoeia: float) -> None: coco = json.loads((ROOT / subset / f"{split}.coco.json").read_text(encoding="utf-8")) unavailable = set() if subset == "danbooru" and (ROOT / "danbooru" / "unavailable.json").exists(): listed = json.loads((ROOT / "danbooru" / "unavailable.json").read_text(encoding="utf-8")) unavailable = {i["id"] for i in coco["images"] if i["danbooru_id"] in set(listed["missing"]) | set(listed["changed"])} images = {i["id"]: i for i in coco["images"] if i["id"] not in unavailable} labels, found = defaultdict(list), defaultdict(list) for a in coco["annotations"]: if a["image_id"] in images: labels[a["image_id"]].append(a) preds = json.loads(Path(predictions).read_text(encoding="utf-8")) for p in preds: if p["image_id"] in images: found[p["image_id"]].append(p) thresholds = {1: text, 2: onomatopoeia} totals = {"story": [0, 0], "onomatopoeia": [0, 0]} on_art = perfect = 0 rows, ideal, spill = [], 0, 0 for image_id, image in images.items(): kept = [p for p in found[image_id] if p["category_id"] in LETTERING and p["score"] >= thresholds[p["category_id"]]] lettering = [a for a in labels[image_id] if a["category_id"] in LETTERING] missed = 0 for a in lettering: if a["iscrowd"]: continue key = "onomatopoeia" if a["category_id"] == 2 else "story" if a["attributes"].get("role") in STORY else None if key is None: continue hit = sum(overlap(a["bbox"], p["bbox"]) for p in kept) >= FOUND * a["bbox"][2] * a["bbox"][3] totals[key][0] += hit totals[key][1] += 1 missed += not hit art = sum(sum(overlap(a["bbox"], p["bbox"]) for a in lettering) < ON_ART * p["bbox"][2] * p["bbox"][3] for p in kept) on_art += art perfect += missed == 0 and art == 0 reviewed = [a for a in lettering if a["category_id"] == 2 and not a["iscrowd"] and a["attributes"].get("quality_tier") in REVIEWED and a["attributes"].get("has_mask")] if not reviewed: continue height, width = image["height"], image["width"] by = grow(width, height) predicted = np.zeros((height, width), bool) for p in kept: predicted |= decode(p["segmentation"]) if "segmentation" in p else box_mask(p["bbox"], height, width) predicted = dilate(predicted, by) labelled = np.zeros((height, width), bool) for a in lettering: labelled |= decode(a["segmentation"]) if a["attributes"].get("has_mask") and not a["iscrowd"] else box_mask(a["bbox"], height, width) grown = dilate(labelled, by) ideal += int(grown.sum()) spill += int((predicted & ~grown).sum()) for a in reviewed: m = decode(a["segmentation"]) rows.append((int(m.sum()), int((m & predicted).sum()))) n = len(images) print(f"manga-layout {subset}/{split}: {n} pages, thresholds text {text}, onomatopoeia {onomatopoeia}") print(f" page accuracy (PA) {perfect / n:.3f}") for key, name in (("story", "text recall"), ("onomatopoeia", "SFX recall")): hit, total = totals[key] if total: print(f" {name:34s} {hit / total:.3f} ({hit} of {total})") print(f" false positives per image (FPPI) {on_art / n:.3f}") if rows: r = np.array(rows, dtype=np.float64) print(f" SFX masks ({len(r)} reviewed): full-coverage rate (FCR) {(r[:, 1] / r[:, 0] >= CLEAN).mean():.3f}, residual ink (RI) {1 - r[:, 1].sum() / r[:, 0].sum():.4f}, excess mask ratio (EMR) {spill / max(1, ideal):.3f}") # COCO AP. Mask AP counts only labels with a mask; the rest become ignore regions. for iou_type in ("bbox", "segm"): gt = {**coco, "images": list(images.values()), "annotations": []} for a in coco["annotations"]: if a["image_id"] not in images: continue crowd = a["iscrowd"] or (iou_type == "segm" and not a["attributes"].get("has_mask")) segmentation = a["segmentation"] if a["attributes"].get("has_mask") or iou_type == "bbox" else rle.encode(np.asfortranarray(box_mask(a["bbox"], images[a["image_id"]]["height"], images[a["image_id"]]["width"]).astype(np.uint8))) if isinstance(segmentation.get("counts"), bytes): segmentation = {**segmentation, "counts": segmentation["counts"].decode("ascii")} gt["annotations"].append({**a, "iscrowd": int(bool(crowd)), "segmentation": segmentation}) # Copies: pycocotools' loadRes writes box polygons into box results. dt = [dict(p) for p in preds if p["image_id"] in images and (iou_type == "bbox" or "segmentation" in p)] if not dt: continue ground = COCO() ground.dataset = gt ground.createIndex() evaluator = COCOeval(ground, ground.loadRes(dt), iou_type) print(f" {'box' if iou_type == 'bbox' else 'mask'} AP50 / AP50-95 per class:") for category in coco["categories"]: evaluator.params.catIds = [category["id"]] evaluator.evaluate() evaluator.accumulate() precision = evaluator.eval["precision"][:, :, 0, 0, -1] if (precision > -1).any(): print(f" {category['name']:13s} {precision[0][precision[0] > -1].mean():.3f} / {precision[precision > -1].mean():.3f}") if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("subset", choices=["danbooru", "manga109", "western"]) parser.add_argument("split", choices=["train", "validation", "test"]) parser.add_argument("predictions") parser.add_argument("--text", type=float, default=0.25) parser.add_argument("--onomatopoeia", type=float, default=0.4) args = parser.parse_args() main(args.subset, args.split, args.predictions, args.text, args.onomatopoeia)