当前位置: 首页 > news >正文

【yolo11自定义实例分割训练集教程】

yolo11使用教程(docker篇)

本文介绍如何在docker中部署yolo11以及如何对实例分割进行训练


文章目录

  • yolo11使用教程(docker篇)
  • 先决条件
  • 一、安装yolo
  • 二、使用自定义训练实例分割
    • 1.构建自定义数据
  • 总结


先决条件

确保系统中已安装 Docker。如果没有,可以从Docker 网站下载并安装。 确保系统已安装NVIDIA GPU 和NVIDIA
驱动程序。

过NVIDIA 支持设置 Docker
首先,运行NVIDIA 驱动程序,验证是否已正确安装:

nvidia-smi
  • 有以下输出则说明已经安装
    在这里插入图片描述
  • 没有输出,则需要装NVIDIA Docker 运行时,安装NVIDIA Docker 运行时,以便在 Docker 容器中启用GPU 支持:
# Add NVIDIA package repositories
curl -s -L https://nvidia.github.io/nvidia-docker/gpgkey | sudo apt-key add -
distribution=$(lsb_release -cs)
curl -s -L https://nvidia.github.io/nvidia-docker/$distribution/nvidia-docker.list | sudo tee /etc/apt/sources.list.d/nvidia-docker.list

# Install NVIDIA Docker runtime
sudo apt-get update
sudo apt-get install -y nvidia-docker2

# Restart Docker service to apply changes
sudo systemctl restart docker
  • 使用 Docker 验证NVIDIA 运行时
    运行 docker info | grep -i runtime 以确保 nvidia 出现在运行时列表中:
docker info | grep -i runtime

一、安装yolo

  1. 拉取yolo镜像,yolo11在github上更名为ultralytics
docker pull ultralytics/ultralytics:latest
  1. 运行容器
  • 使用命令运行,但是需要记住指令
docker run -it --ipc=host --gpus all
  • 使用docker-compose 运行
    • 下载yaml文件
    • 运行指令
version: "2.3"
services:
  detectron2:
    image: ultralytics/ultralytics:latest
    container_name: zx_yolo
    runtime: nvidia    # 添加此行,确保 GPU 可用
    shm_size: "8gb"
    ipc: host
    ulimits:
      memlock: -1
      stack: 67108864
    volumes:
      - /app/ai/yolo/code:/home/zx/code
    environment:
      - DISPLAY=$DISPLAY
      - NVIDIA_VISIBLE_DEVICES=all
      - NVIDIA_DRIVER_CAPABILITIES=compute,utility  # 重要:增强 GPU 功能
    stdin_open: true
    tty: true
docker-compose -p yolo11 up -d

二、使用自定义训练实例分割

1.构建自定义数据

  1. yolo10数据集结构
├── ultralytics
└── datasets
	└── zx
	    └── images
	    	└── train
	    	└── val
	    └── labels
	        └── train
	    	└── val
  1. 使用labelme(查看labelme安装教程)标注,将标注的照片一部分作为训练集放在train文件夹下面,一部分作为验证集放在val文件夹下,验证集尽量平均,每个类别的数量平均,且验证集达到训练集数量的10%左右。

  2. 将labelme的标注文件转为yolo支持的格式,使用以下脚本

  • 实例分割的json格式:<class-index> <x1> <y1> <x2> <y2> ... <xn> <yn>
import json
import os
 
'''
任务:实例分割,labelme的json文件, 转txt文件
Ultralytics YOLO format
<class-index> <x1> <y1> <x2> <y2> ... <xn> <yn>
'''
 
# 类别映射表,定义每个类别对应的ID
label_to_class_id = {
    "person": 0,
    "car": 1,
    "handbag": 2,
    "bottle": 3
    # 根据需要添加更多类别
}
 
# json转txt
def convert_labelme_json_to_yolo(json_file, output_dir, img_width, img_height):
    with open(json_file, 'r', encoding='utf-8') as f:
        labelme_data = json.load(f)
    
    # 获取文件名(不含扩展名)
    file_name = os.path.splitext(os.path.basename(json_file))[0]
    
    # 输出的txt文件路径
    txt_file_path = os.path.join(output_dir, f"{file_name}.txt")
 
    with open(txt_file_path, 'w') as txt_file:
        for shape in labelme_data['shapes']:
            label = shape['label']
            points = shape['points']
 
            # 根据类别映射表获取类别ID,如果类别不在映射表中,跳过该标签
            class_id = label_to_class_id.get(label)
            if class_id is None:
                print(f"Warning: Label '{label}' not found in class mapping. Skipping.")
                continue
 
            # 将点的坐标归一化到0-1范围
            normalized_points = [(x / img_width, y / img_height) for x, y in points]
 
            # 写入类别ID
            txt_file.write(f"{class_id}")
 
            # 写入多边形掩膜的所有归一化顶点坐标
            for point in normalized_points:
                txt_file.write(f" {point[0]:.6f} {point[1]:.6f}")
            txt_file.write("\n")
 
if __name__ == "__main__":
    json_dir = r"E:/zxlz/project/AI/data/yolouse/val"  # 替换为LabelMe标注的JSON文件目录
    output_dir = os.path.join(json_dir, 'out')  # 输出的YOLO格式txt文件目录
    img_width = 640   # 图像宽度,根据实际图片尺寸设置
    img_height = 512  # 图像高度,根据实际图片尺寸设置
 
    # 创建输出文件夹
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
 
    # 批量处理所有json文件
    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, img_width, img_height)


  • 实例检测的json格式:<class-index> <Minx> <Miny> width height
import os
import json
import glob

# LabelMe JSON 数据路径
json_dir = r"E:\zxlz\project\AI\yolo\exchange\val02juxing"  # 替换为LabelMe标注的JSON文件目录
output_dir = os.path.join(json_dir, 'out')  # 输出的YOLO格式txt文件目录

# 创建输出目录
os.makedirs(output_dir, exist_ok=True)

# 类别映射(根据实际情况修改)
class_map = {
    "person": 0,
    "car": 1,
    "handbag": 2,
    "bottle": 3
    # 根据需要添加更多类别
}

# 转换函数
def convert_labelme_json_to_yolo(json_path, output_dir, img_width, img_height):
    with open(json_path, "r", encoding="utf-8") as f:
        labelme_data = json.load(f)

    # 获取标签文件名
    output_file = os.path.join(output_dir, os.path.splitext(os.path.basename(json_path))[0] + ".txt")

    with open(output_file, "w") as yolo_file:
        for shape in labelme_data["shapes"]:
            label = shape["label"]
            points = shape["points"]

            # 获取矩形框坐标
            x_min, y_min = points[0]
            x_max, y_max = points[1]

            # 计算 YOLO 格式的坐标和尺寸(归一化)
            x_center = ((x_min + x_max) / 2) / img_width
            y_center = ((y_min + y_max) / 2) / img_height
            width = (x_max - x_min) / img_width
            height = (y_max - y_min) / img_height

            # 写入 YOLO 标签文件
            yolo_file.write(f"{class_map[label]} {x_center:.6f} {y_center:.6f} {width:.6f} {height:.6f}\n")

# 读取所有 JSON 文件并转换
for json_file in glob.glob(os.path.join(json_dir, "*.json")):
    # 读取图像尺寸 (可根据你的项目需求调整)
    img_width, img_height = 640, 480
    convert_labelme_json_to_yolo(json_file, output_dir, img_width, img_height)

print("✅ 转换完成!")

  1. 编辑自己的yml文件
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license

# PASCAL VOC dataset http://host.robots.ox.ac.uk/pascal/VOC by University of Oxford
# Documentation: # Documentation: https://docs.ultralytics.com/datasets/detect/voc/
# Example usage: yolo train data=VOC.yaml
# parent
# ├── ultralytics
# └── datasets
#     └── VOC  ← downloads here (2.8 GB)

# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
path: /home/zx/code/datasets/
train: # train images (relative to 'path')  16551 images
  - images/train01
val: # val images (relative to 'path')  4952 images
  - images/val01

# Classes
names:
  0: person
  1: car
  2: handbag
  3: bottle
  1. 训练模型train.py
import sys
sys.path.append('/ultralytics')
from ultralytics import YOLO

# Load a model
model = YOLO("yolo11-seg.yaml")  # build a new model from YAML
# model = YOLO("yolo11n-seg.pt")  # load a pretrained model (recommended for training)
# model = YOLO("yolo11n-seg.yaml").load("yolo11n.pt")  # build from YAML and transfer weights

# Train the model
results = model.train(data="/home/zx/code/datasets/zx.yaml", epochs=100, imgsz=640)
  • 输出部分内容如下
    在这里插入图片描述在这里插入图片描述
  1. 使用模型对测试照片输出结果predict.py
import sys
sys.path.append('/ultralytics')
from ultralytics import YOLO

# 加载模型
model = YOLO("/ultralytics/runs/segment/train4/weights/best.pt")

# 进行预测
results = model.predict(
    source="/home/zx/code/test/source",   # 输入数据路径
    imgsz=640,                     # 图像大小
    conf=0.3,                      # 置信度阈值
    project="/home/zx/code/test/out",  # 输出结果的项目路径
    name="result",                  # 结果文件夹名称
    save=True
)

  1. 导出模型export.py
import sys
sys.path.append('/ultralytics')
from ultralytics import YOLO

# Load a model
model = YOLO("/ultralytics/runs/segment/train4/weights/best.pt")  # load a custom trained model

# Export the model
model.export(format="onnx")

总结

  • 一定要确保训练时使用的是GPU,训练过程会显示GPU使用率(或者在容器中使用nvidia-smi指令查看显卡使用情况),如果使用的cpu那么你的电脑可能会顶不住卡死

相关文章:

  • 2.2.盈亏平衡分析
  • webstorm调试模式报错:Cannot detect a launch configuration
  • 快速入手:Nacos融合SpringCloud成为注册配置中心
  • MySQL 入门大全:常用函数
  • Flink启动任务
  • LVS的 NAT 模式实现 3 台RS的轮询访问
  • 【IntelliJ IDEA快速绑定Maven配置指南】
  • 2025年3月23日坚持写原创的第24天
  • 华为HCIE网络工程师培训选机构攻略
  • 算法题(105):小猫爬山
  • C++ 哈希计数器
  • 《论语别裁》第02章 为政(03)星辰知多少
  • 红帽认证工程师价值
  • 补码详细分析
  • 在Dify中使用Echarts生成一个图表
  • LabVIEW FPGA与Windows平台数据滤波处理对比
  • Leetcode 3493. Properties Graph
  • SpringCloud-consul
  • 好用的Markdown阅读编辑器Typora破解记录
  • Midscene.js自然语言驱动的网页自动化全指南
  • 常州新型碳材料集群产值近二千亿,请看《浪尖周报》第24期
  • “80后”萍乡市安源区区长邱伟,拟任县(区)委书记
  • 东部沿海大省浙江,为何盯上内河航运?
  • 浙江省委金融办原副主任潘广恩被“双开”
  • 广西:坚决拥护党中央对蓝天立进行审查调查的决定
  • MSCI中国指数5月调整:新增5只A股、1只港股