【深度学习】YOLOv5,金属表面的缺陷检测,GC10-DET数据集

目录:

文章目录

  • 数据集
  • 数据集转换
  • 下载yolov5
  • 创建 dataset.yaml
  • 训练参数
  • 开始训练
  • 数据分布
  • 训练结果
  • 问询、帮助

数据集

数据集地址:

https://github.com/lvxiaoming2019/GC10-DET-Metallic-Surface-Defect-Datasets

数据集下载方式:

Download link:https://pan.baidu.com/s/1Zrd-gzfVhG6oKdVSa9zoPQ Verify Code:cdyt

其中有个excel,写了介绍:此数据集一共10种金属缺陷,每一种有多少张图也写在excel了:

在这里插入图片描述

数据集转换

数据集的lable文件夹下是每个图片的框和类别标记,是xml格式。

在这里插入图片描述

运行下面这个代码,可以直接将数据集直接转为yolov5格式:

import os
import shutildef listPathAllfiles(dirname):result = []for maindir, subdir, file_name_list in os.walk(dirname):for filename in file_name_list:apath = os.path.join(maindir, filename)result.append(apath)return result# 所有label文件转换后给到labels文件夹,txt文件
import xml.etree.ElementTree as ET
import os
import shutil
import random
import cv2classes = """1_chongkong
2_hanfeng
3_yueyawan
4_shuiban
5_youban
6_siban
7_yiwu
8_yahen
9_zhehen
10_yaozhe""".split("\n")xmldir = r"/ssd/xiedong/GC10-DET/lable"
img_src_dir = r"/ssd/xiedong/GC10-DET"txtdir = r"/ssd/xiedong/GC10-DET_yolov5/labels"
imgdir = r"/ssd/xiedong/GC10-DET_yolov5/images"
os.system("rm -rf " + txtdir)
os.system("rm -rf " + imgdir)
os.makedirs(txtdir, exist_ok=True)
os.makedirs(imgdir, exist_ok=True)def convert_annotation(img_id_filename):image_id = img_id_filename.split(".")[0]# in_file = open(xmldir + '%s.xml' % (image_id), encoding='UTF-8')in_file = open(os.path.join(xmldir, '%s.xml' % (image_id)), encoding='UTF-8')# out_file = open(txtdir + '%s.txt' % (image_id), 'w', encoding='UTF-8')out_file = open(os.path.join(txtdir, '%s.txt' % (image_id)), 'w', encoding='UTF-8')tree = ET.parse(in_file)root = tree.getroot()size = root.find('size')size_width = int(size.find('width').text)size_height = int(size.find('height').text)ix = 0for obj in root.iter('object'):difficult = obj.find('difficult').textcls = obj.find('name').textif cls not in classes or int(difficult) == 1:continuecls_id = classes.index(cls)xmlbox = obj.find('bndbox')b = [float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text),float(xmlbox.find('ymax').text)]if size_width == 0 or size_height == 0:print("不合理的图,程序会删除这张图", image_id)continue# 标注越界修正if b[1] > size_width:b[1] = size_widthif b[3] > size_height:b[3] = size_heighttxt_data = [((b[0] + b[1]) / 2.0 - 1) / size_width, ((b[2] + b[3]) / 2.0 - 1) / size_height,(b[1] - b[0]) / size_width, (b[3] - b[2]) / size_height]out_file.write(str(cls_id) + " " + " ".join([str(a) for a in txt_data]) + '\n')in_file.close()out_file.close()xmllist = os.listdir(xmldir)
for img_id in xmllist:convert_annotation(img_id)img_sub_list_all = []
for i in range(1, 11):img_src_sub_dir = os.path.join(img_src_dir, str(i))img_sub_list = os.listdir(img_src_sub_dir)img_sub_list_all.extend(img_sub_list)all_imgs = listPathAllfiles(img_src_dir)
textlist = os.listdir(txtdir)
print(len(textlist))
for x in textlist:x1 = x.split(".")[0] + ".jpg"if x1 not in img_sub_list_all:print("不可能打印我")continuefor x2 in all_imgs:if x1 in x2:shutil.copy(x2, imgdir)imgdir_files = os.listdir(imgdir)
print(len(imgdir_files))

下载yolov5

下载yolov5

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

创建环境:

conda create -n py310_yolov5 python=3.10 -y
conda activate py310_yolov5

装一个可以用的torch:


# CUDA 11.8
conda install pytorch==2.1.2 torchvision==0.16.2 torchaudio==2.1.2 pytorch-cuda=11.8 -c pytorch -c nvidia

取消这2个:
在这里插入图片描述

然后安装一些别的包:

pip install -r requirements.txt  # install

随后更多内容参考官网这里的训练指导:

https://docs.ultralytics.com/zh/yolov5/tutorials/train_custom_data/#before-you-start

创建 dataset.yaml

创建文件:

cd yolov5/data
cp coco128.yaml jinshu.yaml

将fire_smoke.yaml修改为这样:

path: /ssd/xiedong/GC10-DET_yolov5
train: images
val: images
test: # test images (optional)# Classes
names:0: 1_chongkong1: 2_hanfeng2: 3_yueyawan3: 4_shuiban4: 5_youban5: 6_siban6: 7_yiwu7: 8_yahen8: 9_zhehen9: 10_yaozhe

训练参数

使用python train.py --help查看训练参数:

# python train.py --help
警告 ⚠️ Ultralytics 设置已重置为默认值。这可能是由于您的设置存在问题或最近 Ultralytics 包更新导致的。
使用 'yolo settings' 命令或查看 '/home/xiedong/.config/Ultralytics/settings.yaml' 文件来查看设置。
使用 'yolo settings key=value' 命令来更新设置,例如 'yolo settings runs_dir=path/to/dir'。更多帮助请参考 https://docs.ultralytics.com/quickstart/#ultralytics-settings。
用法: train.py [-h] [--weights WEIGHTS] [--cfg CFG] [--data DATA] [--hyp HYP] [--epochs EPOCHS] [--batch-size BATCH_SIZE] [--imgsz IMGSZ] [--rect] [--resume [RESUME]][--nosave] [--noval] [--noautoanchor] [--noplots] [--evolve [EVOLVE]] [--evolve_population EVOLVE_POPULATION] [--resume_evolve RESUME_EVOLVE][--bucket BUCKET] [--cache [CACHE]] [--image-weights] [--device DEVICE] [--multi-scale] [--single-cls] [--optimizer {SGD,Adam,AdamW}] [--sync-bn][--workers WORKERS] [--project PROJECT] [--name NAME] [--exist-ok] [--quad] [--cos-lr] [--label-smoothing LABEL_SMOOTHING] [--patience PATIENCE][--freeze FREEZE [FREEZE ...]] [--save-period SAVE_PERIOD] [--seed SEED] [--local_rank LOCAL_RANK] [--entity ENTITY] [--upload_dataset [UPLOAD_DATASET]][--bbox_interval BBOX_INTERVAL] [--artifact_alias ARTIFACT_ALIAS] [--ndjson-console] [--ndjson-file]选项:-h, --help            显示帮助信息并退出--weights WEIGHTS     初始权重路径--cfg CFG             模型配置文件路径--data DATA           数据集配置文件路径--hyp HYP             超参数路径--epochs EPOCHS       总训练轮数--batch-size BATCH_SIZE所有 GPU 的总批量大小,-1 表示自动批处理--imgsz IMGSZ, --img IMGSZ, --img-size IMGSZ训练、验证图像大小(像素)--rect                矩形训练--resume [RESUME]     恢复最近的训练--nosave              仅保存最终检查点--noval               仅验证最终轮次--noautoanchor        禁用 AutoAnchor--noplots             不保存绘图文件--evolve [EVOLVE]     为 x 代演进超参数--evolve_population EVOLVE_POPULATION加载种群的位置--resume_evolve RESUME_EVOLVE从上一代演进恢复--bucket BUCKET       gsutil 存储桶--cache [CACHE]       图像缓存 ram/disk--image-weights       在训练时使用加权图像选择--device DEVICE       cuda 设备,例如 00,1,2,3 或 cpu--multi-scale         图像大小变化范围为 +/- 50%--single-cls          将多类数据作为单类训练--optimizer {SGD,Adam,AdamW}优化器--sync-bn             使用 SyncBatchNorm,仅在 DDP 模式下可用--workers WORKERS     最大数据加载器工作进程数(每个 DDP 模式中的 RANK)--project PROJECT     保存到项目/名称--name NAME           保存到项目/名称--exist-ok            存在的项目/名称正常,不增加--quad                四通道数据加载器--cos-lr              余弦学习率调度器--label-smoothing LABEL_SMOOTHING标签平滑 epsilon--patience PATIENCE   EarlyStopping 耐心(未改善的轮次)--freeze FREEZE [FREEZE ...]冻结层:backbone=10, first3=0 1 2--save-period SAVE_PERIOD每 x 轮保存检查点(如果 < 1 则禁用)--seed SEED           全局训练种子--local_rank LOCAL_RANK自动 DDP 多 GPU 参数,不要修改--entity ENTITY       实体--upload_dataset [UPLOAD_DATASET]上传数据,"val" 选项--bbox_interval BBOX_INTERVAL设置边界框图像记录间隔--artifact_alias ARTIFACT_ALIAS要使用的数据集 artifact 版本--ndjson-console      将 ndjson 记录到控制台--ndjson-file         将 ndjson 记录到文件

开始训练

多卡训练:

python -m torch.distributed.run --nproc_per_node 2 train.py --weights yolov5s.pt --data jinshu.yaml --batch-size 100  --epochs 50 --img 640 --sync-bn --name jinshu --cos-lr --device 0,1

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

数据分布

在这里插入图片描述
在这里插入图片描述

训练结果

在这里插入图片描述

问询、帮助

https://docs.qq.com/sheet/DUEdqZ2lmbmR6UVdU?tab=BB08J2

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

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

相关文章

openWebUI+ollamawindows+不用docker+webLite本地安装

openWebUI & ollama & windows & 不用docker & webLite 本地安装 总结一下安装教程 10核CPU16G内存 两个web框架都可以&#xff0c;先说简单的 ollama-webui-lite(https://github.com/ollama-webui/ollama-webui-lite) 轻量级&#xff0c;只使用nodejs 先装…

kaggle之皮肤癌数据的深度学习测试

kaggle之皮肤癌数据的深度学习测试 近期一直在肝深度学习 很久之前&#xff0c;曾经上手搞过一段时间的深度学习&#xff0c;似乎是做轮胎花纹的识别&#xff0c;当初用的是TensorFlow&#xff0c;CPU版本的&#xff0c;但已经很长时间都没弄过了 现在因为各种原因&#xff…

编程学习路线

Java最强学习路线 快来官网定制一套属于自己的学习路线吧 官方网址&#xff1a; Learn to become a modern Java developerCommunity driven, articles, resources, guides, interview questions, quizzes for java development. Learn to become a modern Java developer by…

MySQL中脏读与幻读

一般对于我们的业务系统去访问数据库而言&#xff0c;它往往是多个线程并发执行多个事务的&#xff0c;对于数据库而言&#xff0c;它会有多个事务同时执行&#xff0c;可能这多个事务还会同时更新和查询同一条数据&#xff0c;所以这里会有一些问题需要数据库来解决 我们来看…

Vscode上使用Clang,MSVC, MinGW, (Release, Debug)开发c++完全配置教程(包含常见错误),不断更新中.....

1.VSCode报错头文件找不到 clang(pp_file_not_found) 在Fallback Flags中添加 -I&#xff08;是-include的意思&#xff0c;链接你的编译器对应头文件地址&#xff0c;比如我下面的是MSVC的地址&#xff09; 问题得到解决~

springboot如何使用RedisTemplate

第一步&#xff1a;创建一个spring boot项目 第二步&#xff1a;pom导入redis相关依赖 <!--reids依赖--> <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId> </depen…

Office Word自动编号转文本

原理 使用office自带的宏功能&#xff0c;一键替换 过程 调出word的“开发工具”选项 文件->选项->自定义功能区->选中开发工具->确定 创建宏 开发工具->宏->创建宏 编写宏 在弹出来的框里&#xff0c;替换代码为 Sub num2txt() ActiveDocument.…

win11 安装qt5.14.2 、qtcreator、vs编译器 。用最小安装进行 c++开发qt界面

系统 &#xff1a;win11 一、安装vs生成工具 &#xff0c;安装编译器 下载visualstudio tools 生成工具&#xff1a; 安装编译器 和 windows sdk&#xff1a; 安装debug 调试器&#xff1a; 二、Qt5.14.2下载 下载链接: Index of /archive/qt/5.14/5.14.2 安装qt 三、配置QT/…

计算机毕业设计ssm+jsp离退休人员管理系统7z292

考虑到实际生活中在离退休管理方面的需要以及对该系统认真的分析&#xff0c;将系统权限按管理员和用户这两类涉及用户划分。 &#xff08;1&#xff09;管理员功能需求 管理员登陆后&#xff0c;主要模块包括主页、个人中心、系统公告管理、职业分类管理、用户管理、退休登记管…

Java8 Stream常见用法

Stream流的常见用法&#xff1a; 1.利用stream流特性把数组转list集合 //定义一个数组Integer[] array {5,2,1,6,4,3};//通过stream特性把数组转list集合List<Integer> list Arrays.stream(array).collect(Collectors.toList());//打印结果System.out.println(list);…

【数学建模】DVD在线租赁

2005高教社杯全国大学生数学建模竞赛题目B 随着信息时代的到来&#xff0c;网络成为人们生活中越来越不可或缺的元素之一。许多网站利用其强大的资源和知名度&#xff0c;面向其会员群提供日益专业化和便捷化的服务。例如&#xff0c;音像制品的在线租赁就是一种可行的服务。这…

Vue 使用Canvas画布手写电子版签名 保存 上传服务端

电子版签名效果 定义画布 <canvas width"500"height"250"ref"cn"mousedown"cnMouseDown"mousemove"cnMouseMove"mouseup"cnMouseUp"style"width:500px;height: 250px;background-color:snow;padding: 10p…