Download OVOW/masking/grsam_from_scene_json.py from AIGeeksGroup/PhysicalWM: direct link, hf CLI and curl.
- Browser
- Download file 14.1 kB
-
https://huggingface.co/datasets/AIGeeksGroup/PhysicalWM/resolve/main/OVOW/masking/grsam_from_scene_json.py
- Command line
-
hf download hf://datasets/AIGeeksGroup/PhysicalWM/OVOW/masking/grsam_from_scene_json.py
-
curl -L -o grsam_from_scene_json.py https://huggingface.co/datasets/AIGeeksGroup/PhysicalWM/resolve/main/OVOW/masking/grsam_from_scene_json.py
14.1 kB
| #!/usr/bin/env python | |
| """ | |
| 读取 scene.json(包含 objects + prompt),调用 GroundingDINO + SAM2 分割每个物体, | |
| 按 object 的 id 命名 mask 文件,写入 masks/,并回填 scene.json 的 mask 字段。 | |
| 示例: | |
| conda activate qwen | |
| python Grounded_SAM2/qwen/grsam_from_scene_json.py \ | |
| --scene-dir data_pose/scenes/scene_12 | |
| """ | |
| import argparse | |
| import json | |
| from pathlib import Path | |
| from typing import List, Optional, Tuple | |
| 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"): | |
| """与 segment.py 一致的预处理:宽度 518px,保持长宽比并根据模式裁剪/填充。""" | |
| 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") | |
| target_size = 518 | |
| to_tensor = TF.ToTensor() | |
| 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 = to_tensor(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_tensor = img_tensor | |
| image_np = (image_tensor.permute(1, 2, 0).numpy() * 255).astype(np.uint8) | |
| image_bgr = cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR) | |
| h, w = image_tensor.shape[1], image_tensor.shape[2] | |
| return image_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: | |
| """小写并去掉尾部标点,便于匹配 GDINO 返回的 label。""" | |
| t = text.strip().lower() | |
| while t.endswith((".", ",", ";", " ")): | |
| t = t[:-1] | |
| return t | |
| def build_joint_caption(objects: List[dict]) -> Tuple[str, List[str]]: | |
| """ | |
| 把所有 object.prompt 拼成一个 GDINO caption,并返回标准化后的子句列表。 | |
| - 子句形如 "red car on the road" | |
| - caption 形如 "red car on the road. house on the left." | |
| """ | |
| clauses = [] | |
| for obj in objects: | |
| p = obj.get("prompt") or obj.get("name") or "" | |
| p = p.strip() | |
| if not p: | |
| continue | |
| clauses.append(p) | |
| normalized_clauses = [normalize_phrase(c) for c in clauses] | |
| caption = ". ".join(normalized_clauses) | |
| if not caption.endswith("."): | |
| caption += "." | |
| return caption, normalized_clauses | |
| def main() -> None: | |
| parser = argparse.ArgumentParser( | |
| description="Grounded SAM2 根据 scene.json 的 prompt 分割物体并写回 mask 路径" | |
| ) | |
| 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( | |
| "--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( | |
| "--per-object", | |
| action="store_true", | |
| help="逐物体调用 GDINO/SAM2(默认关闭,使用一次性拼接 caption 的模式)", | |
| ) | |
| 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_model = build_sam2( | |
| str(args.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 | |
| scene_json = scene_dir / "scene.json" | |
| if not scene_json.is_file(): | |
| print(f"[WARN] scene.json 不存在,跳过: {scene_json}") | |
| continue | |
| with scene_json.open("r", encoding="utf-8") as f: | |
| data = json.load(f) | |
| image_name = data.get("image") or find_single_image_file(scene_dir) | |
| if not image_name: | |
| print(f"[WARN] 未找到场景图片,跳过: {scene_dir}") | |
| continue | |
| image_path = scene_dir / image_name | |
| if not image_path.is_file(): | |
| print(f"[WARN] 场景图片不存在,跳过: {image_path}") | |
| continue | |
| objects = data.get("objects", []) | |
| if not objects: | |
| print(f"[WARN] {scene_dir} objects 为空,未执行分割。") | |
| continue | |
| image_tensor, image_bgr, h, w = load_image_for_models(image_path) | |
| 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) | |
| mask_dir = ensure_mask_dir(scene_dir, args.mask_dir_name) | |
| print(f"\n===== 处理 {scene_dir.name} =====") | |
| if args.per_object: | |
| for idx, obj in enumerate(objects): | |
| prompt = obj.get("prompt") or obj.get("name") | |
| if not prompt: | |
| print(f"[WARN] object[{idx}] 缺少 prompt/name,跳过") | |
| continue | |
| print(f"[PROMPT][per-object] idx={idx}: {prompt}") | |
| caption = prompt.lower().strip() | |
| if not caption.endswith("."): | |
| caption = caption + "." | |
| print(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 未检测到:{prompt}") | |
| continue | |
| best_idx = int(torch.argmax(confidences).item()) | |
| box = boxes[best_idx].to(device) | |
| box = box * torch.tensor([w, h, w, h], device=box.device) | |
| box_xyxy = ( | |
| box_convert(boxes=box.unsqueeze(0), in_fmt="cxcywh", out_fmt="xyxy") | |
| .cpu() | |
| .numpy() | |
| ) | |
| masks, scores, _ = sam2_predictor.predict( | |
| point_coords=None, | |
| point_labels=None, | |
| box=box_xyxy, | |
| multimask_output=False, | |
| ) | |
| mask = masks[0].astype(np.uint8) * 255 | |
| obj_id = obj.get("id") or f"obj{idx+1}" | |
| mask_rel = obj.get("mask") or f"{args.mask_dir_name}/{obj_id}.png" | |
| mask_path = scene_dir / mask_rel | |
| mask_path.parent.mkdir(parents=True, exist_ok=True) | |
| cv2.imwrite(str(mask_path), mask) | |
| obj["id"] = obj_id | |
| obj["mask"] = str(mask_rel) | |
| print(f"[OK] {prompt} -> {mask_rel}") | |
| else: | |
| caption, clauses = build_joint_caption(objects) | |
| if not caption.strip(): | |
| print(f"[WARN] 无有效 prompt,跳过 {scene_dir}") | |
| continue | |
| print(f"[PROMPT][joint] 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] GDINO 未检测到任何框,跳过 {scene_dir}") | |
| continue | |
| norm_labels = [normalize_phrase(l) for l in labels] | |
| 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() | |
| used = set() | |
| for idx, obj in enumerate(objects): | |
| target = normalize_phrase(obj.get("prompt") or obj.get("name") or "") | |
| match_idx = None | |
| for j, lbl in enumerate(norm_labels): | |
| if j in used: | |
| continue | |
| if lbl == target: | |
| match_idx = j | |
| break | |
| if match_idx is None: | |
| for j in range(len(norm_labels)): | |
| if j not in used: | |
| match_idx = j | |
| break | |
| if match_idx is None: | |
| print(f"[WARN] 没有可用的检测结果分配给 object[{idx}]") | |
| continue | |
| used.add(match_idx) | |
| box_xyxy = boxes_xyxy[match_idx : match_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 | |
| obj_id = obj.get("id") or f"obj{idx+1}" | |
| mask_rel = obj.get("mask") or f"{args.mask_dir_name}/{obj_id}.png" | |
| mask_path = scene_dir / mask_rel | |
| mask_path.parent.mkdir(parents=True, exist_ok=True) | |
| cv2.imwrite(str(mask_path), mask) | |
| obj["id"] = obj_id | |
| obj["mask"] = str(mask_rel) | |
| print(f"[OK] {obj.get('prompt') or obj.get('name')} -> {mask_rel}") | |
| with scene_json.open("w", encoding="utf-8") as f: | |
| json.dump(data, f, ensure_ascii=False, indent=2) | |
| print(f"[DONE] 已更新 {scene_json}") | |
| if __name__ == "__main__": | |
| main() | |