Repository navigation
Expand file tree
/
Copy pathcheck_material_object.py
More file actions
320 lines (278 loc) · 15.7 KB
/
Copy pathcheck_material_object.py
File metadata and controls
320 lines (278 loc) · 15.7 KB
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
#!/usr/bin/env python
"""Feasibility check: can material evidence fix PartMaterialCATSeg's object-class choice on GC6D?
No training. It answers one question before anyone builds a "frozen material -> object" branch:
on GraspClutter6D GT masks, does the material distribution inside a mask carry object-class
information that the model's own object scores miss?
Stage 1 (GPU, cached in <out>/vectors.npz; ~5 GB):
* GC6D: for every GT mask (mask_visib) whose obj_id has a class in --obj-classes, crop it exactly
like infer_image.label_map_per_object (square crop, --crop-margin, resized to --crop-size), then
take the mean inside the mask of
- the 39 object scores (the part+object head; this is what the model uses to pick the class)
- the 52 DMS material scores (the material head, on the same crop).
* PACO prior: the same material vector for up to --prior-per-class object regions per class from
PACO tabletop train+val (regions = the pre-rendered object map == class). Averaging them gives
P(material | object class). It comes from PACO, not GC6D, so nothing about the GC6D answer leaks
into it. PACO has no material labels: the prior is what the frozen material head *predicts* on
PACO objects, which is exactly the signal a fused model would get.
Stage 2 (CPU, --analyse-only reruns just this):
fused score(c) = log obj_score(c) + lambda * sum_m q(m) log P(m | c)
where q is the mask's material distribution. Reports accuracy over a lambda grid (lambda = 0 is
the model as is), material-only accuracy, and an honest cross-scene number: lambda chosen on one
scene, scored on the other (the two default scenes share no obj_id).
source ./pixi_setup.sh
pixi run python check_material_object.py # scenes 000000 000003, camera slot 1
pixi run python check_material_object.py --analyse-only # rerun stage 2 from the cache
Caveat printed in the summary too: many masks are views of the same physical object (13 views per
object with the default frames), so the effective sample size is the number of distinct objects.
"""
import argparse
import json
import sys
from collections import defaultdict
from pathlib import Path
import numpy as np
REPO = Path(__file__).resolve().parent
GC6D_ROOT = "/scratch2/ennovatex.Rath/dataset/GraspClutter6D-2" # another user's tree: read only
PACO_ROOT = "/scratch2/ennovatex.Soumo/part_datasets/PACO_tabletop"
LAMBDAS = [0.0, 0.1, 0.25, 0.5, 1.0, 2.0, 4.0, 8.0, 16.0, 32.0]
EPS = 1e-3 # smoothing of P(material | class) before the log
# ----------------------------------------------------------------------------- stage 1 (GPU)
def mask_vectors(cfg, model, image, mask, crop_size, margin, want_objects=True):
"""(object scores (n_obj,) or None, material scores (n_mat,)), means inside the mask."""
import torch
from detectron2.data import transforms as T
from infer_image import crop_box, forward
predictor = model.sem_seg_head.predictor
n_part, n_obj = len(predictor.test_part_classes), len(predictor.test_obj_in_part_classes)
t, b, l, r = crop_box(mask, margin)
crop, m = image[t:b, l:r], mask[t:b, l:r]
obj = None
with torch.no_grad():
if want_objects:
_, part_obj = forward(cfg, model, crop, crop_size)
mt = torch.as_tensor(m, device=part_obj.device)
obj = part_obj[n_part:n_part + n_obj][:, mt].mean(1).cpu().numpy()
del part_obj
resized = T.ResizeTransform(b - t, r - l, crop_size, crop_size).apply_image(crop)
x = torch.as_tensor(np.ascontiguousarray(resized.transpose(2, 0, 1))).float()
mat = model.material_inference([{"image": x, "height": b - t, "width": r - l, "task": "material"}])
mat = mat[0]["material_seg"][:, torch.as_tensor(m)].mean(1).numpy()
return obj, mat
def gc6d_samples(root, scenes, frames, obj_classes, obj_names, min_area):
"""(scene, frame, inst, obj_id, class, rgb path, mask path) for every usable GT mask."""
skipped = defaultdict(int)
out = []
for scene in scenes:
sdir = Path(root) / "scenes" / scene
gt = json.loads((sdir / "scene_gt.json").read_text())
for frame in frames:
rgb = sdir / "rgb" / f"{frame:06d}.png"
if not rgb.exists() or str(frame) not in gt:
skipped["missing frame"] += 1
continue
for inst, o in enumerate(gt[str(frame)]):
cls = obj_classes.get(str(o["obj_id"]))
if cls is None:
skipped[f"obj_id {o['obj_id']} has no class"] += 1
continue
if cls not in obj_names:
sys.exit(f"--obj-classes maps obj_id {o['obj_id']} to {cls!r}, not a model object")
mpath = sdir / "mask_visib" / f"{frame:06d}_{inst:06d}.png"
out.append((scene, frame, inst, o["obj_id"], cls, rgb, mpath))
return out, dict(skipped)
def paco_samples(splits, per_class, obj_names, seed):
"""(image path, object map path, class index) pairs, up to per_class per class."""
by_class = defaultdict(list)
for split in splits:
for r in json.loads((Path(PACO_ROOT) / f"{split}.json").read_text()):
for c in r["obj_classes_with_parts"]:
by_class[c].append((r["file_name"], r["obj_sem_seg_file_name"], c))
rng = np.random.RandomState(seed)
out = []
for c in range(len(obj_names)):
items = by_class.get(c, [])
idx = rng.permutation(len(items))[:per_class * 2] # spare ones replace too-small regions
out.append([items[i] for i in idx])
return out
def compute_vectors(args, out_npz):
import torch
from PIL import Image
from infer_image import load_model
if not torch.cuda.is_available():
sys.exit("needs a GPU (PartCATSeg's CLIP text encoder is hard-wired to .cuda())")
cfg, model = load_model("paco_material", args.weights, config=args.config)
predictor = model.sem_seg_head.predictor
obj_names = list(predictor.test_obj_in_part_classes)
mat_names = list(predictor.material_classes)
paco_names = json.loads((Path(PACO_ROOT) / "classes.json").read_text())["OBJ_CLASS_NAMES"]
if paco_names != obj_names:
sys.exit(f"model object order differs from PACO classes.json:\n{obj_names}\n{paco_names}")
obj_classes = {k: v for k, v in json.loads(Path(args.obj_classes).read_text()).items()
if not k.startswith("_")}
samples, skipped = gc6d_samples(args.gc6d_root, args.scenes, args.frames, obj_classes, obj_names,
args.min_mask_area)
print(f"GC6D: {len(samples)} masks to score; skipped {skipped}")
g_obj, g_mat, g_meta = [], [], []
for k, (scene, frame, inst, obj_id, cls, rgb, mpath) in enumerate(samples, 1):
image = np.asarray(Image.open(rgb).convert("RGB"))
mask = np.asarray(Image.open(mpath))
mask = (mask if mask.ndim == 2 else mask[..., 0]) > 0
if mask.sum() < args.min_mask_area:
continue
o, m = mask_vectors(cfg, model, image, mask, args.crop_size, args.crop_margin)
g_obj.append(o)
g_mat.append(m)
g_meta.append([scene, frame, inst, obj_id, obj_names.index(cls)])
if k % 25 == 0 or k == len(samples):
print(f" GC6D {k}/{len(samples)}", flush=True)
torch.cuda.empty_cache()
p_mat, p_cls = [], []
per_class = paco_samples(args.prior_splits, args.prior_per_class, obj_names, args.seed)
total = sum(min(len(v), args.prior_per_class) for v in per_class)
print(f"PACO prior: up to {args.prior_per_class} regions per class, ~{total} crops")
done = 0
for c, items in enumerate(per_class):
kept = 0
for img_path, obj_path, _ in items:
if kept == args.prior_per_class:
break
mask = np.asarray(Image.open(obj_path)) == c
if mask.sum() < args.min_mask_area:
continue
image = np.asarray(Image.open(img_path).convert("RGB"))
_, m = mask_vectors(cfg, model, image, mask, args.crop_size, args.crop_margin, want_objects=False)
p_mat.append(m)
p_cls.append(c)
kept += 1
done += 1
if done % 100 == 0:
print(f" PACO {done}/~{total}", flush=True)
torch.cuda.empty_cache()
np.savez_compressed(out_npz, gc6d_obj=np.array(g_obj), gc6d_mat=np.array(g_mat),
gc6d_meta=np.array(g_meta, dtype=object), paco_mat=np.array(p_mat),
paco_cls=np.array(p_cls), obj_names=np.array(obj_names),
mat_names=np.array(mat_names), checkpoint=str(cfg.MODEL.WEIGHTS),
args=json.dumps(vars(args)))
print(f"saved {out_npz}")
# ----------------------------------------------------------------------------- stage 2 (CPU)
def normalise(v):
v = np.clip(v, 0, None)
return v / np.maximum(v.sum(-1, keepdims=True), 1e-12)
def accuracy(pred, gt, sel=None):
sel = np.ones_like(gt, dtype=bool) if sel is None else sel
return float((pred[sel] == gt[sel]).mean()) if sel.any() else float("nan"), int(sel.sum())
def analyse(npz_path, out_dir):
d = np.load(npz_path, allow_pickle=True)
obj_names, mat_names = list(d["obj_names"]), list(d["mat_names"])
meta = d["gc6d_meta"]
scene = np.array([m[0] for m in meta])
frame = np.array([int(m[1]) for m in meta])
obj_id = np.array([int(m[3]) for m in meta])
gt = np.array([int(m[4]) for m in meta])
obj_scores = d["gc6d_obj"]
q = normalise(d["gc6d_mat"])
# P(material | class) from PACO; classes without PACO regions get a uniform prior (no evidence)
n_obj, n_mat = len(obj_names), len(mat_names)
prior = np.full((n_obj, n_mat), 1.0 / n_mat)
counts = np.bincount(d["paco_cls"].astype(int), minlength=n_obj)
pq = normalise(d["paco_mat"])
for c in range(n_obj):
if counts[c]:
prior[c] = pq[d["paco_cls"] == c].mean(0)
prior = (prior + EPS) / (prior + EPS).sum(1, keepdims=True)
log_obj = np.log(obj_scores + 1e-6) # (N, n_obj)
mat_ll = q @ np.log(prior).T # (N, n_obj) sum_m q(m) log P(m | c)
def predict(lam):
return (mat_ll if lam == "material" else log_obj + lam * mat_ll).argmax(1)
lines = []
say = lines.append
first = frame == frame.min()
say(f"checkpoint: {d['checkpoint']}")
say(f"GC6D masks: {len(gt)} ({len(set(zip(scene, obj_id)))} distinct objects, "
f"{len(set(scene))} scenes, frames {sorted(set(frame))[:3]}...{sorted(set(frame))[-1]})")
say(f"PACO prior: {len(pq)} regions; classes with none (uniform prior): "
f"{[obj_names[c] for c in range(n_obj) if counts[c] == 0] or 'none'}")
gt_classes = sorted(set(gt))
say("prior for the GC6D classes (top 3 materials, n PACO regions):")
for c in gt_classes:
top = np.argsort(-prior[c])[:3]
say(f" {obj_names[c]:<10} n={counts[c]:<3} " + ", ".join(f"{mat_names[m]} {prior[c, m]:.2f}" for m in top))
say("\naccuracy of the object class (lambda 0 = the model as is):")
say(f" {'lambda':>8} {'all':>12} {'first frame':>12} " + " ".join(f"{s:>12}" for s in sorted(set(scene))))
for lam in LAMBDAS + ["material"]:
p = predict(lam)
cells = [accuracy(p, gt), accuracy(p, gt, first)] + [accuracy(p, gt, scene == s) for s in sorted(set(scene))]
say(f" {str(lam):>8} " + " ".join(f"{a:6.3f} ({n:3d})" for a, n in cells))
# honest number: choose lambda on one scene, score on the other(s)
scenes = sorted(set(scene))
if len(scenes) > 1:
say("\ncross-scene: lambda chosen on the other scene(s) (ties -> smallest lambda):")
correct, total = 0, 0
for s in scenes:
train, test = scene != s, scene == s
best = max(LAMBDAS, key=lambda lam: (accuracy(predict(lam), gt, train)[0], -lam))
a0, n = accuracy(predict(0.0), gt, test)
a, _ = accuracy(predict(best), gt, test)
correct += round(a * n)
total += n
say(f" test {s}: lambda {best:<5} -> {a:.3f} (model as is {a0:.3f}, n={n})")
say(f" pooled held-out accuracy: {correct / total:.3f} (model as is {accuracy(predict(0.0), gt)[0]:.3f})")
# the direct question: on the masks the model gets wrong, does material prefer the true class?
p0 = predict(0.0)
wrong = p0 != gt
if wrong.any():
prefers = mat_ll[wrong, gt[wrong]] > mat_ll[wrong, p0[wrong]]
say(f"\nmodel wrong on {wrong.sum()} masks; material log-likelihood prefers the TRUE class over the "
f"model's choice on {prefers.sum()} of them ({prefers.mean():.0%})")
right = ~wrong
keeps = mat_ll[right, gt[right]] >= np.sort(mat_ll[right], 1)[:, -1] - 1e-12
say(f"model right on {right.sum()} masks; material ranks the true class first on {keeps.sum()} "
f"({keeps.mean():.0%})")
say("confusions (true -> model's pick: count, how often material prefers the true class):")
pairs = defaultdict(list)
for i in np.nonzero(wrong)[0]:
pairs[(gt[i], p0[i])].append(mat_ll[i, gt[i]] > mat_ll[i, p0[i]])
for (t, p), v in sorted(pairs.items(), key=lambda kv: -len(kv[1])):
say(f" {obj_names[t]:<10} -> {obj_names[p]:<14} {len(v):3d} material prefers true: {sum(v)}/{len(v)}")
say("\nper mask, first frame:")
say(f" {'scene':<7}{'inst':>4} {'obj_id':>6} {'true':<10} {'model':<14} {'mat-rank':>8} top materials")
rank = (mat_ll > mat_ll[np.arange(len(gt)), gt][:, None]).sum(1) + 1
for i in np.nonzero(first)[0]:
top = np.argsort(-q[i])[:3]
mark = "" if p0[i] == gt[i] else " <- wrong"
say(f" {scene[i]:<7}{int(meta[i][2]):>4} {obj_id[i]:>6} {obj_names[gt[i]]:<10} {obj_names[p0[i]]:<14} "
f"{rank[i]:>8} " + ", ".join(f"{mat_names[m]} {q[i, m]:.2f}" for m in top) + mark)
say("\nmat-rank = rank of the true class among all 39 under material alone (1 = best).")
say("Masks from different frames of one object are NOT independent: judge by distinct objects.")
text = "\n".join(lines)
(out_dir / "summary.txt").write_text(text + "\n")
print(text)
print(f"\nwritten {out_dir / 'summary.txt'}")
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--scenes", nargs="+", default=["000000", "000003"])
ap.add_argument("--frames", nargs="+", type=int, default=list(range(1, 53, 4)),
help="GC6D frame ids (default 1,5,..,49 = camera slot 1, 13 views)")
ap.add_argument("--obj-classes", default=str(REPO / "datasets" / "gc6d_obj_classes.json"))
ap.add_argument("--gc6d-root", default=GC6D_ROOT)
ap.add_argument("--weights", help="default: output/partmaterialcatseg_paco_dms/model_final.pth")
ap.add_argument("--config", help="the checkpoint's config, if not partmaterialcatseg_paco_dms.yaml")
ap.add_argument("--prior-splits", nargs="+", default=["train", "val"])
ap.add_argument("--prior-per-class", type=int, default=40)
ap.add_argument("--crop-size", type=int, default=384)
ap.add_argument("--crop-margin", type=float, default=0.15)
ap.add_argument("--min-mask-area", type=int, default=100)
ap.add_argument("--seed", type=int, default=0)
ap.add_argument("--out", default=str(REPO / "results" / "material_object_check"))
ap.add_argument("--analyse-only", action="store_true", help="skip stage 1, reuse <out>/vectors.npz")
args = ap.parse_args()
out_dir = Path(args.out)
out_dir.mkdir(parents=True, exist_ok=True)
npz = out_dir / "vectors.npz"
if not args.analyse_only:
compute_vectors(args, npz)
elif not npz.exists():
sys.exit(f"{npz} not found: run without --analyse-only first")
analyse(npz, out_dir)
if __name__ == "__main__":
main()