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
| """ Grounded-SAM 自动标注 -> Grounding/Spatial QA 数据生成。 运行方式: 真实: python stage4_week2_spatial.py --images ./imgs/ --out spatial.jsonl --use_dino 离线: python stage4_week2_spatial.py --out spatial.jsonl (伪检测器验证流程) 依赖: (真实模式) torch, transformers, supervision 或 Grounded-SAM 官方仓库 """ import argparse import itertools import json import random
def normalize_box(box, w, h, base=1000): """像素坐标 -> [x1,y1,x2,y2] 归一化整数 (Qwen2-VL 约定)""" x1, y1, x2, y2 = box return [round(base * x1 / w), round(base * y1 / h), round(base * x2 / w), round(base * y2 / h)]
def center(b): return ((b[0] + b[2]) / 2, (b[1] + b[3]) / 2)
def horizontal_rel(a, b, alpha=0.8): """a 相对 b 的水平关系; alpha 为抗歧义带系数。返回 'left'/'right'/None""" (cax, cay), (cbx, cby) = center(a), center(b) band = alpha * min(a[3] - a[1], b[3] - b[1]) if abs(cay - cby) > band: return None return "left" if cax < cbx else "right"
def vertical_rel(a, b, alpha=0.8): (cax, cay), (cbx, cby) = center(a), center(b) band = alpha * min(a[2] - a[0], b[2] - b[0]) if abs(cax - cbx) > band: return None return "above" if cay < cby else "below"
def bigger(a, b, ratio=1.5): area_a = (a[2] - a[0]) * (a[3] - a[1]) area_b = (b[2] - b[0]) * (b[3] - b[1]) if area_a > ratio * area_b: return "a" if area_b > ratio * area_a: return "b" return None
def build_qas(img_name, w, h, dets, rng): """dets: [{'label','box_px','score'}] -> QA 列表""" qas = [] objs = [{"label": d["label"], "box": normalize_box(d["box_px"], w, h), "center": center(normalize_box(d["box_px"], w, h))} for d in dets] for o in objs: qas.append({"image": img_name, "dim": "grounding", "question": f"请定位图中的{o['label']},输出其位置坐标。", "answer": str(o["box"]), "provenance": {"type": "gt_box"}}) for a, b in itertools.combinations(objs, 2): hrel = horizontal_rel(a["box"], b["box"]) vrel = vertical_rel(a["box"], b["box"]) if hrel == "left": q, ans = f"{a['label']}和{b['label']}哪个在图的左边?以相机视角回答。", a["label"] elif hrel == "right": q, ans = f"{a['label']}和{b['label']}哪个在图的左边?以相机视角回答。", b["label"] elif vrel == "above": q, ans = f"{a['label']}和{b['label']}哪个在图的上方?", a["label"] elif vrel == "below": q, ans = f"{a['label']}和{b['label']}哪个在图的上方?", b["label"] else: continue qas.append({"image": img_name, "dim": "spatial", "question": q, "answer": ans, "provenance": {"type": "predicate"}}) bg = bigger(a["box"], b["box"]) if bg: big = a["label"] if bg == "a" else b["label"] qas.append({"image": img_name, "dim": "spatial", "question": f"{a['label']}和{b['label']}哪个更大?", "answer": big, "provenance": {"type": "predicate"}}) from collections import Counter for label, n in Counter(d["label"] for d in dets).items(): if n >= 2: qas.append({"image": img_name, "dim": "counting", "question": f"图中共有几个{label}?", "answer": str(n), "provenance": {"type": "gt_count"}}) rng.shuffle(qas) return qas
def detect_with_grounding_dino(image_path, phrases, device="cuda"): """真实检测入口 (Grounding DINO, HuggingFace 加载方式)""" from transformers import AutoProcessor, AutoModelForZeroShotObjectDetection from PIL import Image proc = AutoProcessor.from_pretrained("IDEA-Research/grounding-dino-tiny") model = AutoModelForZeroShotObjectDetection.from_pretrained( "IDEA-Research/grounding-dino-tiny").to(device) image = Image.open(image_path).convert("RGB") text = " . ".join(phrases) + " ." inputs = proc(images=image, text=text, return_tensors="pt").to(device) with __import__("torch").no_grad(): outputs = model(**inputs) results = proc.post_process_grounded_object_detection( outputs, input_ids=inputs["input_ids"], threshold=0.35, text_threshold=0.30, target_sizes=[image.size[::-1]])[0] return [{"label": lbl.lower().strip(" ."), "box_px": [round(v, 1) for v in box.tolist()], "score": s} for box, lbl, s in zip(results["boxes"], results["text_labels"], results["scores"])]
def fake_detect(img_name, rng): """离线伪检测器: 确定性输出桌面物品 (默认场景含 3 个物体, 保证空间配对有产出)""" scenes = {"img_000.jpg": [("cup", 200, 300, 260, 380, .8), ("laptop", 500, 250, 900, 550, .9), ("cup", 300, 320, 350, 390, .7)], "img_001.jpg": [("book", 100, 400, 260, 480, .75), ("book", 500, 410, 640, 490, .68)], "img_002.jpg": [("plant", 700, 100, 900, 420, .85), ("laptop", 150, 300, 500, 560, .88)]} default = [("cup", 100, 200, 180, 300, .6), ("book", 400, 380, 560, 460, .65), ("laptop", 600, 150, 950, 400, .7)] return [{"label": l, "box_px": [x1, y1, x2, y2], "score": s} for l, x1, y1, x2, y2, s in scenes.get(img_name, default)]
def _test_geometry(): """几何谓词单测: 验证关键行为""" A = [100, 100, 200, 200]; B = [500, 120, 600, 220] assert horizontal_rel(A, B) == "left" and horizontal_rel(B, A) == "right" C = [400, 100, 500, 200] assert horizontal_rel(C, B) == "left" D = [500, 800, 600, 900] assert vertical_rel(D, B) == "below" and horizontal_rel(D, B) is None E = [100, 100, 105, 105] assert bigger(E, A) == "b" and bigger(A, A) is None assert normalize_box([0, 0, 500, 375], 500, 375) == [0, 0, 1000, 1000] print("✅ 几何谓词/归一化单测通过")
if __name__ == "__main__": _test_geometry() ap = argparse.ArgumentParser() ap.add_argument("--images", default="imgs"); ap.add_argument("--out", default="spatial.jsonl") ap.add_argument("--use_dino", action="store_true") args = ap.parse_args() rng = random.Random(0)
all_qas = [] for i in range(50): name = f"img_{i:03d}.jpg" dets = (detect_with_grounding_dino(f"{args.images}/{name}", ["cup", "laptop", "book", "plant", "bottle"]) if args.use_dino else fake_detect(name, rng)) all_qas.extend(build_qas(name, 1000, 750, dets, rng))
for qa in all_qas: if qa["dim"] == "grounding": b = json.loads(qa["answer"]) assert 0 <= b[0] < b[2] <= 1000 and 0 <= b[1] < b[3] <= 1000, \ f"非法归一化框: {b}" if qa["dim"] == "counting": assert int(qa["answer"]) >= 2 assert len(all_qas) >= 200, f"产出不足: {len(all_qas)}" with open(args.out, "w") as f: f.writelines(json.dumps(q, ensure_ascii=False) + "\n" for q in all_qas) print(f"产出 {len(all_qas)} 条 -> {args.out}")
|