使用YOLOv8训练自己的目标检测数据集(VOC格式/COCO格式)

yolov8训练自己的数据集

      • 1. 下载项目
      • 2. 搭建环境
      • 3. 数据集格式转换
        • 3.1 VOC格式转YOLO格式
        • 3.2 COCO格式转YOLO格式
      • 4. 训练数据
      • 5. 推理预测
      • 6. 模型导出

1. 下载项目

git clone https://github.com/ultralytics/ultralytics.git

2. 搭建环境

conda create --name ultralytics python==3.8
conda activate ultralytics
# 电脑是CUDA11.1的
pip install torch==1.8.0+cu111 torchvision==0.9.0+cu111 torchaudio==0.8.0 -f https://download.pytorch.org/whl/torch_stable.htmlpip install ultralytics

3. 数据集格式转换

3.1 VOC格式转YOLO格式
  • VOC格式
── VOCdevkit
└── VOC2007├── Annotations	# 存放图片对应的xml文件,与JPEGImages图片一一对应├── ImageSets│   └── Main	# 存放train.txt、val.txt└── JPEGImages	# 存放所有图片文件
  • YOLO格式
── VOCdevkit
├── images
│   ├── train	# 存放训练集图片
│   └── val	# 存放验证集图片
└── labels├── train	# 存放训练集标注文件└── val	# 存放验证集标注文件
  • 转换脚本
from tqdm import tqdm
import shutil
from pathlib import Path
import xml.etree.ElementTree as ETdef convert_label(path, lb_path, year, image_id, names):def convert_box(size, box):dw, dh = 1. / size[0], 1. / size[1]x, y, w, h = (box[0] + box[1]) / 2.0 - 1, (box[2] + box[3]) / 2.0 - 1, box[1] - box[0], box[3] - box[2]return x * dw, y * dh, w * dw, h * dhin_file = open(path / f'VOC{year}/Annotations/{image_id}.xml')out_file = open(lb_path, 'w')tree = ET.parse(in_file)root = tree.getroot()size = root.find('size')w = int(size.find('width').text)h = int(size.find('height').text)for obj in root.iter('object'):cls = obj.find('name').textif cls in names:xmlbox = obj.find('bndbox')bb = convert_box((w, h), [float(xmlbox.find(x).text) for x in ('xmin', 'xmax', 'ymin', 'ymax')])cls_id = names.index(cls)  # class idout_file.write(" ".join(str(a) for a in (cls_id, *bb)) + '\n')else:print("category error: ", cls)year = "2007"
image_sets = ["train", "val"]
path = Path("F:/vsCode/ultralytics/datasets/VOCdevkit/")
class_names = ["apple"]for image_set in image_sets:imgs_path = path / 'images' / f'{image_set}'lbs_path = path / 'labels' / f'{image_set}'imgs_path.mkdir(exist_ok=True, parents=True)lbs_path.mkdir(exist_ok=True, parents=True)with open(path / f'VOC{year}/ImageSets/Main/{image_set}.txt') as f:image_ids = f.read().strip().split()for id in tqdm(image_ids, desc=f'{image_set}'):f = path / f'VOC{year}/JPEGImages/{id}.jpg'  # old img pathlb_path = (lbs_path / f.name).with_suffix('.txt')  # new label path# f.rename(imgs_path / f.name)  # move imageshutil.copyfile(f, imgs_path / f.name) # copy imageconvert_label(path, lb_path, year, id, class_names)  # convert labels to YOLO format

数据集文件夹目录如下
在这里插入图片描述

3.2 COCO格式转YOLO格式
  • COCO格式
── Apple
├── train
│   ├── _annotations.coco.json	# 训练集标注文件
│   ├── 00001.jpg
│   ├── 00003.jpg
│   └── ...
└── valid├── _annotations.coco.json	# 验证集标注文件├── 00002.jpg├── 00004.jpg└── ...
  • 转换脚本
import json
import os
import shutil
from tqdm import tqdmcoco_path = "F:/datasets/Apple_Detection_Swift-YOLO_192"
output_path = "F:/vsCode/ultralytics/datasets/Apple"os.makedirs(os.path.join(output_path, "images", "train"), exist_ok=True)
os.makedirs(os.path.join(output_path, "images", "val"), exist_ok=True)
os.makedirs(os.path.join(output_path, "labels", "train"), exist_ok=True)
os.makedirs(os.path.join(output_path, "labels", "val"), exist_ok=True)with open(os.path.join(coco_path, "train", "_annotations.coco.json"), "r") as f:train_annotations = json.load(f)with open(os.path.join(coco_path, "valid", "_annotations.coco.json"), "r") as f:val_annotations = json.load(f)# Iterate over the training images
for image in tqdm(train_annotations["images"]):width, height = image["width"], image["height"]scale_x = 1.0 / widthscale_y = 1.0 / heightlabel = ""for annotation in train_annotations["annotations"]:if annotation["image_id"] == image["id"]:# Convert the annotation to YOLO formatx, y, w, h = annotation["bbox"]x_center = x + w / 2.0y_center = y + h / 2.0x_center *= scale_xy_center *= scale_yw *= scale_xh *= scale_yclass_id = annotation["category_id"]label += "{} {} {} {} {}\n".format(class_id, x_center, y_center, w, h)# Save the image and labelshutil.copy(os.path.join(coco_path, "train", image["file_name"]), os.path.join(output_path, "images", "train", image["file_name"]))with open(os.path.join(output_path, "labels", "train", image["file_name"].replace(".jpg", ".txt")), "w") as f:f.write(label)# Iterate over the validation images
for image in tqdm(val_annotations["images"]):width, height = image["width"], image["height"]scale_x = 1.0 / widthscale_y = 1.0 / heightlabel = ""for annotation in val_annotations["annotations"]:if annotation["image_id"] == image["id"]:# Convert the annotation to YOLO formatx, y, w, h = annotation["bbox"]x_center = x + w / 2.0y_center = y + h / 2.0x_center *= scale_xy_center *= scale_yw *= scale_xh *= scale_yclass_id = annotation["category_id"]label += "{} {} {} {} {}\n".format(class_id, x_center, y_center, w, h)# Save the image and labelshutil.copy(os.path.join(coco_path, "valid", image["file_name"]), os.path.join(output_path, "images", "val", image["file_name"]))with open(os.path.join(output_path, "labels", "val", image["file_name"].replace(".jpg", ".txt")), "w") as f:f.write(label)

4. 训练数据

找到ultralytics/cfg/datasets/VOC.yaml,复制一份命名为VOC_self.yaml

# 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: F:/vsCode/ultralytics/datasets/VOCdevkit
train: # train images (relative to 'path')  16551 images- images/train
val: # val images (relative to 'path')  4952 images- images/val
test: # test images (optional)- images/val# Classes
names:0: apple

根据README文件选择预训练模型,最好先手动下载放置在项目主目录下。

在这里插入图片描述

训练命令:

yolo task=detect mode=train model=yolov8x.pt data=f:/ultralytics/ultralytics/cfg/datasets/VOC_self.yaml epochs=100 batch=4 device=0
  • 如果想从头开始构建新模型,则model参数设置为yolov8x.yaml
  • 使用自己的数据集,则data参数最好使用绝对路径
  • 如果数据集进行了修改,比如标注文件调整了、图片增多了等等,那么在训练前一定要先把labels文件夹下面的train.cache和val.cache删掉再运行训练命令

在这里插入图片描述

训练得到的模型保存到runs/detect/train文件夹下

5. 推理预测

yolo task=detect mode=predict model=runs\detect\train\weights\best.pt source=datasets\VOCdevkit\images\val device=0

6. 模型导出

将训练好的pt模型文件导出为onnx格式的

yolo task=detect mode=export model=runs\detect\train\weights\best.pt format=onnx

  • 遇到的问题

由于没提前安装onnx,运行后会自动下载最新版本的onnx,接着就会报错max() arg is an empty sequence
在这里插入图片描述

在这里插入图片描述


  • 解决方法

1)按照输出可以知道Ultralytics要求的onnx>=1.12.0,最好就是直接安装1.12.0版本的,所以pip install onnx==1.12.0

2)直接使用上方的CLI命令导出onnx还是会报max() arg is an empty sequence,需要改用python脚本来导出,并指定onnx的opset设置为13;

在这里插入图片描述

from ultralytics import YOLOmodel = YOLO('F:/vsCode/ultralytics/runs/detect/train2/weights/best.pt')
model.export(format='onnx', opset=13)

3)运行该导出脚本即可导出成功
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/626028.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Spring核心容器总结

2.2 核心容器总结 2.2.1 容器相关 BeanFactory是IoC容器的顶层接口,初始化BeanFactory对象时,加载的bean延迟加载 ApplicationContext接口是Spring容器的核心接口,初始化时bean立即加载 ApplicationContext接口提供基础的bean操作相关方法…

SQL系统函数知识点梳理(Oracle)

这里写目录标题 函数系统函数转换函数to_date()to_char()将数值转换成字符格式 添加货币符号将日期转换成字符 其他不常用的转换函数 字符型函数连接函数大小写转换函数大写转换小写转换首字母大写,其余的小写 替换函数去除空格函数截取函数填充函数获取字符长度函数…

什么是Rust语言?探索安全系统编程的未来

🚀 什么是Rust语言?探索安全系统编程的未来 文章目录 🚀 什么是Rust语言?探索安全系统编程的未来摘要引言正文📘 Rust语言简介🌟 发展历程🎯 Rust的技术意义和优势📦 Rust解决的问题…

Proxmox VE 创建用户

前言 实现创建用户组、创建用户、分配用户角色权限 创建一键创建用户组脚本 用户密码testpve/1234.com用户组testgroupPVEVMUser 角色权限,此角色是默认系统的,查看、备份、配置 CD-ROM、VM 控制台、VM 电源管理pveum role list 查看特权列表pveum us…

Java NIO,高效操作I/O流的必备技能

Java IO在工作中其实不常用到,更别提NIO了。但NIO却是高效操作I/O流的必备技能,如顶级开源项目Kafka、Netty、RocketMQ等都采用了NIO技术,NIO也是大多数面试官必考的体系知识。虽然骨头有点难啃,但还是要慢慢消耗知识、学以致用哈…

OpenHarmony开发实例:【鸿蒙.bin文件烧录】

使用HiBurn烧录鸿蒙.bin文件到Hi3861开发板 鸿蒙官方文档的“Hi3861开发板第一个示例程序”中描述了——如何使用DevEco Device Tool工具烧录二进制文件到Hi3861开发板; 本文将介绍如何使用HiBurn工具烧录鸿蒙的.bin文件到Hi3861开发板。 获取HiBurn工具 通过鸿蒙…

机器人码垛机的技术特点与应用

随着科技的飞速发展,机器人技术正逐渐渗透到各个行业领域,其中,机器人码垛机在物流行业的应用尤为引人瞩目。它不仅提高了物流效率,降低了成本,更在改变传统物流模式的同时,为行业发展带来了重大的变革。 一…

(十一)C++自制植物大战僵尸游戏客户端更新实现

植物大战僵尸游戏开发教程专栏地址http://t.csdnimg.cn/cFP3z 更新检查 游戏启动后会下载服务器中的版本号然后与本地版本号进行对比,如果本地版本号小于服务器版本号就会弹出更新提示。让用户选择是否更新客户端。 在弹出的更新对话框中有显示最新版本更新的内容…

Axure实现导航栏的展开与收缩

Axure实现导航栏的展开与收缩 一、概要介绍二、设计思路三、Axure制作导航栏四、技术细节五、小结 一、概要介绍 使用场景一般是B端后台系统需要以导航栏的展开与收缩实现原型的动态交互,主要使用区域是左边或者顶部的导航栏展开与收缩,同一级导航下的小…

实战纪实 | 学工平台平行越权

一.账号密码可爆破(无验证码) 1.学校学工平台用于请假跟每日上报健康信息,登录框如下: 2.经过测试发现这里不存在验证码验证,并且存在初始密码,可以尝试使用默认密码爆破账号: 3.经测试&#x…

部署wordpress

查看别名type ll ll 是 ls -l --colorauto 的别名 设置别名alias alias ymyum install -y 使用别名ym nginx 取消别名unalias ym 基于LNMP做一个wordpress nginx mysql 5.7 PHP 7.4 1、linux基本环境 修改主机名 hostnamectl set-hostname $name 关闭防火墙及selinux …

基于SpringBoot基于java的教学辅助平台

采用技术 SpringBoot项目基于java的教学辅助平台的设计与实现~ 开发语言:Java 数据库:MySQL 技术:SpringBootMyBatis 工具:IDEA/Ecilpse、Navicat、Maven 页面展示效果 学生信息管理 教师信息管理 课程信息管理 科目分类管…