免费图像分割 API 完全教程:零成本把图片里的每个物体精确抠出来(2026-10-24 验证)
欢迎来到 apishare.cc 的免费API教程专栏!图像分割是计算机视觉中最精细的任务——不仅要识别物体,还要精确到像素级别勾画轮廓。无论你是想做背景移除、医学影像分析、自动驾驶场景理解,还是电商商品抠图,本篇《免费图像分割 API 完全教程》都能帮你零成本落地。更多优质免费接口,请查阅我们的 免费API目录,新用户可前往 注册页面 获取专属开发者密钥。
图像分割(Image Segmentation)是指将图像划分为多个具有语义意义的区域,每个区域内的像素属于同一类别或同一物体。与目标检测只画矩形框不同,图像分割需要输出像素级的精确边界——从粗到细分为三个层级:
- 语义分割(Semantic Segmentation):按类别标注每个像素,同类物体不区分个体
- 实例分割(Instance Segmentation):不仅分类,还区分同类物体的不同个体
- 全景分割(Panoptic Segmentation):语义分割 + 实例分割的融合,覆盖所有像素
过去,高精度图像分割依赖昂贵的标注数据和算力。如今开源模型生态成熟,我们已有多条零成本路径可用。下面逐一拆解 5 种免费方案,附完整代码和选型建议。
方案一:Hugging Face 推理 API(Segment Anything Model)
简介
Meta 发布的 Segment Anything Model(SAM)是图像分割领域的里程碑模型,在 11 亿张图像上训练,支持零样本分割。Hugging Face 提供免费推理端点,无需 GPU 即可调用。
免费额度
- 推理 API:无硬性配额限制,但单次请求超时 30 秒
- 适合间歇性调用,高频场景建议自建
代码示例
import requests
API_URL = "https://api-inference.huggingface.co/models/facebook/sam-vit-base"
headers = {"Authorization": "Bearer YOUR_HF_TOKEN"}
def segment_image(image_path, points=None):
"""使用 SAM 模型进行图像分割"""
with open(image_path, "rb") as f:
data = f.read()
payload = {"inputs": data}
if points:
# 提供提示点引导分割
payload["parameters"] = {"input_points": points}
response = requests.post(API_URL, headers=headers, json=payload)
if response.status_code == 200:
result = response.json()
# 返回分割掩码
masks = result[0].get("mask", [])
scores = result[0].get("score", 0)
print(f"分割成功!置信度: {scores:.4f}")
return masks
else:
print(f"请求失败: {response.status_code}")
return None
# 使用示例
masks = segment_image("example.jpg", points=[[500, 375]])
优缺点
- ✅ 零样本分割,无需训练
- ✅ 支持点提示、框提示
- ❌ 免费端点偶尔排队等待
- ❌ 大图需先缩放
方案二:Google Cloud Vision API(图像分割)
简介
Google Cloud Vision API 的 Image Annotation 功能支持多种分割模式,包括 IMAGE_SEGMENTATION(前景分割)和 CROP_HINTS(裁剪提示)。免费层每月 1000 次调用。
免费额度
- 每月前 1000 次
IMAGE_SEGMENTATION调用免费 - 超出后 $3.50/1000 次
- 需绑定信用卡但不会自动扣费
代码示例
from google.cloud import vision
import io
def google_segment(image_path):
"""Google Cloud Vision 图像分割"""
client = vision.ImageAnnotatorClient()
with io.open(image_path, 'rb') as f:
content = f.read()
image = vision.Image(content=content)
# 前景分割
response = client.image_properties(image=image)
# 获取分割结果
if response.image_properties_annotation:
dominant_colors = response.image_properties_annotation.dominant_colors
print(f"检测到 {len(dominant_colors.colors)} 种主要颜色区域")
# 使用 crop_hints 获取裁剪建议
crop_hints_params = vision.CropHintsParams(aspect_ratios=[1.0])
features = [{"type_": vision.Feature.Type.CROP_HINTS}]
return response
# 更强大的方式:使用 Localized Object Annotation
def google_object_segment(image_path):
"""Google Vision 实例分割"""
client = vision.ImageAnnotatorClient()
with io.open(image_path, 'rb') as f:
content = f.read()
image = vision.Image(content=content)
objects = client.object_localization(image=image).localized_object_annotations
for obj in objects:
print(f"物体: {obj.name} (置信度: {obj.score:.3f})")
vertices = obj.bounding_poly.normalized_vertices
for v in vertices:
print(f" 坐标: ({v.x:.2f}, {v.y:.2f})")
return objects
优缺点
- ✅ 1000 次/月真免费
- ✅ 多种分割模式可选
- ✅ Google 基础设施稳定
- ❌ 需绑定信用卡
- ❌ 像素级掩码不如 SAM 精细
方案三:Remove.bg API(背景移除专用分割)
简介
Remove.bg 专注于背景移除场景,基于深度学习模型自动检测前景主体并精确分割。API 接口简洁,一行代码即可完成抠图。
免费额度
- 每月 50 次免费预览(低分辨率)
- 通过 apishare.cc 注册 可获取更多 API 额度
- 高清输出需付费
代码示例
import requests
def remove_background(image_path, output_path):
"""Remove.bg 背景移除"""
response = requests.post(
'https://api.remove.bg/v1.0/removebg',
data={'size': 'auto'},
files={'image_file': open(image_path, 'rb')},
headers={'X-Api-Key': 'YOUR_API_KEY'}
)
if response.status_code == 200:
with open(output_path, 'wb') as f:
f.write(response.content)
print(f"背景移除完成!保存到 {output_path}")
else:
print(f"错误: {response.status_code} - {response.text}")
remove_background("photo.jpg", "photo_nobg.png")
优缺点
- ✅ 一行代码完成抠图
- ✅ 人像/商品分割质量极高
- ✅ 返回透明背景 PNG
- ❌ 免费额度较少(50 次/月)
- ❌ 仅支持背景移除,不支持多类分割
方案四:Roboflow Inference API
简介
Roboflow 平台提供端到端的计算机视觉工作流,支持自定义训练分割模型和预训练模型推理。免费层每月 1000 次推理调用。
免费额度
- 每月 1000 次推理免费
- 支持自定义模型部署
- 工作空间 10 GB 存储
代码示例
from roboflow import Roboflow
def roboflow_segment(image_path):
"""Roboflow 分割推理"""
rf = Roboflow(api_key="YOUR_API_KEY")
project = rf.workspace().project("your-segmentation-project")
model = project.version(1).model
result = model.predict(image_path).json()
for pred in result.get("predictions", []):
print(f"类别: {pred['class']}")
print(f"置信度: {pred['confidence']:.3f}")
# 分割多边形点
points = pred.get("points", [])
print(f"轮廓点数: {len(points)}")
return result
roboflow_segment("street_scene.jpg")
优缺点
- ✅ 支持自定义训练分割模型
- ✅ 可视化工具完善
- ✅ 1000 次/月免费
- ❌ 需自行训练或选用社区模型
- ❌ 复杂场景需大量标注数据
方案五:Python 自建(SAM2 + OpenCV)
简介
对于需要完全控制和无限制调用的场景,本地部署 SAM2(Segment Anything Model 2)是最佳选择。配合 OpenCV 可实现完整的分割工作流。
免费额度
- 完全免费,无调用限制
- 需要 GPU(建议 8GB+ 显存)或高性能 CPU
代码示例
import numpy as np
import cv2
from segment_anything import sam_model_registry, SamPredictor
def sam_segment(image_path, point_coords=None):
"""本地 SAM 模型分割"""
# 加载模型
sam = sam_model_registry["vit_h"](checkpoint="sam_vit_h.pth")
sam.to(device="cuda")
predictor = SamPredictor(sam)
# 读取图像
image = cv2.imread(image_path)
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
predictor.set_image(image_rgb)
# 使用点提示进行分割
if point_coords is None:
h, w = image.shape[:2]
point_coords = np.array([[w//2, h//2]])
point_labels = np.array([1]) # 1=前景
masks, scores, logits = predictor.predict(
point_coords=point_coords,
point_labels=point_labels,
multimask_output=True
)
# 选择最佳掩码
best_mask = masks[np.argmax(scores)]
print(f"生成 {len(masks)} 个候选掩码")
print(f"最佳置信度: {scores.max():.4f}")
print(f"分割区域像素数: {best_mask.sum()}")
# 可视化
overlay = image.copy()
overlay[best_mask] = [0, 255, 0] # 绿色高亮
result = cv2.addWeighted(image, 0.7, overlay, 0.3, 0)
cv2.imwrite("segment_result.jpg", result)
return best_mask
# 批量分割
def batch_segment(image_dir):
"""批量目录分割"""
import os
results = {}
for fname in os.listdir(image_dir):
if fname.endswith(('.jpg', '.png')):
path = os.path.join(image_dir, fname)
mask = sam_segment(path)
results[fname] = mask
print(f"已处理: {fname}")
return results
优缺点
- ✅ 无限制调用
- ✅ 像素级精度最高
- ✅ 数据完全本地,隐私安全
- ❌ 需要 GPU 硬件
- ❌ 首次部署配置较复杂
五方案横向对比
选型决策树
评估指标速查
| 指标 | 含义 | 计算方式 | 适用场景 |
|---|---|---|---|
| mIoU | 平均交并比 | Σ(IoU_i)/N | 语义分割 |
| mAP | 平均精度均值 | ∫Precision·dRecall | 实例分割 |
| Pixel Accuracy | 像素准确率 | 正确像素/总像素 | 快速评估 |
| Dice | Dice 系数 | 2 | A∩B |
| Boundary F1 | 边界 F1 | 边界精度召回调和 | 轮廓质量 |
常见问题
Q1:图像分割和目标检测有什么区别?
目标检测输出矩形边界框,图像分割输出像素级掩码。分割精度更高但计算量更大。实际项目中,常先用目标检测定位物体,再用分割细化边界。
Q2:SAM 模型需要 GPU 吗?
在线 API 调用不需要本地 GPU。本地部署 SAM ViT-H 建议 8GB+ 显存,SAM ViT-B 可在 4GB 显存运行。CPU 推理可行但速度较慢(单图 10-30 秒)。
Q3:如何评估分割质量?
最常用 mIoU(平均交并比),值越接近 1 表示分割越精确。如果关注边界质量,可使用 Boundary F1 指标。医学影像场景常用 Dice 系数。
Q4:免费额度用完了怎么办?
可以组合使用多个方案实现配额轮转。也可通过 apishare.cc 注册 获取统一 API 网关,自动在多个 provider 间负载均衡,避免单点限流。
总结
图像分割是计算机视觉从"识别"走向"理解"的关键一步。5 种免费方案覆盖了从低频原型验证到高频生产部署的全场景:
- 快速验证:Hugging Face SAM(零配置,零样本分割)
- 生产可用:Google Vision(1000 次/月稳定免费)
- 垂直场景:Remove.bg(人像/商品抠图一键完成)
- 自定义需求:Roboflow(支持训练专属分割模型)
- 无限制调用:SAM2 本地部署(像素级精度最高)
建议从 Hugging Face SAM 开始原型验证,确认需求后再迁移到 Google Vision 或本地部署。更多免费 API 资源请持续关注 apishare.cc 免费API目录,我们每日更新实测教程。
进阶实战:电商商品自动抠图工作流
在实际电商场景中,每天可能有上千张商品照片需要处理。下面演示一个完整的批量抠图工作流,结合目标检测定位商品 + SAM 分割精确抠图:
import os
import time
import requests
import numpy as np
from PIL import Image
import io
class ProductSegmentationPipeline:
"""电商商品批量抠图工作流"""
def __init__(self, hf_token):
self.hf_token = hf_token
self.det_url = "https://api-inference.huggingface.co/models/facebook/detr-resnet-50"
self.seg_url = "https://api-inference.huggingface.co/models/facebook/sam-vit-base"
def detect_products(self, image_path):
"""第一步:目标检测定位商品"""
with open(image_path, "rb") as f:
data = f.read()
response = requests.post(
self.det_url,
headers={"Authorization": f"Bearer {self.hf_token}"},
json={"inputs": data}
)
if response.status_code == 200:
results = response.json()
boxes = []
for item in results:
if item.get("score", 0) > 0.7: # 置信度阈值
box = item["box"]
boxes.append({
"label": item["label"],
"box": [box["xmin"], box["ymin"], box["xmax"], box["ymax"]],
"score": item["score"]
})
return boxes
return []
def segment_product(self, image_path, box):
"""第二步:SAM 精确分割"""
with open(image_path, "rb") as f:
data = f.read()
# 使用检测框作为提示
response = requests.post(
self.seg_url,
headers={"Authorization": f"Bearer {self.hf_token}"},
json={
"inputs": data,
"parameters": {"input_boxes": [box]}
}
)
if response.status_code == 200:
masks = response.json()
if masks and len(masks) > 0:
return masks[0].get("mask")
return None
def remove_background(self, image_path, mask):
"""第三步:基于掩码移除背景"""
image = Image.open(image_path).convert("RGBA")
mask_array = np.array(mask)
# 创建透明背景
result = np.array(image)
result[:, :, 3] = (mask_array * 255).astype(np.uint8)
return Image.fromarray(result)
def process_batch(self, input_dir, output_dir):
"""批量处理目录"""
os.makedirs(output_dir, exist_ok=True)
stats = {"total": 0, "success": 0, "failed": 0}
for fname in os.listdir(input_dir):
if not fname.endswith(('.jpg', '.png', '.jpeg')):
continue
stats["total"] += 1
image_path = os.path.join(input_dir, fname)
try:
# 检测商品
boxes = self.detect_products(image_path)
if not boxes:
print(f"[跳过] {fname}: 未检测到商品")
stats["failed"] += 1
continue
# 分割最大商品
best_box = max(boxes, key=lambda x: x["score"])["box"]
mask = self.segment_product(image_path, best_box)
if mask:
result = self.remove_background(image_path, mask)
output_path = os.path.join(output_dir, f"nobg_{fname}")
result.save(output_path)
print(f"[成功] {fname} -> {output_path}")
stats["success"] += 1
else:
stats["failed"] += 1
except Exception as e:
print(f"[错误] {fname}: {e}")
stats["failed"] += 1
time.sleep(1) # 速率限制
print(f"\n批量处理完成: {stats}")
return stats
# 使用示例
pipeline = ProductSegmentationPipeline("YOUR_HF_TOKEN")
pipeline.process_batch("input_images/", "output_images/")
不同分割任务的模型选型指南
根据具体任务类型选择最合适的模型和方案,能大幅提升效果和效率:
语义分割模型对比
| 模型 | 架构 | mIoU | 速度 | 适合场景 |
|---|---|---|---|---|
| SAM ViT-H | Transformer | 通用零样本 | 中等 | 通用分割 |
| SAM ViT-B | Transformer | 通用零样本 | 快 | 移动端 |
| SegFormer | Transformer | 高 | 快 | 场景理解 |
| U2Net | U-Net | 中 | 快 | 显著性分割 |
| DeepLab v3+ | CNN | 高 | 中等 | 精确分割 |
实例分割模型对比
| 模型 | mAP | 速度 | 免费可用 | 适合场景 |
|---|---|---|---|---|
| Mask R-CNN | 高 | 中等 | ✅ 开源 | 通用实例 |
| YOLOv8-Seg | 中高 | 极快 | ✅ 开源 | 实时分割 |
| SAM (实例模式) | 高 | 中等 | ✅ 开源 | 零样本 |
| DETR Panoptic | 高 | 中等 | ✅ 开源 | 全景分割 |
速率限制与配额管理策略
免费 API 普遍存在速率限制,合理规划配额能最大化免费额度的利用率:
| 平台 | 免费额度 | 速率限制 | 超限策略 |
|---|---|---|---|
| Hugging Face | 无硬性限制 | 30s 超时 | 排队等待 |
| Google Vision | 1000 次/月 | 10 QPS | 429 限流 |
| Remove.bg | 50 次/月 | 1 QPS | 402 付费 |
| Roboflow | 1000 次/月 | 无硬限 | 配额耗尽 |
多平台配额轮转示例代码:
import itertools
class SegmentationLoadBalancer:
"""多平台分割 API 负载均衡"""
def __init__(self):
self.providers = itertools.cycle([
("huggingface", self._hf_segment),
("google", self._google_segment),
("roboflow", self._roboflow_segment),
])
self.usage = {"huggingface": 0, "google": 0, "roboflow": 0}
self.limits = {"huggingface": float('inf'), "google": 1000, "roboflow": 1000}
def segment(self, image_path):
"""轮询调用,自动切换 provider"""
for _ in range(len(self.providers)):
name, func = next(self.providers)
if self.usage[name] < self.limits[name]:
try:
result = func(image_path)
if result:
self.usage[name] += 1
return {"provider": name, "result": result}
except Exception as e:
print(f"Provider {name} failed: {e}")
continue
raise Exception("所有免费配额已耗尽!")
安全与隐私注意事项
使用云端图像分割 API 时,需注意数据隐私合规:
- 敏感图像不上传:医疗影像、身份证件等敏感数据应使用本地 SAM 部署
- 数据传输加密:确保 API 请求使用 HTTPS 加密传输
- 结果存储安全:分割结果可能包含图像特征,存储时需加密
- GDPR 合规:欧盟用户数据需确认服务商数据处理协议
总结与最佳实践
图像分割技术正从实验室走向大规模商用。基于本教程的 5 种免费方案,我们推荐以下落地路径:
- 原型验证阶段(0-1000 次/月):Hugging Face SAM 零配置上手,验证分割效果
- 小规模生产(1000-3000 次/月):Google Vision + Roboflow 配额轮转
- 大规模生产(>3000 次/月):本地 SAM2 部署,无限调用
- 垂直场景:电商抠图用 Remove.bg,医学分割用 SAM2 + Dice 评估
更多免费 API 资源请持续关注 apishare.cc 免费API目录,我们每日更新实测教程。新用户可前往 注册页面 获取专属开发者密钥。