SAM3 多物体分割器
| 11 | |
| 12 | |
| 13 | class SAM3MultiObjectSegmenter: |
| 14 | """SAM3 多物体分割器""" |
| 15 | |
| 16 | def __init__(self, checkpoint_path: Path = None, confidence_threshold: float = 0.1): |
| 17 | """ |
| 18 | 初始化 SAM3 模型 |
| 19 | |
| 20 | Args: |
| 21 | checkpoint_path: SAM3 checkpoint 路径 |
| 22 | confidence_threshold: 置信度阈值 |
| 23 | """ |
| 24 | if checkpoint_path is None: |
| 25 | checkpoint_path = Path("/mnt/workspace/users/lbc/sam3/checkpoints/sam3.pt") |
| 26 | |
| 27 | self.checkpoint_path = checkpoint_path |
| 28 | self.confidence_threshold = confidence_threshold |
| 29 | |
| 30 | # 添加 sam3 路径 |
| 31 | sam3_path = Path("/mnt/workspace/users/lbc/sam3") |
| 32 | if sam3_path not in [Path(p) for p in sys.path]: |
| 33 | sys.path.insert(0, str(sam3_path)) |
| 34 | |
| 35 | # 导入 SAM3 |
| 36 | from sam3.model_builder import build_sam3_image_model |
| 37 | from sam3.model.sam3_image_processor import Sam3Processor |
| 38 | |
| 39 | # 加载模型 |
| 40 | logger.info(f"Loading SAM3 model from: {checkpoint_path}") |
| 41 | model = build_sam3_image_model( |
| 42 | checkpoint_path=str(checkpoint_path), |
| 43 | load_from_HF=False |
| 44 | ) |
| 45 | self.processor = Sam3Processor(model, confidence_threshold=confidence_threshold) |
| 46 | logger.success("✓ SAM3 model loaded") |
| 47 | |
| 48 | def segment_object_multiview( |
| 49 | self, |
| 50 | images_dir: Path, |
| 51 | object_name: str, |
| 52 | text_prompt: str, |
| 53 | output_dir: Path, |
| 54 | ) -> Dict: |
| 55 | """ |
| 56 | 对多个视角的图像分割同一个物体 |
| 57 | |
| 58 | Args: |
| 59 | images_dir: 图像目录 |
| 60 | object_name: 物体名称 |
| 61 | text_prompt: SAM3 文本提示词 |
| 62 | output_dir: 输出目录(将创建 object_name/ 子目录) |
| 63 | |
| 64 | Returns: |
| 65 | Dict with status and info |
| 66 | """ |
| 67 | logger.info(f"\n[Segmenting: {object_name}]") |
| 68 | logger.info(f" Prompt: '{text_prompt}'") |
| 69 | |
| 70 | # 获取所有图像(使用自然数字排序,确保 2.png 排在 10.png 前面) |