#!/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()