
大家好,我是 Echo_Wish。
前几天一个做电商的朋友找我,说老板让他把商品图里的人像自动抠出来换背景,他对着 PS 抠了一下午,眼睛都花了。我说你这不就是图像分割吗,让模型干啊。他问我用啥,我说 DeepLabv3,经典、稳、好部署,今天咱就把它从头到尾聊透。
分类模型回答的是"这图里有啥",检测模型回答的是"东西在哪个框里",分割回答的是"每个像素属于谁"。
一张图 520×520,就是 27 万多个像素,模型要给每一个像素打标签:这是人、这是狗、这是背景。所以分割的输出不是一个类别,而是一张和原图一样大的"标签地图"。
不讲公式,只讲思路。
传统卷积网络一路下采样,图越缩越小,语义是抽象出来了,但边缘细节也丢光了。DeepLab 系列的招数叫空洞卷积(Atrous Conv):卷积核里"留白",不增加参数,却能看到更大的范围,所以不用把图缩得太狠,细节保住了,视野也够大。
再配上 ASPP 模块,用不同空洞率的卷积并联,同时看"近处"和"远处",大物体小物体一起照顾。
我的感受是:DeepLabv3 不是最新最炫的,但它结构清晰、论文好读、torchvision 里开箱即用。想入门分割,这是一块很好的敲门砖。
先装环境:
pip install torch torchvision pillow numpy然后直接上:
import torch
import numpy as np
from PIL import Image
from torchvision.models.segmentation import (
deeplabv3_resnet50, DeepLabV3_ResNet50_Weights
)
weights = DeepLabV3_ResNet50_Weights.DEFAULT
model = deeplabv3_resnet50(weights=weights).eval()
preprocess = weights.transforms() # 官方预处理,别自己瞎写
categories = weights.meta["categories"] # 21 个类别名
img = Image.open("demo.jpg").convert("RGB")
x = preprocess(img).unsqueeze(0) # [1, 3, H, W]
with torch.inference_mode():
logits = model(x)["out"] # [1, 21, H, W]
mask = logits.argmax(1)[0].numpy() # [H, W],每个像素一个类别 id
print("图里有:", [categories[i] for i in np.unique(mask)])这里有两个关键点,我踩过坑,必须说:
model(x) 返回的是个字典,真正的结果在 ["out"] 里,还有个 aux 是训练时的辅助分支,推理不用管。argmax(1) 就是在 21 个通道里挑分数最高的,分割的本质就是"逐像素分类"。只打印类别没意思,咱把它画出来:
def voc_palette(n=21):
palette = np.zeros((n, 3), dtype=np.uint8)
for i in range(n):
c, r, g, b = i, 0, 0, 0
for j in range(8):
r |= ((c >> 0) & 1) << (7 - j)
g |= ((c >> 1) & 1) << (7 - j)
b |= ((c >> 2) & 1) << (7 - j)
c >>= 3
palette[i] = [r, g, b]
return palette
def overlay(img, mask, alpha=0.5):
color = voc_palette()[mask] # [h, w, 3]
color = Image.fromarray(color).resize(img.size, Image.NEAREST)
return Image.blend(img, color, alpha)
overlay(img, mask).save("overlay.png")再来朋友最想要的功能,抠人(VOC 里 person 的 id 是 15):
def cutout_person(img, mask, cls_id=15):
m = (mask == cls_id).astype(np.uint8) * 255
m = Image.fromarray(m).resize(img.size, Image.NEAREST) # 掩码还原到原图尺寸
out = img.convert("RGBA")
out.putalpha(m)
return out
cutout_person(img, mask).save("person.png")注意那句 resize(img.size, Image.NEAREST)。预处理会把图缩到 520 左右,掩码是小尺寸的,必须还原回原图大小,而且必须用最近邻插值,用双线性的话类别 id 会被插值成一堆不存在的"小数类别",边缘全花。
预训练模型只认 21 类,业务里你要分的可能是"裂缝"、"皮损"、"商品主体"。这时候别从零训练,冻住或微调骨干,换掉分类头:
from torchvision.models.segmentation.deeplabv3 import DeepLabHead
num_classes = 3 # 比如:背景 / 商品 / 阴影
model = deeplabv3_resnet50(weights=weights)
model.classifier = DeepLabHead(2048, num_classes)
model.aux_classifier = None # 辅助头不要了,省事损失函数用 CrossEntropyLoss 就行,标签是 [B, H, W] 的整数图。说句掏心窝子的话:数据标注质量比模型选型重要十倍。我见过太多人纠结用 v3 还是 v3+,结果标注边缘都是糊的,模型再强也白搭。
模型在 notebook 里跑通,只完成了 30%。真正考验人的是上线。我的路线是:PyTorch → ONNX → onnxruntime → FastAPI,不依赖 torch,镜像小、启动快。
先导出 ONNX:
import torch
class Wrapper(torch.nn.Module):
def __init__(self, m):
super().__init__()
self.m = m
def forward(self, x):
return self.m(x)["out"] # 把字典输出拍平成张量,ONNX 才好导
dummy = torch.randn(1, 3, 520, 520)
torch.onnx.export(
Wrapper(model).eval(), dummy, "deeplabv3.onnx",
input_names=["input"], output_names=["logits"],
dynamic_axes={"input": {0: "batch", 2: "h", 3: "w"},
"logits": {0: "batch", 2: "h", 3: "w"}},
opset_version=17,
)再写服务(app.py):
import io
import numpy as np
import onnxruntime as ort
from PIL import Image
from fastapi import FastAPI, UploadFile
from fastapi.responses import Response
app = FastAPI()
sess = ort.InferenceSession("deeplabv3.onnx", providers=["CPUExecutionProvider"])
MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32)
STD = np.array([0.229, 0.224, 0.225], dtype=np.float32)
def prepare(img: Image.Image, size=520):
img = img.resize((size, size), Image.BILINEAR)
arr = (np.asarray(img, dtype=np.float32) / 255.0 - MEAN) / STD
return arr.transpose(2, 0, 1)[None] # [1, 3, H, W]
@app.post("/segment")
async def segment(file: UploadFile):
img = Image.open(io.BytesIO(await file.read())).convert("RGB")
logits = sess.run(None, {"input": prepare(img)})[0]
mask = logits.argmax(1)[0].astype(np.uint8)
mask_img = Image.fromarray(mask).resize(img.size, Image.NEAREST)
buf = io.BytesIO()
mask_img.save(buf, format="PNG")
return Response(buf.getvalue(), media_type="image/png")pip install fastapi uvicorn onnxruntime python-multipart
uvicorn app:app --host 0.0.0.0 --port 8000
curl -F "file=@demo.jpg" http://localhost:8000/segment -o mask.png到这一步,你的分割服务就能被别人调用了。
第一,预处理一致性是头号杀手。 训练时用什么均值方差、什么缩放方式,部署时必须一模一样。我见过线上效果比本地差一大截,查了两天,结果是 RGB 和 BGR 搞反了。
第二,ResNet50 版的 DeepLabv3 不算轻。 纯 CPU 上单张图跑个几百毫秒到一两秒很正常。要提速,可以换 MobileNet 骨干的版本(torchvision 里有 deeplabv3_mobilenet_v3_large),或者上 GPU、做量化,别硬扛。
第三,别神化模型。 头发丝、半透明物体、复杂背景,它照样会翻车。需要发丝级抠图的话,分割结果只能当"粗掩码",后面还得接 matting 模型。
说点感想。这两年大家都在追 SAM、追各种大模型,但我越来越觉得:能把一个经典模型从数据、训练一路干到稳定上线的人,比只会跑 demo 的人值钱得多。DeepLabv3 不新,但它把"分割该怎么做"这件事讲得明明白白,吃透了它,再看 SegFormer、Mask2Former 就是换汤不换药。
最后送大家一句话:模型是用来解决问题的,不是用来炫技的。 朋友那个抠人需求,我用上面这套半天就搞定了,老板满意,他也不用再对着 PS 熬夜。
好了,今天就聊到这。代码拿去跑跑看,遇到坑欢迎留言,咱们评论区见。
我是 Echo_Wish,下期再聊。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。