import os import json import cv2 import numpy as np import torch from PIL import Image from transformers import AutoProcessor, AutoModelForZeroShotObjectDetection from sam2.sam2_image_predictor import SAM2ImagePredictor from sam2.build_sam import build_sam2 VALID_DIR = {"left", "right", "front", "back"} def load_dir_map(jsonl_path: str): mp = {} with open(jsonl_path, "r", encoding="utf-8") as f: for line in f: line = line.strip() if not line: continue try: obj = json.loads(line) except Exception: continue vid = obj.get("video_id", None) direc = obj.get("direction", None) if isinstance(direc, str): direc = direc.strip().lower() if direc not in VALID_DIR: direc = None else: direc = None if vid is not None: mp[str(vid)] = direc return mp def save_mask(mask_bool: np.ndarray, out_path: str): os.makedirs(os.path.dirname(out_path), exist_ok=True) mask_uint8 = (mask_bool.astype(np.uint8) * 255) cv2.imwrite(out_path, mask_uint8) def build_models( device, dino_dir="/mnt/prev_nas/qhy/MagicMotion/trajectory_construction/Grounded_SAM2/checkpoints/grounding-dino-tiny", sam2_checkpoint="/mnt/prev_nas/qhy/MagicMotion/trajectory_construction/Grounded_SAM2/checkpoints/sam2_hiera_large.pt", model_cfg="sam2_hiera_l.yaml", ): processor = AutoProcessor.from_pretrained(dino_dir) grounding_model = AutoModelForZeroShotObjectDetection.from_pretrained(dino_dir).to(device) sam2_model = build_sam2(model_cfg, sam2_checkpoint) predictor = SAM2ImagePredictor(sam2_model) return processor, grounding_model, predictor @torch.no_grad() def segment_single_image(image_path, text_prompt, processor, grounding_model, predictor, device, box_threshold=0.25, text_threshold=0.3): image_pil = Image.open(image_path).convert("RGB") image_np = np.array(image_pil) text = text_prompt.strip().lower() if not text.endswith("."): text += "." inputs = processor(images=image_pil, text=text, return_tensors="pt").to(device) outputs = grounding_model(**inputs) results = processor.post_process_grounded_object_detection( outputs, inputs.input_ids, box_threshold=box_threshold, text_threshold=text_threshold, target_sizes=[image_pil.size[::-1]] # (H, W) ) boxes = results[0]["boxes"].detach().cpu().numpy() if len(boxes) == 0: return None, False predictor.set_image(image_np) masks, _, _ = predictor.predict( point_coords=None, point_labels=None, box=boxes, multimask_output=False ) if masks.ndim == 4: masks = masks.squeeze(1) # (N, H, W) final_mask = np.any(masks, axis=0) # (H, W), bool return final_mask, True def main(): import argparse p = argparse.ArgumentParser() p.add_argument("--prompts_json", default="/mnt/prev_nas/qhy_1/datasets/unedit_image_prompts/genspace_prompts_vlm.json") p.add_argument("--dir_jsonl", default="/mnt/5T_nas/cwl/wan/OmniGen2/data_configs/train/example/edit/qwen_direction_merged.jsonl") # 图片用 video_id 定位:{img_root}/{video_id}.png 或 {img_root}/{video_id} p.add_argument("--img_root", default="/mnt/prev_nas/qhy_1/datasets/flux_gen_images_edit") p.add_argument("--img_ext", default=".png", help="when image file is {video_id}{img_ext}") p.add_argument("--out_dir", default="/mnt/prev_nas/qhy_1/datasets/flux_gen_images_masks") p.add_argument("--overwrite", action="store_true") p.add_argument("--start", type=int, default=0) p.add_argument("--end", type=int, default=-1) p.add_argument("--dino_dir", default="/mnt/prev_nas/qhy/MagicMotion/trajectory_construction/Grounded_SAM2/checkpoints/grounding-dino-tiny") p.add_argument("--sam2_ckpt", default="/mnt/prev_nas/qhy/MagicMotion/trajectory_construction/Grounded_SAM2/checkpoints/sam2_hiera_large.pt") p.add_argument("--sam2_cfg", default="sam2_hiera_l.yaml") args = p.parse_args() dir_map = load_dir_map(args.dir_jsonl) with open(args.prompts_json, "r", encoding="utf-8") as f: data = json.load(f) samples = data["samples"] start = max(0, args.start) end = len(samples) if args.end < 0 else min(len(samples), args.end) samples = samples[start:end] print(f"samples: [{start}:{end}) -> {len(samples)}") device = "cuda" if torch.cuda.is_available() else "cpu" processor, grounding_model, predictor = build_models( device=device, dino_dir=args.dino_dir, sam2_checkpoint=args.sam2_ckpt, model_cfg=args.sam2_cfg, ) for s in samples: video_id = s.get("sample_id") obj_class = s.get("object_class") if not video_id or not obj_class: continue # qwen_direction_merged.jsonl 里可能是 allocentric_000.png 这种 direction = dir_map.get(video_id, None) if direction is None: direction = dir_map.get(video_id + ".png", None) # 如果 jsonl 里有 .png,而 video_id 本身已经带扩展名,这里也不会影响 if direction is None: continue # 找图片:优先 {img_root}/{video_id},不存在再试 {video_id}{img_ext} img_path = os.path.join(args.img_root, video_id) if not os.path.exists(img_path): img_path2 = os.path.join(args.img_root, video_id + args.img_ext) if os.path.exists(img_path2): img_path = img_path2 else: print("missing image:", img_path, "or", img_path2) continue # 保存同名 mask(统一用 png) out_name = video_id if not out_name.lower().endswith(".png"): out_name = out_name + ".png" out_path = os.path.join(args.out_dir, out_name) if (not args.overwrite) and os.path.exists(out_path): continue mask, ok = segment_single_image( img_path, obj_class, processor, grounding_model, predictor, device ) if not ok or mask is None: print(f"no detection: {video_id} text={obj_class}") continue save_mask(mask, out_path) print("saved:", out_path) if __name__ == "__main__": main()