解决Ultralytics-YOLOv8-seg 由pt文件导出onnx后精度损失

解决Ultralytics-YOLOv8-seg 由pt文件导出onnx后精度损失 前言使用Ultralytics 8.1.34中yolov8n-seg进行训练并到处onnx模型后onnx模型精度对比pt文件有明显损失具体表现为检测到的分割区域会出现缺少情况。如下图所示pt文件推理正常分割图片onnx模型推理分割图片产生该问题原因(参考注释)classDetect(nn.Module):YOLOv8 Detect head for detection models.dynamicFalse# force grid reconstructionexportFalse# export modeshapeNoneanchorstorch.empty(0)# initstridestorch.empty(0)# initdef__init__(self,nc80,ch()):Initializes the YOLOv8 detection layer with specified number of classes and channels.super().__init__()self.ncnc# number of classesself.nllen(ch)# number of detection layersself.reg_max16# DFL channels (ch[0] // 16 to scale 4/8/12/16/20 for n/s/m/l/x)self.noncself.reg_max*4# number of outputs per anchorself.stridetorch.zeros(self.nl)# strides computed during buildc2,c3max((16,ch[0]//4,self.reg_max*4)),max(ch[0],min(self.nc,100))# channelsself.cv2nn.ModuleList(nn.Sequential(Conv(x,c2,3),Conv(c2,c2,3),nn.Conv2d(c2,4*self.reg_max,1))forxinch)self.cv3nn.ModuleList(nn.Sequential(Conv(x,c3,3),Conv(c3,c3,3),nn.Conv2d(c3,self.nc,1))forxinch)self.dflDFL(self.reg_max)ifself.reg_max1elsenn.Identity()......defdecode_bboxes(self,bboxes,anchors):Decode bounding boxes.ifself.export:returndist2bbox(bboxes,anchors,xywhFalse,dim1)# 导出onnx时xywh入参为Falsereturndist2bbox(bboxes,anchors,xywhTrue,dim1)# pt训练推理时xywh入参为Truedefdist2bbox(distance,anchor_points,xywhTrue,dim-1):Transform distance(ltrb) to box(xywh or xyxy).assert(distance.shape[dim]4)lt,rbdistance.split([2,2],dim)x1y1anchor_points-lt x2y2anchor_pointsrbifxywh:# pt训练推理时的代码实现c_xy(x1y1x2y2)/2whx2y2-x1y1returntorch.cat((c_xy,wh),dim)# xywh bboxreturntorch.cat((x1y1,x2y2),dim)# 导出onnx时代码实现xywh的入参不同导致模型结构出现不同需要将入参部分全部置为True即可。