Repository navigation
Expand file tree
/
Copy pathinfer_hops.py
More file actions
251 lines (219 loc) · 12.8 KB
/
Copy pathinfer_hops.py
File metadata and controls
251 lines (219 loc) · 12.8 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
"""Run a trained HOPS model on arbitrary images (e.g. GraspClutter6D frames), zero-shot over a chosen
test vocabulary, and compare it with an existing per-object PartCATSeg / PartMaterialCATSeg result.
usage (from the repo root, through pixi so DETECTRON2_DATASETS is set):
source ./pixi_setup.sh && pixi run --frozen python infer_hops.py <image or dir> \
[--weights output/hops_voc/model_final.pth] [--config configs/zero_shot/hops_voc.yaml] \
[--vocab-dataset paco_tabletop_obj_part_sem_seg_test_obj_condition] \
[--masks-dir results/part_material/gc6d_meeting/sam3_masks] \
[--compare-dir results/part_material/gc6d_meeting] [--out results/hops_gc6d] [--whole-image]
Default (masks given): the SAM 3 masks REPLACE HOPS's stage-1 object map. Each mask becomes one HOPS
region, exactly as `Hops.postprocess_obj_predictions` builds them (image * mask, cropped to the mask's
box, resized to 384^2), and goes through HOPS's own part stage (`forward_second` with the parts of the
region's object). One forward per mask, so same-class masks with overlapping boxes can't overwrite each
other (HOPS writes whole boxes). Inside a mask only that object's part channels compete, so every mask
pixel gets a part (like `infer_image.py --obj-masks`). The object class per mask is chosen two ways:
hops : argmax of HOPS's stage-1 object probabilities averaged inside the mask, background excluded;
ours : the class our model gave that mask (`<compare-dir>/<stem>_sam3_masks.json`), so both models
segment parts of the same object and only part quality differs.
Masks are painted largest first, so smaller objects stay visible on top.
`--whole-image`: HOPS's native pipeline instead (its own object stage; masks only for display).
"""
import argparse
import json
import os
import sys
from pathlib import Path
import numpy as np
import torch
import torch.nn.functional as F
from PIL import Image
REPO = Path(__file__).resolve().parent
sys.path.insert(0, str(REPO))
import matplotlib # noqa: E402
matplotlib.use("Agg")
import matplotlib.pyplot as plt # noqa: E402
from matplotlib.patches import Patch # noqa: E402
import detectron2.data.transforms as T # noqa: E402
from detectron2.checkpoint import DetectionCheckpointer # noqa: E402
from detectron2.config import get_cfg # noqa: E402
from detectron2.data import MetadataCatalog # noqa: E402
from detectron2.projects.deeplab import add_deeplab_config # noqa: E402
from detectron2.structures import Instances # noqa: E402
from baselines import add_mask_former_config # noqa: E402
import train_net # noqa: E402
NONE = 65535
p = argparse.ArgumentParser()
p.add_argument("images", nargs="+")
p.add_argument("--config", default="configs/zero_shot/hops_voc.yaml")
p.add_argument("--weights", default="output/hops_voc/model_final.pth")
p.add_argument("--vocab-dataset", default="paco_tabletop_obj_part_sem_seg_test_obj_condition",
help="registered dataset whose stuff_classes / obj_classes are the test vocabulary")
p.add_argument("--masks-dir", default="results/part_material/gc6d_meeting/sam3_masks")
p.add_argument("--compare-dir", default="results/part_material/gc6d_meeting",
help="dir with <stem>_sam3_masks_parts.png / .json from infer_part_material.py (optional)")
p.add_argument("--out", default="results/hops_gc6d")
p.add_argument("--whole-image", action="store_true", help="HOPS's own object stage instead of the masks")
p.add_argument("--alpha", type=float, default=0.65)
a = p.parse_args()
paths = []
for x in a.images:
x = Path(x)
paths += sorted(q for q in x.iterdir() if q.suffix.lower() in (".png", ".jpg", ".jpeg")) if x.is_dir() else [x]
cfg = get_cfg()
add_deeplab_config(cfg)
add_mask_former_config(cfg)
cfg.set_new_allowed(True)
cfg.PROGRESS_BAR = False
cfg.merge_from_file(a.config)
cfg.merge_from_list(["MODEL.WEIGHTS", a.weights, "DATASETS.TEST", (a.vocab_dataset,),
"TEST.VISUALIZE", False, "OUTPUT_DIR", str(REPO / ".tmp/hops_infer")])
cfg.freeze()
model = train_net.Trainer.build_model(cfg)
DetectionCheckpointer(model).load(a.weights)
model.eval()
part_names = list(MetadataCatalog.get(a.vocab_dataset).stuff_classes)
obj_names = list(model.test_obj_in_part_classes) # HOPS's stage-1 channels, background last
obj_parts = {o: [i for i, n in enumerate(part_names) if n.split("'s")[0].strip() == o] for o in obj_names}
print(f"vocabulary: {len(part_names)} object-part classes, {len(obj_names)} objects, from {a.vocab_dataset}")
rng = np.random.RandomState(7)
PALETTE = rng.rand(len(part_names), 3) * 0.75 + 0.2
resize = T.ResizeShortestEdge(cfg.INPUT.MIN_SIZE_TEST, cfg.INPUT.MAX_SIZE_TEST, "choice")
# --- mask-driven regions: replaces Hops.postprocess_obj_predictions for one call -------------------
_orig_post = type(model).postprocess_obj_predictions
FORCE = {} # {"mask": HxW bool np (input res), "cls": name or None}; "chosen"/"top3" written back
def _post_from_mask(self, output_obj, batched_inputs, H_1, W_1):
if not FORCE:
return _orig_post(self, output_obj, batched_inputs, H_1, W_1)
m = torch.as_tensor(FORCE["mask"], device=self.device)
assert m.shape == (H_1, W_1), (m.shape, H_1, W_1)
probs = F.softmax(output_obj, dim=1)[0, :-1][:, m].mean(1) # object channels only, inside the mask
top = probs.topk(3)
FORCE["top3"] = [(obj_names[i], round(float(v), 4)) for v, i in zip(top.values, top.indices)]
cls = FORCE["cls"] if FORCE["cls"] is not None else obj_names[int(probs.argmax())]
FORCE["chosen"] = cls
img = batched_inputs[0]["image"].to(self.device).float()
ys, xs = torch.where(m)
x0, y0, x1, y1 = xs.min(), ys.min(), xs.max() + 1, ys.max() + 1
crop = (img * m)[:, y0:y1, x0:x1] # as HOPS: background zeroed, then the box
resized = F.interpolate(crop[None], size=(384, 384), mode="bilinear", align_corners=False)[0]
region = {"class_id": obj_names.index(cls), "mask": m, "resized_image": resized,
"bbox_xywh": torch.stack([x0, y0, x1 - x0, y1 - y0])}
return [[region]]
type(model).postprocess_obj_predictions = _post_from_mask
@torch.no_grad()
def hops_forward(img, mask=None, cls=None):
"""sem_seg_all (C+1, h, w) on CPU. With `mask` (h x w bool) the mask is HOPS's only region."""
h, w = img.shape[:2]
tf = resize.get_transform(img)
r = tf.apply_image(img)
x = torch.as_tensor(np.ascontiguousarray(r.transpose(2, 0, 1))).float()
FORCE.clear()
if mask is not None:
FORCE.update(mask=tf.apply_segmentation(mask.astype(np.uint8)) > 0, cls=cls)
inst = Instances(r.shape[:2])
inst.gt_classes = torch.zeros(1, dtype=torch.long) # dummy: only feeds the ignored masked output
# Hops.forward moves the GT maps to the GPU before branching; the inference branch never reads them
dummy = torch.full(r.shape[:2], 255, dtype=torch.long)
out = model([{"image": x, "height": h, "width": w, "instances": inst,
"obj_part_sem_seg": dummy, "sem_seg": dummy}])[0]["sem_seg_all"]
assert out.shape[0] == len(part_names) + 1, out.shape
return out
def overlay(img, lab, alpha):
out = img.astype(np.float32) / 255.0
m = lab != NONE
out[m] = (1 - alpha) * out[m] + alpha * PALETTE[lab[m]]
return out
def per_mask(img, masks, classes):
"""Label map from one HOPS pass per mask + per-object records."""
lab = np.full(img.shape[:2], NONE, dtype=np.int64)
recs = []
for k in sorted(range(len(masks)), key=lambda k: -masks[k].sum()):
m = masks[k]
if m.sum() < 50:
continue
out = hops_forward(img, m, classes[k])
cls = FORCE["chosen"]
ch = obj_parts[cls]
sc = out[ch][:, torch.as_tensor(m)] # (parts, pixels)
best = np.array(ch)[sc.argmax(0).numpy()]
lab[m] = best
ids, cnt = np.unique(best, return_counts=True)
recs.append({"mask_index": k, "area_px": int(m.sum()), "object": cls,
"object_source": "given" if classes[k] is not None else "hops",
"hops_object_top3": FORCE["top3"],
"parts": {part_names[i]: round(c / m.sum(), 4) for i, c in sorted(zip(ids, cnt), key=lambda t: -t[1])}})
return lab, sorted(recs, key=lambda r: r["mask_index"])
def figure(path, title, panels, labs):
present_ids, cnt = np.unique(np.concatenate([l[l != NONE] for l in labs]), return_counts=True)
present = [i for i, _ in sorted(zip(present_ids, cnt), key=lambda t: -t[1])][:30]
ncol = len(panels)
fig, ax = plt.subplots(1, ncol, figsize=(7.2 * ncol, 5.6))
for x_, (im, t) in zip(ax, panels):
x_.imshow(im)
x_.set_title(t, fontsize=14)
x_.axis("off")
nrow_leg = int(np.ceil(len(present) / 6))
fig.legend(handles=[Patch(color=PALETTE[c], label=part_names[c]) for c in present],
loc="lower center", ncol=6, fontsize=12, frameon=False,
title="HOPS part colours (largest first)", title_fontsize=12)
fig.suptitle(title, fontsize=16)
fig.subplots_adjust(left=0.01, right=0.99, top=0.88, bottom=0.08 + 0.05 * nrow_leg, wspace=0.03)
fig.savefig(path, dpi=100)
plt.close(fig)
os.makedirs(a.out, exist_ok=True)
for path in paths:
stem = path.stem
img = np.array(Image.open(path).convert("RGB"))
mask_files = sorted(Path(a.masks_dir).glob(f"{stem}_*.png")) if a.masks_dir else []
masks = [np.array(Image.open(f).convert("L").resize(img.shape[1::-1], Image.NEAREST)) > 127 for f in mask_files]
cmp_png = Path(a.compare_dir) / f"{stem}_sam3_masks_parts.png" if a.compare_dir else None
cmp_json = Path(a.compare_dir) / f"{stem}_sam3_masks.json" if a.compare_dir else None
ours = {}
if cmp_json and cmp_json.is_file():
ours = {Path(o["mask"]).name: o["object"] for o in json.load(open(cmp_json))["objects"]}
ours_panel = [(np.array(Image.open(cmp_png).convert("RGB")), "ours (PartMaterialCATSeg, per object)")] \
if cmp_png and cmp_png.is_file() else []
if a.whole_image or not masks:
out = hops_forward(img)
lab = out.argmax(0).numpy().astype(np.int64)
lab[lab == len(part_names)] = NONE
Image.fromarray(lab.astype(np.uint16)).save(os.path.join(a.out, f"{stem}_hops_whole_labels.png"))
union = np.any(masks, axis=0) if masks else np.ones(lab.shape, bool)
lab_in = np.where(union, lab, NONE)
figure(os.path.join(a.out, f"{stem}_hops_whole_comparison.png"),
f"{stem}: HOPS, own object stage (trained on Pascal-Part, zero-shot vocabulary)",
[(img / 255.0, "image"), (overlay(img, lab, a.alpha), "HOPS, whole image"),
(overlay(img, lab_in, a.alpha), "HOPS, kept inside SAM 3 masks")] + ours_panel, [lab_in])
print(f"{stem}: whole image, {np.mean(lab != NONE):.1%} of pixels labelled")
continue
lab_h, rec_h = per_mask(img, masks, [None] * len(masks))
given = [ours.get(f.name) if ours.get(f.name) in obj_parts else None for f in mask_files]
lab_o, rec_o = per_mask(img, masks, given) if any(g is not None for g in given) else (None, [])
for r in rec_h + rec_o:
r["mask"] = str(mask_files[r["mask_index"]])
r["ours_object"] = ours.get(mask_files[r["mask_index"]].name)
Image.fromarray(lab_h.astype(np.uint16)).save(os.path.join(a.out, f"{stem}_hops_sam3_hopsclass_labels.png"))
if lab_o is not None:
Image.fromarray(lab_o.astype(np.uint16)).save(os.path.join(a.out, f"{stem}_hops_sam3_ourclass_labels.png"))
with open(os.path.join(a.out, f"{stem}_hops_sam3.json"), "w") as fh:
json.dump({"image": str(path), "checkpoint": a.weights, "vocab_dataset": a.vocab_dataset,
"part_classes": part_names, "label_png_background_value": NONE,
"objects_hops_class": rec_h, "objects_our_class": rec_o}, fh, indent=1)
panels = [(img / 255.0, "image"), (overlay(img, lab_h, a.alpha), "HOPS on SAM 3 masks, HOPS's object class")]
labs = [lab_h]
if lab_o is not None:
panels.append((overlay(img, lab_o, a.alpha), "HOPS on SAM 3 masks, our object class"))
labs.append(lab_o)
figure(os.path.join(a.out, f"{stem}_hops_sam3_comparison.png"),
f"{stem}: HOPS parts on SAM 3 object masks (HOPS trained on Pascal-Part, zero-shot PACO vocabulary)",
panels + ours_panel, labs)
agree = sum(r["object"] == r["ours_object"] for r in rec_h)
print(f"\n{stem}: {len(rec_h)} masks, HOPS's object class == ours on {agree}/{len(rec_h)}")
by_k = {r["mask_index"]: r for r in rec_o}
for r in rec_h:
top = ", ".join(f"{n.split(chr(39) + 's ')[-1]} {v:.0%}" for n, v in list(r["parts"].items())[:3])
ro = by_k.get(r["mask_index"])
topo = ", ".join(f"{n.split(chr(39) + 's ')[-1]} {v:.0%}" for n, v in list(ro["parts"].items())[:3]) if ro else "-"
print(f" {r['mask_index']:2d} hops: {r['object']:14} ({r['hops_object_top3'][0][1]:.2f}) {top:40} | "
f"ours: {str(r['ours_object']):14} -> HOPS parts: {topo}")
print("\nwrote", a.out)