【计算机视觉】YoloV8-训练与测试教程

devtools/2024/9/25 5:56:44/


Blog’s 主页: 白乐天_ξ( ✿>◡❛)
🌈 个人Motto:他强任他强,清风拂山冈!
💫 欢迎来到我的学习笔记!

制作数据集

Labelme 数据集

  • 数据集选用自己标注的,可参考以下:
['c17', 'c5', 'helicopter', 'c130', 'f16', 'b2',
'other', 'b52', 'kc10', 'command', 'f15', 'kc135', 'a10',
'b1', 'aew', 'f22', 'p3', 'p8', 'f35', 'f18', 'v22', 'f4',
'globalhawk', 'u2', 'su-27', 'il-38', 'tu-134', 'su-33',
'an-70', 'su-24', 'tu-22', 'il-76']

格式转换

  • 将 Labelme 数据集转为 yolov8 格式的数据集,转换代码如下:
import os
import shutilimport numpy as np
import json
from glob import glob
import cv2
from sklearn.model_selection import train_test_split
from os import getcwddef convert(size, box):dw = 1. / (size[0])dh = 1. / (size[1])x = (box[0] + box[1]) / 2.0 - 1y = (box[2] + box[3]) / 2.0 - 1w = box[1] - box[0]h = box[3] - box[2]x = x * dww = w * dwy = y * dhh = h * dhreturn (x, y, w, h)def change_2_yolo5(files, txt_Name):imag_name = []for json_file_ in files:json_filename = labelme_path + json_file_ + ".json"out_file = open('%s/%s.txt' % (labelme_path, json_file_), 'w')json_file = json.load(open(json_filename, "r", encoding="utf-8"))# image_path = labelme_path + json_file['imagePath']imag_name.append(json_file_ + '.jpg')height, width, channels = cv2.imread(labelme_path + json_file_ + ".jpg").shapefor multi in json_file["shapes"]:points = np.array(multi["points"])xmin = min(points[:, 0]) if min(points[:, 0]) > 0 else 0xmax = max(points[:, 0]) if max(points[:, 0]) > 0 else 0ymin = min(points[:, 1]) if min(points[:, 1]) > 0 else 0ymax = max(points[:, 1]) if max(points[:, 1]) > 0 else 0label = multi["label"].lower()if xmax <= xmin:passelif ymax <= ymin:passelse:cls_id = classes.index(label)b = (float(xmin), float(xmax), float(ymin), float(ymax))bb = convert((width, height), b)out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')# print(json_filename, xmin, ymin, xmax, ymax, cls_id)return imag_namedef image_txt_copy(files, scr_path, dst_img_path, dst_txt_path):""":param files: 图片名字组成的list:param scr_path: 图片的路径:param dst_img_path: 图片复制到的路径:param dst_txt_path: 图片对应的txt复制到的路径:return:"""for file in files:img_path = scr_path + fileprint(file)shutil.copy(img_path, dst_img_path + file)scr_txt_path = scr_path + file.split('.')[0] + '.txt'shutil.copy(scr_txt_path, dst_txt_path + file.split('.')[0] + '.txt')if __name__ == '__main__':classes = ['c17', 'c5', 'helicopter', 'c130', 'f16', 'b2','other', 'b52', 'kc10', 'command', 'f15', 'kc135', 'a10','b1', 'aew', 'f22', 'p3', 'p8', 'f35', 'f18', 'v22', 'f4','globalhawk', 'u2', 'su-27', 'il-38', 'tu-134', 'su-33','an-70', 'su-24', 'tu-22', 'il-76']# 1.标签路径labelme_path = "USA-Labelme/"isUseTest = True  # 是否创建test集# 3.获取待处理文件files = glob(labelme_path + "*.json")files = [i.replace("\\", "/").split("/")[-1].split(".json")[0] for i in files]for i in files:print(i)trainval_files, test_files = train_test_split(files, test_size=0.1, random_state=55)# splittrain_files, val_files = train_test_split(trainval_files, test_size=0.1, random_state=55)train_name_list = change_2_yolo5(train_files, "train")print(train_name_list)val_name_list = change_2_yolo5(val_files, "val")test_name_list = change_2_yolo5(test_files, "test")# 创建数据集文件夹。file_List = ["train", "val", "test"]for file in file_List:if not os.path.exists('./VOC/images/%s' % file):os.makedirs('./VOC/images/%s' % file)if not os.path.exists('./VOC/labels/%s' % file):os.makedirs('./VOC/labels/%s' % file)image_txt_copy(train_name_list, labelme_path, './VOC/images/train/', './VOC/labels/train/')image_txt_copy(val_name_list, labelme_path, './VOC/images/val/', './VOC/labels/val/')image_txt_copy(test_name_list, labelme_path, './VOC/images/test/', './VOC/labels/test/')
  • 运行完成后就得到了yolov8格式的数据集。

本地调试

  1. 下载与安装
    ● Github: GitHub - ultralytics/ultralytics: NEW - YOLOv8 🚀 in PyTorch > ONNX > OpenVINO > CoreML > TFLite
    ● 也可以直接使用命令行:pip install
    ● 下载到本地后解压,将生成的yolo数据集放到datasets(需要创建datasets 文件夹)文件夹下面,如下图:

  1. 安装库文件
  • 安装必要的库文件,安装命令:
    • pip install opencv-python
    • pip install numpy==1.23.5
    • pip install pyyaml
    • pip install tqdm
    • pip install matplotlib
  • 注意numpy的版本,如果是 2.0 以上版本一定要把版本降下来。
  1. 创建配置文件
  • 在根目录新建 VOC.yaml 文件,添加内容:
train:./VOC/images/train # train images
val:./VOC/images/val # val images
test:./VOC/images/test # test images (optional)names: ['c17', 'c5', 'helicopter', 'c130', 'f16', 'b2','other', 'b52', 'kc10', 'command', 'f15', 'kc135', 'a10','b1', 'aew', 'f22', 'p3', 'p8', 'f35', 'f18', 'v22', 'f4','globalhawk', 'u2', 'su-27', 'il-38', 'tu-134', 'su-33','an-70', 'su-24', 'tu-22', 'il-76']
  1. 创建训练脚本:
  • 新建train.py,在train.py添加代码:
from ultralytics import YOLO
if __name__ == '__main__':# 加载模型model = YOLO("ultralytics/cfg/models/v8/yolov8l.yaml")  # 从头开始构建新模型print(model.model)# Use the modelresults = model.train(data="VOC.yaml", epochs=100, device='0', batch=16, workers=0)  # 训练模型
  • 点击run开始运行train.py进行训练。

实时目标检测代码实现

以下是一个使用 Python 和 OpenCV 实现实时目标检测的示例代码:

import cv2
from ultralytics import YOLO# 加载模型
model = YOLO('your_model_path.pt')  # 替换为你的模型路径# 打开摄像头
cap = cv2.VideoCapture(0)  # 0 表示默认摄像头,如果有多个摄像头可以调整这个参数while True:# 读取一帧图像ret, frame = cap.read()if not ret:break# 进行目标检测results = model(frame)# 在图像上绘制检测结果annotated_frame = results[0].plot()# 显示图像cv2.imshow('Real-time Object Detection', annotated_frame)# 按下 'q' 键退出循环if cv2.waitKey(1) & 0xFF == ord('q'):break# 释放摄像头和关闭窗口
cap.release()
cv2.destroyAllWindows()

基于丹摩智算的训练

创建一个实例,这个在我之前发布的与丹摩平台关联的文章很详细地提到过,可以跳转学习:【链接】

  1. 首先创建账号,登录;
  2. 然后点击CPU云实例,开始创建实例;
  3. 选择付费类型;
  4. 选择实力配置;
  5. 配置数据盘;
  6. 选择镜像Pytorch;
  7. 创建密钥对;

实例创建完后,就点击JupyterLab进入控制台。

然后将我们刚才创建的工程压缩成 zip 的压缩包,等待上传。

点击,文件夹样子的标签,进入根目录,然后点击,进入上传文件的页面。

选择文件,点击打开。

上传完成后,点击Termina就可以进入我们熟悉的命令行界面。

输入 ls,就可以看到我们刚才上传的压缩包。然后输入:

unzip ultralytics-main.zip

解压!

解压后就可以在左侧的目录中看到解压后的文件夹。点击进入。

点击train.py,Open With→Editor。

打开 train.py 后就可以修改 train.py 里面的参数了。

pip install opencv-python

通过以上步骤,你可以成功地进行 YoloV8 的训练和测试。无论是在本地还是基于丹摩智算平台,都能根据自己的需求进行模型的训练和优化。

在训练过程中,需要注意以下几点:

一、数据准备

  1. 确保标注的数据集准确无误,类别清晰明确。这将直接影响模型的训练效果和准确性。
  2. 在格式转换过程中,仔细检查转换后的数据集是否符合 YoloV8 的格式要求,避免出现错误。

二、参数调整

  1. 在本地调试和基于丹摩智算的训练中,可以根据实际情况调整训练参数,如 epochs(训练轮数)、batch(批大小)、device(使用的设备)等。不同的参数组合可能会对训练时间和模型性能产生影响。
  2. 对于复杂的数据集或特定的任务,可以尝试不同的模型架构和超参数,以获得更好的性能。

三、测试与评估

  1. 在测试阶段,使用不同的图像进行预测,观察模型的准确性和泛化能力。可以通过调整阈值等参数来优化预测结果。
  2. 对测试结果进行评估,如计算准确率、召回率、F1 值等指标,以了解模型的性能表现。

四、持续优化

  1. 根据测试结果和评估指标,对模型进行进一步的优化。可以尝试增加数据量、进行数据增强、调整模型结构等方法。
  2. 不断尝试新的技术和方法,以提高模型的性能和适用性。

总之,YoloV8 是一个强大的目标检测模型,通过合理的数据准备、参数调整和测试评估,可以获得良好的训练效果和准确的预测结果。希望本教程能够帮助你顺利地进行 YoloV8 的训练和测试,为你的目标检测任务提供有力的支持。


http://www.ppmy.cn/devtools/116832.html

相关文章

美团中间件C++一面-面经总结

1、TCP和UDP 的区别&#xff1f; 速记标识符&#xff1a;连靠刘墉宿营 解释&#xff1a; 面向连接vs无连接 可靠传输vs不保证可靠 字节流vs报文传输 拥塞控制流量控制vs无 速度慢vs速度快 应用场景自己描述 2、服务端处于close wait是什么情况&#xff0c;是由什么造成的&…

俯卧撑动作起伏识别计数系统源码分享

俯卧撑动作起伏识别计数检测系统源码分享 [一条龙教学YOLOV8标注好的数据集一键训练_70全套改进创新点发刊_Web前端展示] 1.研究背景与意义 项目参考AAAI Association for the Advancement of Artificial Intelligence 项目来源AACV Association for the Advancement of Co…

armbian debian 系统安装overlayroot后无法启用

千盼万盼 终于debian12可以用了 它终于也跟ubuntu 系统一样可以安装overlayroot了 但是 满怀欣喜的装完了发现 压根没法启动 这。。。。。 原因吗 也简单。。。 默认的映像里没有busybox......... 而它有这个要求。。。 overlayroot 包中有一个小错误&#xff1a;它要求 gr…

深度学习:数据增强

目录 前言 一、为什么要使用数据增强&#xff1f; 二、数据增强有哪些方法&#xff1f; 1. 几何变换 2. 颜色变换 3. 噪声添加 4. 裁剪 5. 混合技术 6. 其他方法 三、代码实现 前言 数据增强是深度学习中常用的一种技术&#xff0c;旨在通过对训练数据进行各种变换来…

计算机毕业设计之:宠物互助平台的微信小程序系统(源码+文档+讲解)

博主介绍&#xff1a; ✌我是阿龙&#xff0c;一名专注于Java技术领域的程序员&#xff0c;全网拥有10W粉丝。作为CSDN特邀作者、博客专家、新星计划导师&#xff0c;我在计算机毕业设计开发方面积累了丰富的经验。同时&#xff0c;我也是掘金、华为云、阿里云、InfoQ等平台…

低代码中实现数据映射的必要性与方案

在数字化转型的浪潮中&#xff0c;低代码平台因其快速开发和灵活性而受到越来越多企业的青睐。然而&#xff0c;随着业务需求的复杂化&#xff0c;单纯依赖低代码工具往往难以满足企业在数据处理和业务逻辑上的要求。数据映射作为连接不同数据源和业务逻辑的桥梁&#xff0c;显…

【C++篇】手撕 C++ string 类:从零实现到深入剖析的模拟之路

文章目录 C string 类的模拟实现&#xff1a;从构造到高级操作前言第一章&#xff1a;为什么要手写 C string 类&#xff1f;1.1 理由与价值 第二章&#xff1a;实现一个简单的 string 类2.1 基本构造与析构2.1.1 示例代码&#xff1a;基础的 string 类实现2.1.2 解读代码 2.2 …

WPF 中的线程池

WPF 中的线程池 在 WPF 中&#xff0c;虽然应用程序主要运行在 UI 线程上&#xff0c;但我们可以使用 线程池 来执行后台任务而不会阻塞 UI 线程。WPF 中常用的线程池是 .NET 线程池&#xff0c;可以通过 ThreadPool 类或 Task 来管理后台任务。以下是 WPF 中如何使用线程池及…