Yolov8/Yolov11实例分割训练自有数据集
一、实例分割标注软件Labelme
下载地址: 绿色目标检测标注软件LabelImg和实例分割标注软件Labelme资源-CSDN下载
打开Labelme软件可对图像进行标注,选择“创建多边形”,对物体进行分割信息标注。
注完成后,点击“Save”,保存保存标注信息,生成和图片同名的json文件;
yolov8和yolov11的实例分割需将json转为yolo的txt格式的文件转换代码如下:label_format-seg.py
import jsonimport os label_to_class_id = { \"fod\": 0, # 从0开始 # 其他类别...} def convert_labelme_json_to_yolo(json_file, output_dir): try: with open(json_file, \'r\') as f: labelme_data = json.load(f) img_width = labelme_data[\"imageWidth\"] img_height = labelme_data[\"imageHeight\"] file_name = os.path.splitext(os.path.basename(json_file))[0] txt_path = os.path.join(output_dir, f\"{file_name}.txt\") with open(txt_path, \'w\') as txt_file: for shape in labelme_data[\'shapes\']: label = shape[\'label\'] points = shape[\'points\'] if not points: continue class_id = label_to_class_id.get(label) if class_id is None: print(f\"Warning: 跳过未定义标签 \'{label}\'\") continue # 检查多边形是否闭合 if points[0] != points[-1]: points.append(points[0]) normalized = [(x / img_width, y / img_height) for x, y in points] line = f\"{class_id} \" + \" \".join(f\"{x:.6f} {y:.6f}\" for x, y in normalized) txt_file.write(line + \"\\n\") except Exception as e: print(f\"处理文件 {json_file} 时出错: {str(e)}\") if __name__ == \"__main__\": json_dir = \"data-seg/json\" # labelme标注存放的目录 output_dir = \"data-seg/labels\" # 输出目录 if not os.path.exists(output_dir): os.makedirs(output_dir) for json_file in os.listdir(json_dir): if json_file.endswith(\".json\"): json_path = os.path.join(json_dir, json_file) convert_labelme_json_to_yolo(json_path, output_dir)
具体应用时,该需注意修改的地方包括:
1)首先修改类别映射;
2)需要修改json_dir 的路径,它用来存放 LabelMe标注的JSON文件;
3)需要修改output_dir 的路径,输出的YOLO格式txt文件目录;
4)img_width和img_height,默认是640,分别指图片宽度和高度,根据实际图像尺寸修改即可。
运行代码,会生成用于YOLO11分割的txt标签文件。
二、实例分割模型训练
建立实例分割python文件train-seg.py,代码内容如下:
from ultralytics import YOLO if __name__ == \'__main__\': # 初始训练 model = YOLO(\"./cfg/models/11/yolo11-seg.yaml\").load(\"yolo11n-seg.pt\") # 加载预训练模型,如果本地没有会自动下载 # 进行训练 results = model.train(data=\"./datasets/data-seg.yaml\", epochs=100, imgsz=640, batch=4, workers=8)
三、数据集yaml配置文件修改
在路径ultralytics/datasets/data-seg.yaml
yaml文件中的path,需要根据实际数据路径进行修改,指定数据集的路径。
四、YOLO11模型结构配置文件
路径ultralytics/cfg/models/11/yolo11-seg.yaml
注意需修改nc: 80 # number of classes
五、训练
激活虚拟环境:conda activate Y11
执行训练Yolov11的实例分割训练命令: python .\\train-segv11.py
或执行训练Yolov8的实例分割训练命令: python .\\train-segv8.py
六、推理
执行推理pyhton文件命令,predict-seg.py文件内容如下
from ultralytics import YOLO # 加载训练的模型model = YOLO(\'runs/segment/train3/weights/best.pt\') img_list = [\'testfiles/3.jpg\'] for img in img_list: # 运行推理,并附加参数 save:是否保存文件 retina_masks:返回高分辨率分割掩码 model.predict(img, save=True, conf=0.5, retina_masks=True)
七、C++部署
1.首先转换为ONNX文件