SAM3 的核心机制:PCS
SAM3 不是问答模型,而是 Promptable Concept Segmentation(PCS) 模型:
- 输入:概念描述(名词短语)
- 输出:所有匹配该概念的实例 Mask(多个)
理解这一点才能写出有效 prompt。
识别题目区域的 Prompt
通用(推荐):
exam question
question block
problem statement
更细粒度:
question text region
numbered question
multiple choice question
fill-in-the-blank question
文档/OCR 类:
text question area
exercise item
不要写 all questions 或 detect all questions,SAM3 不理解 all、detect 这类逻辑词。用名词短语描述”这类东西是什么”,SAM3 会自动找出所有实例。
Python 调用示例
import torch
from sam3 import SAM3
model = SAM3.from_pretrained("facebook/sam3-base")
model.eval()
from PIL import Image
image = Image.open("exam_page.jpg")
# PCS 模式:用概念 prompt 找所有实例
with torch.no_grad():
masks = model.predict_concept(
image=image,
concept="exam question",
threshold=0.5
)
print(f"找到 {len(masks)} 个题目区域")
for i, mask in enumerate(masks):
# mask 是 numpy bool array,shape = (H, W)
print(f"题目 {i+1}: bbox = {mask_to_bbox(mask)}")
与 GroundingDINO 组合使用
SAM3 PCS 直接输出 Mask,但复杂图片中 Mask 边界可能不够精确。可以先用 GroundingDINO 获得检测框,再用 SAM3 精确分割:
from groundingdino.util.inference import predict as gdino_predict
from sam3 import SAM3Predictor
# Step 1: GroundingDINO 获得题目框
boxes, _, _ = gdino_predict(
model=gdino_model,
image=image,
caption="exam question",
box_threshold=0.3,
text_threshold=0.25
)
# Step 2: SAM3 对每个框精确分割
sam3_predictor = SAM3Predictor(model)
sam3_predictor.set_image(image)
for box in boxes:
masks, scores, _ = sam3_predictor.predict(
box=box,
multimask_output=False
)
# masks[0] 即为精确 Mask
组合方案比单独使用任一模型效果更好。
Prompt 调试技巧
-
从通用开始,再细化:先试
question,如果噪声太多再改exam question block -
同义词扩展:英文
question、problem、exercise、item可能效果不同,逐一测试 -
调整阈值:
threshold降低会找到更多实例(包括噪声),提高则更保守 -
多 prompt 投票:对同一图片用多个 prompt 预测,取交集或并集
prompts = ["exam question", "question block", "problem statement"]
all_masks = []
for p in prompts:
masks = model.predict_concept(image=image, concept=p, threshold=0.4)
all_masks.extend(masks)
# NMS 去重(基于 IoU)
final_masks = nms_masks(all_masks, iou_threshold=0.5)
常见场景 Prompt 参考
| 场景 | 推荐 Prompt |
|---|---|
| 试卷题目 | exam question, question block |
| 表单字段 | form field, input field |
| 车辆检测 | car, vehicle, truck |
| 人脸 | human face, person face |
| 交通标志 | traffic sign, road sign |
| 文字区域 | text region, printed text |
SAM3 的训练数据以英文概念为主,中文 prompt(如”题目”)效果不稳定,建议始终使用英文。
