图像分割(FastSAM)
更新时间:2026-09-14
简介
FastSAM 全图分割算子,用 ultralytics 的 FastSAM 做 segment-anything,返回每张图分割出的目标框。只保留框、不保留掩码,避免长列掩码撑爆内存。
功能描述
- 框取 ultralytics 的
boxes.xywh,即中心点 + 宽高,单位是原图像素;输出为 struct,并额外带回conf,便于下游按置信度过滤 - 图像统一转 RGB 后按 ndarray 调 FastSAM,推理参数
imgsz/conf/iou/retina_masks由构造参数控制,固定verbose=False - 设备:
num_gpus > 0且torch.cuda.is_available()时取整数卡号rank % 可见卡数,否则"cpu" - 未分割出任何目标、或输入为 null 时,
bbox与conf都是空列表 - 行级异常默认记日志并返回空结构;
fail_on_error=True时直接抛出,让整个任务失败 - 权重只从本地
{model_path}/{model_name}加载,缺失时构造期抛FileNotFoundError,不联网下载 - 只输出框,不输出掩码
算子参数
输入
| 输入 | 含义 |
|---|---|
| image | 图像输入,内容类型由 image_src_type 决定(本地/BOS/HTTP 路径、Base64 字符串、二进制数据) |
输出
输出列类型为 struct,字段如下:
| 输出 | 含义 |
|---|---|
| segments.bbox | list<list |
| segments.conf | list |
参数
| 参数名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| image_src_type | str | "image_url" | 图像输入类型:image_url / image_base64 / image_binary |
| model_path | str | "/opt/aihc/model" | 权重根目录 |
| model_name | str | "FastSAM-x.pt" | 相对 model_path 的 FastSAM 权重文件名 |
| imgsz | int | 1024 | 推理分辨率 |
| conf | float | 0.05 | 置信度阈值 |
| iou | float | 0.5 | NMS IoU 阈值 |
| retina_masks | bool | True | 是否用高分辨率掩码(影响框精度) |
| fail_on_error | bool | False | 单行异常时是否直接抛出而不是返回空结构 |
| rank | int | 0 | 多卡场景 worker 序号,GPU 卡号取 rank % 可见卡数 |
注意事项
conf默认 0.05,阈值很低、出框多,下游按conf自行过滤。- 输出只有框、没有掩码,需要像素级掩码的场景本算子不适用。
num_gpus=0时整图 1024 分辨率的 FastSAM 推理跑在 CPU 上,吞吐会明显下降。
调用示例
Python
1from __future__ import annotations
2
3import os
4
5import daft
6from daft import col
7
8from daft.aihc.common.udf import aihc_udf
9from daft.aihc.functions.image.image_segment import ImageSegment
10
11if __name__ == "__main__":
12 if os.getenv("DAFT_RUNNER", "native") == "ray":
13 import ray
14 ray.init(dashboard_host="0.0.0.0", ignore_reinit_error=True)
15 daft.set_runner_ray()
16 daft.set_execution_config(actor_udf_ready_timeout=6000, min_cpu_per_task=0)
17
18samples = {"image": ["bos://your-bucket/sample.jpg"]}
19 ds = daft.from_pydict(samples)
20 ds = ds.with_column(
21 "segments",
22 aihc_udf(
23 ImageSegment,
24 construct_args={
25 "image_src_type": "image_url",
26 "model_path": "/path/to/models",
27 "model_name": "FastSAM-x.pt",
28 "imgsz": 1024,
29 "conf": 0.05,
30 "iou": 0.5,
31 },
32 num_cpus=1,
33 num_gpus=1,
34 concurrency=1,
35 batch_size=1,
36 )(col("image")),
37 )
38 ds.show()
评价此篇文章
