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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
#!/usr/bin/env python
"""
读取 label.json(labels + image),调用 GroundingDINO + SAM2 分割每个 label 的所有实例,
按 label_01/label_02/... 命名 mask 文件,写入 masks/,并生成/写回 scene.json。
"""

import argparse
import json
import re
from pathlib import Path
from typing import List, Optional

import cv2
import numpy as np
import torch
from PIL import Image
from torchvision import transforms as TF
from torchvision.ops import box_convert

from sam2.build_sam import build_sam2
from sam2.sam2_image_predictor import SAM2ImagePredictor
from grounding_dino.groundingdino.util.inference import load_model, predict


def find_single_image_file(scene_dir: Path) -> Optional[str]:
    exts = {".jpg", ".jpeg", ".png", ".JPG", ".JPEG", ".PNG"}
    candidates = [p.name for p in scene_dir.iterdir() if p.is_file() and p.suffix in exts]
    if len(candidates) == 1:
        return candidates[0]
    return None


def load_image_for_models(image_path: Path, mode: str = "crop", target_size: int = 518):
    if mode not in ("crop", "pad"):
        raise ValueError("mode 必须是 'crop' 或 'pad'")

    img = Image.open(image_path)
    if img.mode == "RGBA":
        bg = Image.new("RGBA", img.size, (255, 255, 255, 255))
        img = Image.alpha_composite(bg, img)
    img = img.convert("RGB")

    width, height = img.size

    if mode == "pad":
        if width >= height:
            new_width = target_size
            new_height = round(height * (new_width / width) / 14) * 14
        else:
            new_height = target_size
            new_width = round(width * (new_height / height) / 14) * 14
    else:
        new_width = target_size
        new_height = round(height * (new_width / width) / 14) * 14

    img = img.resize((new_width, new_height), Image.Resampling.BICUBIC)
    img_tensor = TF.ToTensor()(img)

    if mode == "crop" and new_height > target_size:
        start_y = (new_height - target_size) // 2
        img_tensor = img_tensor[:, start_y : start_y + target_size, :]

    if mode == "pad":
        h_padding = target_size - img_tensor.shape[1]
        w_padding = target_size - img_tensor.shape[2]
        if h_padding > 0 or w_padding > 0:
            pad_top = h_padding // 2
            pad_bottom = h_padding - pad_top
            pad_left = w_padding // 2
            pad_right = w_padding - pad_left
            img_tensor = torch.nn.functional.pad(
                img_tensor,
                (pad_left, pad_right, pad_top, pad_bottom),
                mode="constant",
                value=1.0,
            )

    image_np = (img_tensor.permute(1, 2, 0).numpy() * 255).astype(np.uint8)
    image_bgr = cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR)
    h, w = img_tensor.shape[1], img_tensor.shape[2]
    return img_tensor, image_bgr, h, w


def ensure_mask_dir(scene_dir: Path, mask_dir_name: str) -> Path:
    mask_dir = scene_dir / mask_dir_name
    mask_dir.mkdir(parents=True, exist_ok=True)
    return mask_dir


def parse_scene_spec(spec: str) -> List[int]:
    ids: List[int] = []
    for chunk in spec.split(","):
        chunk = chunk.strip()
        if not chunk:
            continue
        if "-" in chunk:
            a, b = chunk.split("-", 1)
            start, end = int(a), int(b)
            if end < start:
                start, end = end, start
            ids.extend(range(start, end + 1))
        else:
            ids.append(int(chunk))
    return sorted(set(ids))


def normalize_phrase(text: str) -> str:
    t = text.strip().lower()
    while t.endswith((".", ",", ";", " ")):
        t = t[:-1]
    return t


def _as_int(value, default=0) -> int:
    try:
        return int(value)
    except Exception:
        return default


def parse_labels_and_counts(data: dict):
    labels: List[str] = []
    label_counts = {}
    label_prompts = {}

    def add_label(name_raw, num_raw=None, prompt_raw=None):
        name = normalize_phrase(str(name_raw))
        if not name:
            return
        labels.append(name)
        if num_raw is not None:
            num = _as_int(num_raw, default=0)
            if num > 0:
                label_counts[name] = max(label_counts.get(name, 0), num)
        if prompt_raw:
            label_prompts.setdefault(name, str(prompt_raw))

    objects = data.get("objects", [])
    if isinstance(objects, list):
        for obj in objects:
            if isinstance(obj, dict):
                add_label(
                    obj.get("name") or obj.get("label") or obj.get("prompt") or "",
                    obj.get("num") or obj.get("count") or obj.get("instances"),
                    obj.get("prompt") or obj.get("name"),
                )
            elif isinstance(obj, str):
                add_label(obj)

    label_counts_raw = data.get("label_counts", {})
    if isinstance(label_counts_raw, dict):
        for k, v in label_counts_raw.items():
            add_label(k, v, None)

    label_items = data.get("labels", [])
    if isinstance(label_items, list):
        for item in label_items:
            if isinstance(item, dict):
                add_label(
                    item.get("name") or item.get("label") or item.get("prompt") or "",
                    item.get("num") or item.get("count") or item.get("instances"),
                    item.get("prompt") or item.get("name"),
                )
            else:
                add_label(item)

    return labels, label_counts, label_prompts


def sanitize_id(text: str) -> str:
    base = normalize_phrase(text)
    base = re.sub(r"[^a-z0-9]+", "_", base).strip("_")
    return base or "obj"

def load_binary_mask(mask_path: Path):
    mask = cv2.imread(str(mask_path), cv2.IMREAD_GRAYSCALE)
    if mask is None:
        return None
    return mask > 0

def mask_iou(a, b) -> float:
    inter = (a & b).sum()
    union = (a | b).sum()
    return float(inter) / float(union) if union else 0.0

def dedupe_objects_by_iou(objects, scene_dir: Path, iou_thresh: float, keep_mode: str):
    if iou_thresh <= 0:
        return objects
    kept = []
    kept_masks = []
    kept_scores = []
    kept_areas = []
    for obj in objects:
        mask_path = scene_dir / obj["mask"]
        mask = load_binary_mask(mask_path)
        if mask is None:
            continue
        score = float(obj.get("_score", 0.0))
        area = int(mask.sum())
        match_idx = None
        for i, km in enumerate(kept_masks):
            if mask_iou(mask, km) >= iou_thresh:
                match_idx = i
                break
        if match_idx is None:
            kept.append(obj)
            kept_masks.append(mask)
            kept_scores.append(score)
            kept_areas.append(area)
        else:
            if keep_mode == "area":
                better = area > kept_areas[match_idx]
            else:
                better = score > kept_scores[match_idx]
            if better:
                kept[match_idx] = obj
                kept_masks[match_idx] = mask
                kept_scores[match_idx] = score
                kept_areas[match_idx] = area
    return kept


def main() -> None:
    parser = argparse.ArgumentParser(
        description="Grounded SAM2 根据 label.json 分割物体并写回 scene.json(多实例)"
    )
    parser.add_argument("--scene-dir", type=Path, help="单个 scene 目录")
    parser.add_argument(
        "--scene-range",
        type=str,
        help='批量模式,形如 "1-4,6,8"(按 scene_{:02d} 命名)',
    )
    parser.add_argument(
        "--root-dir",
        type=Path,
        default=Path(__file__).resolve().parents[2] / "data_pose" / "scenes",
        help="场景根目录(默认 data_pose/scenes)",
    )
    parser.add_argument(
        "--label-json-name",
        type=str,
        default="label.json",
        help="label.json 文件名(默认 label.json)",
    )
    parser.add_argument(
        "--sam2-ckpt",
        type=Path,
        default=Path("checkpoints/sam2.1_hiera_large.pt"),
        help="SAM2 checkpoint 路径",
    )
    parser.add_argument(
        "--sam2-config",
        type=Path,
        default=Path("configs/sam2.1/sam2.1_hiera_l.yaml"),
        help="SAM2 config 路径",
    )
    parser.add_argument(
        "--gdino-config",
        type=Path,
        default=Path("grounding_dino/groundingdino/config/GroundingDINO_SwinB_cfg.py"),
        help="GroundingDINO 配置",
    )
    parser.add_argument(
        "--gdino-ckpt",
        type=Path,
        default=Path("gdino_checkpoints/groundingdino_swinb_cogcoor.pth"),
        help="GroundingDINO checkpoint",
    )
    parser.add_argument("--box-threshold", type=float, default=0.2, help="GroundingDINO box threshold")
    parser.add_argument("--text-threshold", type=float, default=0.2, help="GroundingDINO text threshold")
    parser.add_argument(
        "--mask-dir-name",
        type=str,
        default="masks",
        help="mask 输出目录名(相对 scene_dir)",
    )
    parser.add_argument(
        "--target-size",
        type=int,
        default=1024,
        help="检测/分割输入的目标分辨率(默认 1024)",
    )
    parser.add_argument(
        "--merge-label-masks",
        action=argparse.BooleanOptionalAction,
        default=True,
        help="每个 label 将所有实例 mask 合并为一张(默认开启)",
    )
    parser.add_argument(
        "--only-existing-masks",
        action="store_true",
        help="仅使用已存在的 mask 文件生成 scene.json,不进行检测/分割(默认关闭)",
    )
    parser.add_argument(
        "--dedupe-iou",
        type=float,
        default=0.0,
        help="跨 label 去重阈值(mask IoU),0 表示关闭",
    )
    parser.add_argument(
        "--dedupe-keep",
        type=str,
        default="score",
        choices=["score", "area"],
        help="去重冲突时保留的策略:score 或 area",
    )
    parser.add_argument(
        "--max-instances-per-label",
        type=int,
        default=50,
        help="每个 label 最多输出多少个实例(默认 50)",
    )
    parser.add_argument(
        "--dump-preprocessed",
        action="store_true",
        help="保存预处理后的检测输入,便于调试(默认关闭)",
    )

    args = parser.parse_args()

    scene_dirs: List[Path] = []
    if args.scene_dir:
        scene_dirs = [args.scene_dir.resolve()]
    if args.scene_range:
        for sid in parse_scene_spec(args.scene_range):
            scene_dirs.append(args.root_dir / f"scene_{sid:02d}")
    if not scene_dirs:
        raise ValueError("必须提供 --scene-dir 或 --scene-range")

    device = "cuda" if torch.cuda.is_available() else "cpu"
    gdino = load_model(
        model_config_path=str(args.gdino_config),
        model_checkpoint_path=str(args.gdino_ckpt),
        device=device,
    ).to(device)
    sam2_config = args.sam2_config
    if sam2_config.is_absolute():
        marker = "/sam2/configs/"
        s = str(sam2_config)
        if marker in s:
            sam2_config = Path("configs") / s.split(marker, 1)[1]
    sam2_model = build_sam2(
        str(sam2_config),
        str(args.sam2_ckpt),
        device=device,
    ).to(device)
    sam2_predictor = SAM2ImagePredictor(sam2_model)

    for scene_dir in scene_dirs:
        if not scene_dir.is_dir():
            print(f"[WARN] scene 目录不存在,跳过: {scene_dir}")
            continue

        label_json = scene_dir / args.label_json_name
        if not label_json.is_file():
            print(f"[WARN] label.json 不存在,跳过: {label_json}")
            continue

        with label_json.open("r", encoding="utf-8") as f:
            data = json.load(f)

        image_name = data.get("image") or find_single_image_file(scene_dir)
        labels, label_counts, label_prompts = parse_labels_and_counts(data)
        if not image_name:
            print(f"[WARN] 未找到场景图片,跳过: {scene_dir}")
            continue
        if not labels:
            print(f"[WARN] label.json labels 为空,跳过: {scene_dir}")
            continue

        uniq = []
        seen = set()
        for lbl in labels:
            t = normalize_phrase(str(lbl))
            if not t or t in seen:
                continue
            seen.add(t)
            uniq.append(t)
        labels = uniq
        if label_counts:
            label_counts = {k: v for k, v in label_counts.items() if k in set(labels)}

        image_path = scene_dir / image_name
        if not image_path.is_file():
            print(f"[WARN] 场景图片不存在,跳过: {image_path}")
            continue

        image_tensor, image_bgr, h, w = load_image_for_models(
            image_path, target_size=args.target_size
        )
        if args.dump_preprocessed:
            debug_dir = scene_dir / "debug_inputs"
            debug_dir.mkdir(exist_ok=True, parents=True)
            dump_name = debug_dir / f"{scene_dir.name}_{image_path.stem}_preprocessed.png"
            cv2.imwrite(str(dump_name), image_bgr)
            print(f"[DEBUG] 已保存预处理图像: {dump_name}")
        sam2_predictor.set_image(image_bgr)

        ensure_mask_dir(scene_dir, args.mask_dir_name)

        print(f"\n===== 处理 {scene_dir.name} =====")

        objects: List[dict] = []
        if args.only_existing_masks:
            mask_dir = scene_dir / args.mask_dir_name
            for lbl in labels:
                base_id = sanitize_id(lbl)
                max_n = max(1, int(args.max_instances_per_label))
                if args.merge_label_masks:
                    mask_path = mask_dir / f"{base_id}.png"
                    if not mask_path.exists():
                        print(f"[WARN] 缺少已有 mask:{lbl}")
                        continue
                    mask_rel = f"{args.mask_dir_name}/{base_id}.png"
                    objects.append(
                        {
                            "id": base_id,
                            "name": lbl,
                            "prompt": lbl,
                            "is_occluded": False,
                            "mask": str(mask_rel),
                            "_score": 0.0,
                        }
                    )
                    print(f"[OK] {lbl} -> {mask_rel} (existing)")
                else:
                    files = sorted(mask_dir.glob(f"{base_id}_*.png"))
                    if not files:
                        print(f"[WARN] 缺少已有 mask:{lbl}")
                        continue
                    for mask_path in files[:max_n]:
                        inst_id = mask_path.stem
                        mask_rel = f"{args.mask_dir_name}/{inst_id}.png"
                        objects.append(
                            {
                                "id": inst_id,
                                "name": lbl,
                                "prompt": lbl,
                                "is_occluded": False,
                                "mask": str(mask_rel),
                                "_score": 0.0,
                            }
                        )
                        print(f"[OK] {lbl} -> {mask_rel} (existing)")

            if args.dedupe_iou > 0 and objects:
                objects = dedupe_objects_by_iou(objects, scene_dir, args.dedupe_iou, args.dedupe_keep)
            if not objects:
                print(f"[WARN] {scene_dir} 未生成任何 objects")
                continue

            scene_json = scene_dir / "scene.json"
            for obj in objects:
                obj.pop("_score", None)
            with scene_json.open("w", encoding="utf-8") as f:
                json.dump({"image": image_name, "objects": objects}, f, ensure_ascii=False, indent=2)
            print(f"[DONE] 已更新 {scene_json}")
            continue

        for lbl in labels:
            prompt = label_prompts.get(lbl, lbl)
            caption = str(prompt).lower().strip()
            if not caption.endswith("."):
                caption = caption + "."

            boxes, confidences, _labels = predict(
                model=gdino,
                image=image_tensor,
                caption=caption,
                box_threshold=args.box_threshold,
                text_threshold=args.text_threshold,
                device=device,
            )
            if boxes is None or len(boxes) == 0:
                print(f"[WARN] GroundingDINO 未检测到:{lbl}")
                continue

            keep = confidences >= args.box_threshold
            if keep.numel() != 0:
                boxes = boxes[keep]
                confidences = confidences[keep]
            if boxes is None or len(boxes) == 0:
                print(f"[WARN] 过滤后无有效框:{lbl}")
                continue

            boxes = boxes * torch.tensor([w, h, w, h], device=boxes.device)
            boxes_xyxy = box_convert(boxes=boxes, in_fmt="cxcywh", out_fmt="xyxy").cpu().numpy()

            order = torch.argsort(confidences, descending=True)
            boxes_xyxy = boxes_xyxy[order.cpu().numpy()]
            conf_sorted = confidences[order].detach().cpu().numpy()

            base_id = sanitize_id(lbl)
            max_n = max(1, int(args.max_instances_per_label))
            if label_counts and lbl in label_counts:
                max_n = min(max_n, max(1, int(label_counts[lbl])))

            if args.merge_label_masks:
                merged = None
                kept = 0
                best_score = 0.0
                for inst_idx, box_xyxy in enumerate(boxes_xyxy, start=1):
                    if inst_idx > max_n:
                        break
                    if inst_idx - 1 < len(conf_sorted):
                        best_score = max(best_score, float(conf_sorted[inst_idx - 1]))
                    masks, scores, _ = sam2_predictor.predict(
                        point_coords=None,
                        point_labels=None,
                        box=box_xyxy,
                        multimask_output=False,
                    )
                    mask = masks[0].astype(np.uint8) * 255
                    if merged is None:
                        merged = mask.copy()
                    else:
                        merged = np.maximum(merged, mask)
                    kept += 1

                if merged is None:
                    print(f"[WARN] {lbl} 未生成任何 mask")
                    continue

                inst_id = base_id
                mask_rel = f"{args.mask_dir_name}/{inst_id}.png"
                mask_path = scene_dir / mask_rel
                mask_path.parent.mkdir(parents=True, exist_ok=True)
                cv2.imwrite(str(mask_path), merged)

                objects.append(
                    {
                        "id": inst_id,
                        "name": lbl,
                        "prompt": lbl,
                        "is_occluded": False,
                        "mask": str(mask_rel),
                        "_score": best_score,
                    }
                )
                print(f"[OK] {lbl} -> {mask_rel} (merged {kept})")
            else:
                for inst_idx, box_xyxy in enumerate(boxes_xyxy, start=1):
                    if inst_idx > max_n:
                        break
                    masks, scores, _ = sam2_predictor.predict(
                        point_coords=None,
                        point_labels=None,
                        box=box_xyxy,
                        multimask_output=False,
                    )
                    mask = masks[0].astype(np.uint8) * 255

                    inst_id = f"{base_id}_{inst_idx:02d}"
                    mask_rel = f"{args.mask_dir_name}/{inst_id}.png"
                    mask_path = scene_dir / mask_rel
                    mask_path.parent.mkdir(parents=True, exist_ok=True)
                    cv2.imwrite(str(mask_path), mask)

                    objects.append(
                        {
                            "id": inst_id,
                            "name": lbl,
                            "prompt": lbl,
                            "is_occluded": False,
                            "mask": str(mask_rel),
                            "_score": float(conf_sorted[inst_idx - 1]) if inst_idx - 1 < len(conf_sorted) else 0.0,
                        }
                    )
                    print(f"[OK] {lbl} -> {mask_rel}")

        if args.dedupe_iou > 0 and objects:
            objects = dedupe_objects_by_iou(objects, scene_dir, args.dedupe_iou, args.dedupe_keep)
        if not objects:
            print(f"[WARN] {scene_dir} 未生成任何 objects")
            continue

        scene_json = scene_dir / "scene.json"
        for obj in objects:
            obj.pop("_score", None)
        with scene_json.open("w", encoding="utf-8") as f:
            json.dump({"image": image_name, "objects": objects}, f, ensure_ascii=False, indent=2)
        print(f"[DONE] 已更新 {scene_json}")


if __name__ == "__main__":
    main()