yolo训练自己的模型(附完整代码)

用python写的,期间遇到的问题解决方法在另一篇博文里,需要的话可以自行查看

1、准备图像集合

2、使用labelImg标注图像(我标注的是屋顶和车顶),标注后生成的.txt文件存到labels文件夹下(下面会给出文件目录)

3、运行split.py,把图像和标注数据放到合适的地方

split.py

# -*- coding: utf-8 -*-
"""
Created on Fri Dec 29 14:06:08 2023

@author: DIY-PC
"""

import os
import random
import shutil

# 原数据集目录
root_dir = 'D:/python/trainproject/dataset'
# 划分比例
train_ratio = 0.8
valid_ratio = 0.1
test_ratio = 0.1

# 设置随机种子
random.seed(42)

# 拆分后数据集目录
split_dir = 'D:/python/trainproject/dataset/images'
os.makedirs(os.path.join(split_dir, 'train/images'), exist_ok=True)
os.makedirs(os.path.join(split_dir, 'train/labels'), exist_ok=True)
os.makedirs(os.path.join(split_dir, 'valid/images'), exist_ok=True)
os.makedirs(os.path.join(split_dir, 'valid/labels'), exist_ok=True)
os.makedirs(os.path.join(split_dir, 'test/images'), exist_ok=True)
os.makedirs(os.path.join(split_dir, 'test/labels'), exist_ok=True)

# 获取图片文件列表
image_files = os.listdir(os.path.join(root_dir, 'images'))
label_files = os.listdir(os.path.join(root_dir, 'labels'))

# 随机打乱文件列表
combined_files = list(zip(image_files, label_files))
random.shuffle(combined_files)
image_files_shuffled, label_files_shuffled = zip(*combined_files)

# 根据比例计算划分的边界索引
train_bound = int(train_ratio * len(image_files_shuffled))
valid_bound = int((train_ratio + valid_ratio) * len(image_files_shuffled))

# 将图片和标签文件移动到相应的目录
for i, (image_file, label_file) in enumerate(zip(image_files_shuffled, label_files_shuffled)):
    if i < train_bound:
        shutil.move(os.path.join(root_dir, 'images', image_file), os.path.join(split_dir, 'train/images', image_file))
        shutil.move(os.path.join(root_dir, 'labels', label_file), os.path.join(split_dir, 'train/labels', label_file))
    elif i < valid_bound:
        shutil.move(os.path.join(root_dir, 'images', image_file), os.path.join(split_dir, 'valid/images', image_file))
        shutil.move(os.path.join(root_dir, 'labels', label_file), os.path.join(split_dir, 'valid/labels', label_file))
    else:
        shutil.move(os.path.join(root_dir, 'images', image_file), os.path.join(split_dir, 'test/images', image_file))
        shutil.move(os.path.join(root_dir, 'labels', label_file), os.path.join(split_dir, 'test/labels', label_file))

4、创建roof.yaml文件,指定模型训练元数据的位置(上面准备好的文件夹train,valid,test下的数据)

# Helmet
path: D:/python/trainproject/dataset
train: images/train
val: images/valid
test: images/test

# number of classes
nc: 2
# class names
names: ['roof','busroof']

5、开始模型训练,创建.py文件并运行,代码如下

from ultralytics import YOLO
import os
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
# 加载模型
# model = YOLO("yolov8n.yaml")  # 从头开始构建新模型
model = YOLO("yolov8n.pt")  # 加载预训练模型(推荐用于训练)

# Use the model
results = model.train(data="roof.yaml", epochs=20, batch=2)  # 训练模型

运行结果:

6、获得我们需要的模型

7、使用我们自己训练出的模型进行图像标注测试,创建test.py,代码如下:


from ultralytics import YOLO
from PIL import Image
#model = YOLO('yolov8n.pt')
model = YOLO('XXX/runs/detect/train6/weights/best.pt')
#image = Image.open("bus.jpg")
image = Image.open("D:/python/project/images/DJI_20230925133837_0046.JPG")
results = model.predict(source=image, save=True, save_txt=True) 

运行成功:

8、查看图像标注结果(由于训练模型使用的数据过少只有20张,所以识别不精确,但也能大致识别出来):

  • 10
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个使用C#编写的YOLOv3模型训练代码的例程,需要使用YOLOv3的darknet框架。请确保您已经安装了相关依赖和工具,并已经配置好相关环境变量。 ```C# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace YOLOv3 { class Program { static void Main(string[] args) { string darknetPath = @"C:\darknet\"; // darknet框架路径 string cfgFile = @"C:\darknet\cfg\yolov3.cfg"; // 模型配置文件路径 string dataFile = @"C:\darknet\cfg\coco.data"; // 数据集配置文件路径 string weightsFile = @"C:\darknet\yolov3.weights"; // 预训练模型权重文件路径 string trainFile = @"C:\darknet\cfg\train.txt"; // 训练集文件路径 string validFile = @"C:\darknet\cfg\val.txt"; // 验证集文件路径 string backupPath = @"C:\darknet\backup\"; // 模型保存路径 // 训练模型命令 string trainCmd = $"{darknetPath}darknet.exe detector train {dataFile} {cfgFile} {weightsFile} -map -dont_show -mjpeg_port 8090 -gpus 0,1,2,3"; // 加载训练集和验证集 List<string> trainList = File.ReadAllLines(trainFile).ToList(); List<string> validList = File.ReadAllLines(validFile).ToList(); // 创建一个模型保存文件夹 if (!Directory.Exists(backupPath)) { Directory.CreateDirectory(backupPath); } // 开始训练模型 var process = new System.Diagnostics.Process(); process.StartInfo.FileName = "cmd.exe"; process.StartInfo.CreateNoWindow = false; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardInput = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.Start(); process.StandardInput.WriteLine(trainCmd); process.StandardInput.Flush(); process.StandardInput.Close(); string output = process.StandardOutput.ReadToEnd(); string error = process.StandardError.ReadToEnd(); process.WaitForExit(); process.Close(); // 输出训练结果 Console.WriteLine(output); Console.WriteLine(error); } } } ``` 以上代码将模型训练所需的相关路径和命令进行了配置,并提供了一个简单的训练流程,以供参考。由于YOLOv3模型训练涉及到很多细节和参数调整,所以您可能需要根据自己的具体需求进行修改和调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值