File size: 6,186 Bytes
a863f79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
import argparse
import json
from pathlib import Path

import numpy as np
from PIL import Image


def load_meta(path):
    return json.loads(Path(path).read_text(encoding="utf-8"))


def camera_view(meta, point):
    matrix = np.array(meta["camera"]["matrix_world"], dtype=np.float64)
    inv = np.linalg.inv(matrix)
    homogeneous = np.array([point[0], point[1], point[2], 1.0], dtype=np.float64)
    return inv @ homogeneous


def project(meta, point):
    cam = camera_view(meta, point)
    if cam[2] >= -1e-6:
        return None
    lens = meta["camera"]["lens_mm"]
    sensor = meta["camera"]["sensor_mm"]
    width, height = meta["camera"]["resolution"]
    f = lens / sensor * width
    u = width / 2.0 + f * cam[0] / (-cam[2])
    v = height / 2.0 - f * cam[1] / (-cam[2])
    return [float(u), float(v)]


def overlap_area(a, b):
    ax0, ay0, az0 = a["min"]
    ax1, ay1, az1 = a["max"]
    bx0, by0, bz0 = b["min"]
    bx1, by1, bz1 = b["max"]
    dx = min(ax1, bx1) - max(ax0, bx0)
    dy = min(ay1, by1) - max(ay0, by0)
    return max(0.0, dx) * max(0.0, dy)


def mask_coverage(meta, root):
    path = Path(root) / meta["mask"]
    mask = np.asarray(Image.open(path).convert("RGB")).astype(int)
    total = mask.shape[0] * mask.shape[1]
    red = int(((mask[:, :, 0] > 200) & (mask[:, :, 1] < 80)).sum())
    green = int(((mask[:, :, 1] > 200) & (mask[:, :, 0] < 80)).sum())
    return red / total, green / total


def analyze(meta, root):
    root = Path(root)
    subj = next(o for o in meta["objects"] if o["role"] == "subject")
    obj = next(o for o in meta["objects"] if o["role"] == "object")
    sc = camera_view(meta, subj["world_bbox"]["center"])
    oc = camera_view(meta, obj["world_bbox"]["center"])
    su = project(meta, subj["world_bbox"]["center"])
    ou = project(meta, obj["world_bbox"]["center"])
    width, height = meta["camera"]["resolution"]
    family = meta["family"]
    detail = {
        "cam_x_subject": float(sc[0]),
        "cam_y_subject": float(sc[1]),
        "cam_z_subject": float(sc[2]),
        "cam_x_object": float(oc[0]),
        "cam_y_object": float(oc[1]),
        "cam_z_object": float(oc[2]),
        "pixel_subject": su,
        "pixel_object": ou,
        "gap_m": None,
    }
    if family == "left_right":
        detail["dx_cam"] = float(sc[0] - oc[0])
        computed = "yes" if detail["dx_cam"] < 0 else "no"
        margin = abs(detail["dx_cam"])
    elif family == "above_below":
        detail["dy_cam"] = float(sc[1] - oc[1])
        computed = "yes" if detail["dy_cam"] > 0 else "no"
        margin = abs(detail["dy_cam"])
    elif family == "front_behind":
        detail["dz_cam"] = float(sc[2] - oc[2])
        computed = "yes" if detail["dz_cam"] > 0 else "no"
        margin = abs(detail["dz_cam"])
    else:
        gap = subj["world_bbox"]["min"][2] - obj["world_bbox"]["max"][2]
        area = overlap_area(subj["world_bbox"], obj["world_bbox"])
        subj_area = (subj["world_bbox"]["max"][0] - subj["world_bbox"]["min"][0]) * (
            subj["world_bbox"]["max"][1] - subj["world_bbox"]["min"][1]
        )
        detail["gap_m"] = float(gap)
        detail["overlap_ratio"] = float(area / subj_area) if subj_area > 0 else 0.0
        computed = "yes" if abs(gap) <= 0.02 and detail["overlap_ratio"] >= 0.2 else "no"
        margin = abs(gap)
    inside = (
        su is not None
        and ou is not None
        and 0 <= su[0] < width
        and 0 <= su[1] < height
        and 0 <= ou[0] < width
        and 0 <= ou[1] < height
    )
    pixel_sep = None
    if su is not None and ou is not None:
        pixel_sep = float(np.hypot(su[0] - ou[0], su[1] - ou[1]))
    detail.update(
        {
            "computed": computed,
            "declared": meta["truth"],
            "agree": computed == meta["truth"],
            "margin": float(margin),
            "inside_frame": bool(inside),
            "pixel_separation": pixel_sep,
        }
    )
    subj_frac, obj_frac = mask_coverage(meta, root)
    detail["subject_px_frac"] = subj_frac
    detail["object_px_frac"] = obj_frac
    detail["visible"] = bool(subj_frac >= 0.006 and obj_frac >= 0.006)
    return detail


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--meta", required=True)
    parser.add_argument("--out", required=True)
    args = parser.parse_args()
    rows = []
    for path in sorted(Path(args.meta).glob("*.json")):
        meta = load_meta(path)
        detail = analyze(meta, path.parent)
        rows.append(
            {
                "image": meta["image"],
                "scene_id": meta["scene_id"],
                "family": meta["family"],
                "state": meta["state"],
                "question": meta["question"],
                "subject_category": next(o["category"] for o in meta["objects"] if o["role"] == "subject"),
                "object_category": next(o["category"] for o in meta["objects"] if o["role"] == "object"),
                **detail,
            }
        )
    out = Path(args.out)
    out.parent.mkdir(parents=True, exist_ok=True)
    with out.open("w", encoding="utf-8") as fh:
        for row in rows:
            fh.write(json.dumps(row, ensure_ascii=False) + "\n")
    total = len(rows)
    agree = sum(1 for r in rows if r["agree"])
    inside = sum(1 for r in rows if r["inside_frame"])
    summary = {
        "rows": total,
        "agree": agree,
        "agree_rate": agree / total if total else None,
        "inside_frame": inside,
        "weak_margin": sum(1 for r in rows if r["margin"] < 0.05),
        "min_pixel_separation": min((r["pixel_separation"] or 0.0) for r in rows) if rows else None,
        "by_family": {},
    }
    for family in sorted({r["family"] for r in rows}):
        subset = [r for r in rows if r["family"] == family]
        summary["by_family"][family] = {
            "rows": len(subset),
            "agree_rate": sum(1 for r in subset if r["agree"]) / len(subset),
        }
    (out.parent / "truth_summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8")
    print(json.dumps(summary, ensure_ascii=False))


if __name__ == "__main__":
    main()