1. Python调用
模型预测:
def segment_predict():
model = YOLO('../weights/segment/yolo11n-seg.pt')
print(model)
results = model('../ultralytics/assets/bus.jpg')
if not os.path.exists(results[0].save_dir):
os.makedirs(results[0].save_dir)
for result in results:
filename = result.path.split("\\")[-1]
filedir = result.save_dir + "\\" + filename
result.save(filedir)
运行结果:
模型训练,同样基于coco8数据集
# Load a model
model = YOLO("yolo11n-seg.yaml").load("yolo11n.pt") # build from YAML and transfer weights
# Train the model
results = model.train(data="coco8-seg.yaml", epochs=100, imgsz=640, device="0")
# Evaluate model performance on the validation set
metrics = model.val()
# Perform object detection on an image
results = model("../ultralytics/assets/bus.jpg")
results[0].show()
# Export the model to ONNX format
path = model.export(format="onnx") # return path to exported model
2. 网络结构图
分割的网络结构图主体部分与检测部分相同,只是Detect部分增加了Proto与Pred_mask而已。
图2-1 yolo11-segment网络结构图
3. 损失函数
3.1 损失函数定位
与Detection部分相同,训练函数都是调用BaseTrainer中的train函数,其中不同的是训练类与模型类都是继承自Detection中的类,另外分割的损失为类v8SegmentationLoss,用流程图定位损失函数的走向如图3-1所示,其中损失函数以类的方式定义。
图3-1 yolo11-segment的损失函数定位
3.2 损失函数具体分析
(1) 前向推理与构造anchor
segment的前向推理包括detection的feats,segment的pred_mask和proto,具体代码如下所示。其中anchor的构建如