本文主要介紹如何運(yùn)用開源Yolov5模型,結(jié)合自己的數(shù)據(jù),訓(xùn)練其他目標(biāo)檢測(cè)模型。
基礎(chǔ)準(zhǔn)備工作:
- anaconda
- 適用Yolov5的虛擬環(huán)境
- git上下載Yolov5并調(diào)通測(cè)試代碼https://github.com/ultralytics/yolov5https://github.com/ultralytics/yolov5
本次用的環(huán)境:
- python==3.7
- pytorch==1.7.1
- torchvision==0.8.2
- torchaudio==0.7.0
- cudatoolkit==10.2
環(huán)境配置好后運(yùn)行測(cè)試代碼:
import torch
# GPU
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# Model
model = torch.hub.load('D:/work/git-example/yolov5-master', 'yolov5s', source='local') # or yolov5m, yolov5l, yolov5x, custom
model = model.to(device)
# Images
img = './data/images/zidane.jpg' # or file, Path, PIL, OpenCV, numpy, list
# Inference
results = model(img)
# Results
results.print() # or .show(), .save(), .crop(), .pandas(), etc.
其中torch.hub.load通過source='local'來(lái)判斷是在本地還是在git上加載yolov5s.pt模型,為了避免網(wǎng)速問題,可以提前下載yolov5s.pt模型,放在本地yolov5-master文件夾下,然后制定source為local進(jìn)行模型加載。
result.print()可以將模型中識(shí)別出的目標(biāo)物類別進(jìn)行輸出,如果要獲取到這個(gè)變量,需要修改models/common.py文件中Detections/display()方法,將類別return一下就可以獲取了。
環(huán)境配好后再說(shuō)訓(xùn)練自己的模型:
數(shù)據(jù)準(zhǔn)備
對(duì)圖片進(jìn)行打標(biāo)工作,這里使用labelimg,直接使用python的pip安裝即可
pip install labelimg
安裝成功后在終端中輸入labelimg啟動(dòng)打標(biāo)工具。
Yolo有自己要求的數(shù)據(jù)標(biāo)注格式,但是我們打標(biāo)的時(shí)候一般采取VOC格式,這樣方便數(shù)據(jù)可以給其他模型使用,VOC到y(tǒng)olo格式需要經(jīng)過一些轉(zhuǎn)換。
voc格式如下所示,是一個(gè)xml文件
<annotation>
<folder>train</folder>
<filename>暴露垃圾_2.jpg</filename>
<path>D:\work\git-example\yolov5-master\YOLO_rubbish\images\train\暴露垃圾_2.jpg</path>
<source>
<database>Unknown</database>
</source>
<size>
<width>650</width>
<height>867</height>
<depth>3</depth>
</size>
<segmented>0</segmented>
<object>
<name>rubbish</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>235</xmin>
<ymin>410</ymin>
<xmax>408</xmax>
<ymax>631</ymax>
</bndbox>
</object>
</annotation>
?yolo格式如下所示,分別對(duì)應(yīng)xmin xmax ymin ymax坐標(biāo)值
0 0.503846 0.603806 0.287692 0.261822
采用如下代碼對(duì)voc格式的標(biāo)注進(jìn)行轉(zhuǎn)換
import xml.etree.ElementTree as ET
import os
from os import listdir, getcwd
sets = ['train', 'test', 'val']
classes = ["rubbish"]
def convert(size, box):
dw = 1. / size[0]
dh = 1. / size[1]
x = (box[0] + box[1]) / 2.0
y = (box[2] + box[3]) / 2.0
w = box[1] - box[0]
h = box[3] - box[2]
x = x * dw
w = w * dw
y = y * dh
h = h * dh
return (x, y, w, h)
def convert_annotation(image_id):
try:
in_file = open('./YOLO_rubbish/labels/%s.xml' % (image_id), 'r', encoding='utf-8')
except:
return
out_file = open('./YOLO_rubbish/labels-yolo2/%s.txt' % (image_id), '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'):
difficult = obj.find('difficult').text
cls = obj.find('name').text
if cls not in classes or int(difficult) == 1:
continue
cls_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))
bb = convert((w, h), b)
out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
每一個(gè)voc對(duì)應(yīng)的xml文件調(diào)用convert_annotation方法即可完成對(duì)應(yīng)yolo的轉(zhuǎn)換。
代碼準(zhǔn)備
標(biāo)注工作完成后,就是對(duì)代碼進(jìn)行修改以適應(yīng)自己數(shù)據(jù)的步驟了,新建數(shù)據(jù)文件夾,文件夾結(jié)構(gòu)如下所示:
images中放訓(xùn)練圖片,labels中放對(duì)應(yīng)的標(biāo)注數(shù)據(jù)(labels文件夾名字不可變,且要放在和images同級(jí)的地方,程序會(huì)自動(dòng)去找,名字變了就找不到了。。。。要改這個(gè)地方就要改源碼,還是遵照這個(gè)默認(rèn)的規(guī)則吧。。。)
新建數(shù)據(jù)路徑y(tǒng)aml配置文件,我這里在./data下建了一個(gè)rubbish_data.yaml文件
# YOLOv5 ?? by Ultralytics, GPL-3.0 license
# COCO 2017 dataset http://cocodataset.org by Microsoft
# Example usage: python train.py --data coco.yaml
# parent
# ├── yolov5
# └── datasets
# └── coco ← downloads here
# 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: D:/work/git-example/yolov5-master/YOLO_rubbish # dataset root dir
train: ./YOLO_rubbish/images/train # train images (relative to 'path') 118287 images
val: ./YOLO_rubbish/images/val # val images (relative to 'path') 5000 images
test: ./YOLO_rubbish/images/test # 20288 of 40670 images, submit to https://competitions.codalab.org/competitions/20794
# Classes
nc: 1 # number of classes
names: ['rubbish'] # class names
其中nc表示檢測(cè)類別種數(shù),names表示類別名稱,train/val/test表示訓(xùn)練數(shù)據(jù)圖片所在的路徑(上面images下的路徑)
新建yaml配置文件,在./models下建了個(gè)rubbish.yaml文件,文件內(nèi)容復(fù)制yolo5s.yaml就行,主要修改其中的nc值
訓(xùn)練
一切準(zhǔn)備就緒,運(yùn)行下面腳本開始訓(xùn)練
>python train.py --data rubbish_data.yaml --cfg rubbish.yaml --weights yolov5s.pt --epoch 100 --batch-size 16 --device 0
?yaml文件路徑均是上面新建的路徑,device為0表示使用的是GPU
訓(xùn)練會(huì)出現(xiàn)很多信息,大概不報(bào)錯(cuò)就行
?最后結(jié)果在這個(gè)文件夾下
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-448664.html
模型應(yīng)用
在./runs/train/exp中得到的模型結(jié)果包含信息很多,我們最后訓(xùn)練出的模型為weights下面的best.pt文件,直接加載這個(gè)模型文件即可用自己訓(xùn)練的模型對(duì)圖片完成目標(biāo)檢測(cè)工作。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-448664.html
python detect.py --weights ./runs/train/exp/weights/best.pt --source ./YOLO_rubbish/dblj_0.jpg --device 0
到了這里,關(guān)于使用Yolov5訓(xùn)練自己的模型的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!