conda create -n yolov5-6.1 python=3.8
conda activate yolov5-6.1
cd 你的目标目录
git clone GitHub - ultralytics/yolov5: YOLOv5 in PyTorch > ONNX > CoreML > TFLite
mv yolov5 yolov5-6.1
cd yolov5-6.1
pip install -r requirements.txt
Note:导出模型需要按照export.py 内说明安装对应的包,下面以导出TRT为例。
pip install onnx onnx-simplifier onnxruntime-gpu
一般工业还是需要使用如labelme等标注,格式为coco格式(class_id x y w x)xywx均需要归一化,类别号从0开始,一个框一行。
以“images” 命名图片路径,标签路径仅仅是将“images” 变为“labels”;代码自动对应images和labels,所以一张图片的标签需要和图片同名(如果没有对应的label 就是认为是背景图,没有目标)。
1)使用文件夹(列表)文件夹存储所有的训练图片(由于磁盘文件系统,单个文件夹文件过多影响吞吐速度)。
单个文件夹对应配置文件的写法
path: ../datasets/VOC
train: # train images (relative to 'path')
- images/train2007
val: # val images (relative to 'path')
- images/test2007
test: # test images (optional)
- images/test2007
多个文件夹对应配置文件的写法
path: ../datasets/VOC
train: # train images (relative to 'path')
- images/train2012
- images/train2007
val: # val images (relative to 'path')
- images/test2007
test: # test images (optional)
- images/test2007
2)使用文本文件(列表)存储图片
单个文本文件对应配置文件的写法
path: ../datasets/VOC
train: # train images (relative to 'path')
- train2017.txt
val: # val images (relative to 'path')
- val2017.txt
test: # test images (optional)
- test-dev2017.txt
多个文本文件对应配置文件的写法
path: ../datasets/VOC
train: # train images (relative to 'path')
- train2017.txt
- train2012.txt
val: # val images (relative to 'path')
- val2017.txt
test: # test images (optional)
- test-dev2017.txt
参考源代码:
解析images
f = [] # image files
for p in path if isinstance(path, list) else [path]:
p = Path(p) # os-agnostic
if p.is_dir(): # dir
f += glob.glob(str(p / '**' / '*.*'), recursive=True)
# f = list(p.rglob('*.*')) # pathlib
elif p.is_file(): # file
with open(p) as t:
t = t.read().strip().splitlines()
parent = str(p.parent) + os.sep
f += [x.replace('./', parent) if x.startswith('./') else x for x in t] # local to global path
# f += [p.parent / x.lstrip(os.sep) for x in t] # local to global path (pathlib)
else:
raise FileNotFoundError(f'{prefix}{p} does not exist')
self.im_files = sorted(x.replace('/', os.sep) for x in f if x.split('.')[-1].lower() in IMG_FORMATS)
解析labels
def img2label_paths(img_paths):
# Define label paths as a function of image paths
sa, sb = f'{os.sep}images{os.sep}', f'{os.sep}labels{os.sep}' # /images/, /labels/ substrings
return [sb.join(x.rsplit(sa, 1)).rsplit('.', 1)[0] + '.txt' for x in img_paths]
如 data/coco128.yaml,里面的每一项都需要按需更改。
按需选择模型结构(s m l x)等参数,训练结果存储在runs/train/exp* 目录。
python train.py --img 640 --batch 16 --epochs 3 --data coco128.yaml --weights yolov5s.pt
测试时间
python val.py --weights yolov5l.pt --batch-size 32 --task speed
可以看run根目录下,对应的训练结果的保存。主要参考混淆矩阵、精度曲线、召回曲线、P_R曲线等
参考链接:
技术博客丨使用YOLOv5模型进行目标检测!
yolov5/dataloaders.py at f8722b4429e80f96be04b36e4efd84ce6583bfa1 · ultralytics/yolov5 · GitHub