File size: 4,890 Bytes
fde9a21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#!/usr/bin/env python3
"""Render evaluator-only previews of every ordered instance box.

These overlays stay separate from images/ and public baseline jobs. They let
a human verify row assignment, left-to-right ordinals, A/B targets, and box
coverage before SAM2 is run.
"""

from __future__ import annotations

import argparse
import json
from pathlib import Path
from typing import Any

from PIL import Image, ImageDraw, ImageFont, ImageOps


DEFAULT_ROOT = Path(__file__).resolve().parents[1]
ROW_COLORS = {
    "single": (0, 230, 255),
    "top": (255, 210, 0),
    "upper": (255, 210, 0),
    "back": (255, 210, 0),
    "rear": (255, 210, 0),
    "bottom": (0, 255, 110),
    "lower": (0, 255, 110),
    "front": (0, 255, 110),
}


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--dataset-root", type=Path, default=DEFAULT_ROOT)
    parser.add_argument("--manifest", type=Path, default=None)
    parser.add_argument("--output-dir", type=Path, default=None)
    parser.add_argument("--max-width", type=int, default=1800)
    parser.add_argument("--max-height", type=int, default=1400)
    return parser.parse_args()


def font(size: int) -> ImageFont.ImageFont:
    for path in (
        "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
        "/usr/share/fonts/truetype/liberation2/LiberationSans-Bold.ttf",
    ):
        if Path(path).exists():
            return ImageFont.truetype(path, size=size)
    return ImageFont.load_default()


def norm_box(values: list[float], width: int, height: int) -> tuple[int, int, int, int]:
    x1, y1, x2, y2 = (float(value) for value in values)
    return (
        round(x1 * (width - 1)),
        round(y1 * (height - 1)),
        round(x2 * (width - 1)),
        round(y2 * (height - 1)),
    )


def row_color(row: str) -> tuple[int, int, int]:
    return ROW_COLORS.get(row.casefold(), (255, 115, 225))


def main() -> None:
    args = parse_args()
    root = args.dataset_root.resolve()
    manifest_path = (args.manifest or root / "metadata/manifest.json").resolve()
    output_dir = (args.output_dir or root / "previews/instance_order").resolve()
    manifest: dict[str, Any] = json.loads(manifest_path.read_text(encoding="utf-8"))
    output_dir.mkdir(parents=True, exist_ok=True)

    for case in manifest["cases"]:
        case_id = str(case["case_id"])
        with Image.open(root / str(case["image"])) as raw:
            image = ImageOps.exif_transpose(raw).convert("RGB")
        source_size = image.size
        image.thumbnail((args.max_width, args.max_height), Image.Resampling.LANCZOS)
        width, height = image.size
        draw = ImageDraw.Draw(image)
        line_width = max(3, round(max(width, height) / 400))
        label_font = font(max(18, round(max(width, height) / 48)))
        title_font = font(max(20, round(max(width, height) / 42)))

        target_pairs: dict[str, list[str]] = {}
        for variant in case["variants"]:
            target_pairs.setdefault(str(variant["target_instance_id"]), []).append(str(variant["pair"]))

        for instance in case["instance_order"]:
            instance_id = str(instance["instance_id"])
            row = str(instance["row"])
            ordinal = int(instance["ordinal_from_left"])
            box = norm_box(instance["bbox_xyxy_norm"], width, height)
            color = row_color(row)
            draw.rectangle(box, outline=color, width=line_width)
            pairs = target_pairs.get(instance_id, [])
            suffix = f"  TARGET {'/'.join(pairs)}" if pairs else ""
            label = f"{row}:{ordinal}{suffix}"
            text_box = draw.textbbox((box[0], box[1]), label, font=label_font, stroke_width=2)
            pad = max(4, line_width)
            label_top = max(0, box[1] - (text_box[3] - text_box[1]) - 2 * pad)
            label_right = min(width - 1, box[0] + (text_box[2] - text_box[0]) + 2 * pad)
            draw.rectangle((box[0], label_top, label_right, box[1]), fill=(0, 0, 0))
            draw.text(
                (box[0] + pad, label_top + pad),
                label,
                font=label_font,
                fill=color,
                stroke_width=1,
                stroke_fill=(0, 0, 0),
            )

        title = f"{case_id} | {case['category']} | {case['layout']} | source {source_size[0]}x{source_size[1]}"
        title_box = draw.textbbox((0, 0), title, font=title_font, stroke_width=2)
        pad = max(7, line_width * 2)
        draw.rectangle((0, 0, min(width, title_box[2] + 2 * pad), title_box[3] + 2 * pad), fill=(0, 0, 0))
        draw.text((pad, pad), title, font=title_font, fill=(255, 255, 255), stroke_width=1, stroke_fill=(0, 0, 0))

        output = output_dir / f"{case_id}_instances.jpg"
        image.save(output, quality=95, subsampling=0)
        print(output)


if __name__ == "__main__":
    main()