https://blog.csdn.net/qq_36756866/article/details/109111065
深度學習菜鳥 2020-10-16 11:38:18 11156 收藏 215
分類專欄: yolov5目標檢測 文章標簽: 深度學習 python pytorch
版權
一.Requirements
本教程所用環境:代碼版本V3.0,源碼下載地址:https://github.com/ultralytics/yolov5.git
Pytorch:1.6.0
Cuda:10.1
Python:3.7
官方要求Python>=3.8 and PyTorch>=1.6.
通過git clone https://github.com/ultralytics/yolov5.git將YOLOv5源碼下載到本地,創建好虛擬環境,並通過pip install -r requirements.txt安裝依賴包。
二. 准備自己的數據集(VOC格式)
1.在yolov5目錄下創建paper_data文件夾(名字可以自定義),目錄結構如下,將之前labelImg標注好的xml文件和圖片放到對應目錄下
paper_data
…images # 存放圖片
…Annotations # 存放圖片對應的xml文件
…ImageSets/Main #之后會在Main文件夾內自動生成train.txt,val.txt,test.txt和trainval.txt四個文件,存放訓練集、驗證集、測試集圖片的名字(無后綴.jpg)
示例如下:
paper_data文件夾下內容如下:
Annotations文件夾下面為xml文件(標注工具采用labelImage),內容如下:
images為VOC數據集格式中的JPEGImages,內容如下:
ImageSets文件夾下面有個Main子文件夾,其下面存放訓練集、驗證集、測試集的划分,通過腳本生成,可以創建一個split_train_val.py文件,代碼內容如下:
# coding:utf-8
import os
import random
import argparse
parser = argparse.ArgumentParser()
#xml文件的地址,根據自己的數據進行修改 xml一般存放在Annotations下
parser.add_argument('--xml_path', default='Annotations', type=str, help='input xml label path')
#數據集的划分,地址選擇自己數據下的ImageSets/Main
parser.add_argument('--txt_path', default='ImageSets/Main', type=str, help='output txt label path')
opt = parser.parse_args()
trainval_percent = 1.0
train_percent = 0.9
xmlfilepath = opt.xml_path
txtsavepath = opt.txt_path
total_xml = os.listdir(xmlfilepath)
if not os.path.exists(txtsavepath):
os.makedirs(txtsavepath)
num = len(total_xml)
list_index = range(num)
tv = int(num * trainval_percent)
tr = int(tv * train_percent)
trainval = random.sample(list_index, tv)
train = random.sample(trainval, tr)
file_trainval = open(txtsavepath + '/trainval.txt', 'w')
file_test = open(txtsavepath + '/test.txt', 'w')
file_train = open(txtsavepath + '/train.txt', 'w')
file_val = open(txtsavepath + '/val.txt', 'w')
for i in list_index:
name = total_xml[i][:-4] + '\n'
if i in trainval:
file_trainval.write(name)
if i in train:
file_train.write(name)
else:
file_val.write(name)
else:
file_test.write(name)
file_trainval.close()
file_train.close()
file_val.close()
file_test.close()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
運行代碼后,在Main文件夾下生成下面四個txt文檔:
2.接下來准備labels,把數據集格式轉換成yolo_txt格式,即將每個xml標注提取bbox信息為txt格式(這種數據集格式成為yolo_txt格式),每個圖像對應一個txt文件,文件每一行為一個目標的信息,包括類別 xmin xmax ymin ymax。格式如下:
創建voc_label.py文件,將訓練集、驗證集、測試集生成label標簽(訓練中要用到),同時將數據集路徑導入txt文件中,代碼內容如下:
# -*- coding: utf-8 -*-
import xml.etree.ElementTree as ET
import os
from os import getcwd
sets = ['train', 'val', 'test']
classes = ["a", "b"] # 改成自己的類別
abs_path = os.getcwd()
print(abs_path)
def convert(size, box):
dw = 1. / (size[0])
dh = 1. / (size[1])
x = (box[0] + box[1]) / 2.0 - 1
y = (box[2] + box[3]) / 2.0 - 1
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):
in_file = open('/home/trainingai/zyang/yolov5/paper_data/Annotations/%s.xml' % (image_id), encoding='UTF-8')
out_file = open('/home/trainingai/zyang/yolov5/paper_data/labels/%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
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))
b1, b2, b3, b4 = b
# 標注越界修正
if b2 > w:
b2 = w
if b4 > h:
b4 = h
b = (b1, b2, b3, b4)
bb = convert((w, h), b)
out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
wd = getcwd()
for image_set in sets:
if not os.path.exists('/home/trainingai/zyang/yolov5/paper_data/labels/'):
os.makedirs('/home/trainingai/zyang/yolov5/paper_data/labels/')
image_ids = open('/home/trainingai/zyang/yolov5/paper_data/ImageSets/Main/%s.txt' % (image_set)).read().strip().split()
list_file = open('paper_data/%s.txt' % (image_set), 'w')
for image_id in image_ids:
list_file.write(abs_path + '/paper_data/images/%s.jpg\n' % (image_id))
convert_annotation(image_id)
list_file.close()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
運行后會生成如下labels文件夾和三個包含數據集的txt文件,其中labels中為不同圖像的標注文件,train.txt等txt文件為划分后圖像所在位置的絕對路徑,如train.txt就含有所有訓練集圖像的絕對路徑。
三個txt文件里面的內容如下:
3.配置文件
1)數據集的配置
在yolov5目錄下的data文件夾下新建一個ab.yaml文件(可以自定義命名),用來存放訓練集和驗證集的划分文件(train.txt和val.txt),這兩個文件是通過運行voc_label.py代碼生成的,然后是目標的類別數目和具體類別列表,ab.yaml內容如下:
疑問:ab.yaml文件中train和val通過train.txt和val.txt指定,我在訓練時報錯(別人沒有報錯,很費解!),於是我參照官網上data/coco128.yaml的形式指定train和val,內容如下:
2)編輯模型的配置文件
2-1) 聚類得出先驗框(可選)(聚類重新生成anchors運行時間較長)
kmeans.py代碼內容如下:
import numpy as np
def iou(box, clusters):
"""
Calculates the Intersection over Union (IoU) between a box and k clusters.
:param box: tuple or array, shifted to the origin (i. e. width and height)
:param clusters: numpy array of shape (k, 2) where k is the number of clusters
:return: numpy array of shape (k, 0) where k is the number of clusters
"""
x = np.minimum(clusters[:, 0], box[0])
y = np.minimum(clusters[:, 1], box[1])
if np.count_nonzero(x == 0) > 0 or np.count_nonzero(y == 0) > 0:
raise ValueError("Box has no area")
intersection = x * y
box_area = box[0] * box[1]
cluster_area = clusters[:, 0] * clusters[:, 1]
iou_ = intersection / (box_area + cluster_area - intersection)
return iou_
def avg_iou(boxes, clusters):
"""
Calculates the average Intersection over Union (IoU) between a numpy array of boxes and k clusters.
:param boxes: numpy array of shape (r, 2), where r is the number of rows
:param clusters: numpy array of shape (k, 2) where k is the number of clusters
:return: average IoU as a single float
"""
return np.mean([np.max(iou(boxes[i], clusters)) for i in range(boxes.shape[0])])
def translate_boxes(boxes):
"""
Translates all the boxes to the origin.
:param boxes: numpy array of shape (r, 4)
:return: numpy array of shape (r, 2)
"""
new_boxes = boxes.copy()
for row in range(new_boxes.shape[0]):
new_boxes[row][2] = np.abs(new_boxes[row][2] - new_boxes[row][0])
new_boxes[row][3] = np.abs(new_boxes[row][3] - new_boxes[row][1])
return np.delete(new_boxes, [0, 1], axis=1)
def kmeans(boxes, k, dist=np.median):
"""
Calculates k-means clustering with the Intersection over Union (IoU) metric.
:param boxes: numpy array of shape (r, 2), where r is the number of rows
:param k: number of clusters
:param dist: distance function
:return: numpy array of shape (k, 2)
"""
rows = boxes.shape[0]
distances = np.empty((rows, k))
last_clusters = np.zeros((rows,))
np.random.seed()
# the Forgy method will fail if the whole array contains the same rows
clusters = boxes[np.random.choice(rows, k, replace=False)]
while True:
for row in range(rows):
distances[row] = 1 - iou(boxes[row], clusters)
nearest_clusters = np.argmin(distances, axis=1)
if (last_clusters == nearest_clusters).all():
break
for cluster in range(k):
clusters[cluster] = dist(boxes[nearest_clusters == cluster], axis=0)
last_clusters = nearest_clusters
return clusters
if __name__ == '__main__':
a = np.array([[1, 2, 3, 4], [5, 7, 6, 8]])
print(translate_boxes(a))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
聚類生成新anchors的文件clauculate_anchors.py,代碼內容如下:
# -*- coding: utf-8 -*-
# 根據標簽文件求先驗框
import os
import numpy as np
import xml.etree.cElementTree as et
from kmeans import kmeans, avg_iou
FILE_ROOT = "/home/trainingai/zyang/yolov5/paper_data/" # 根路徑
ANNOTATION_ROOT = "Annotations" # 數據集標簽文件夾路徑
ANNOTATION_PATH = FILE_ROOT + ANNOTATION_ROOT
ANCHORS_TXT_PATH = "/home/trainingai/zyang/yolov5/data/anchors.txt"
CLUSTERS = 9
CLASS_NAMES = ['a', 'b']
def load_data(anno_dir, class_names):
xml_names = os.listdir(anno_dir)
boxes = []
for xml_name in xml_names:
xml_pth = os.path.join(anno_dir, xml_name)
tree = et.parse(xml_pth)
width = float(tree.findtext("./size/width"))
height = float(tree.findtext("./size/height"))
for obj in tree.findall("./object"):
cls_name = obj.findtext("name")
if cls_name in class_names:
xmin = float(obj.findtext("bndbox/xmin")) / width
ymin = float(obj.findtext("bndbox/ymin")) / height
xmax = float(obj.findtext("bndbox/xmax")) / width
ymax = float(obj.findtext("bndbox/ymax")) / height
box = [xmax - xmin, ymax - ymin]
boxes.append(box)
else:
continue
return np.array(boxes)
if __name__ == '__main__':
anchors_txt = open(ANCHORS_TXT_PATH, "w")
train_boxes = load_data(ANNOTATION_PATH, CLASS_NAMES)
count = 1
best_accuracy = 0
best_anchors = []
best_ratios = []
for i in range(10): ##### 可以修改,不要太大,否則時間很長
anchors_tmp = []
clusters = kmeans(train_boxes, k=CLUSTERS)
idx = clusters[:, 0].argsort()
clusters = clusters[idx]
# print(clusters)
for j in range(CLUSTERS):
anchor = [round(clusters[j][0] * 640, 2), round(clusters[j][1] * 640, 2)]
anchors_tmp.append(anchor)
print(f"Anchors:{anchor}")
temp_accuracy = avg_iou(train_boxes, clusters) * 100
print("Train_Accuracy:{:.2f}%".format(temp_accuracy))
ratios = np.around(clusters[:, 0] / clusters[:, 1], decimals=2).tolist()
ratios.sort()
print("Ratios:{}".format(ratios))
print(20 * "*" + " {} ".format(count) + 20 * "*")
count += 1
if temp_accuracy > best_accuracy:
best_accuracy = temp_accuracy
best_anchors = anchors_tmp
best_ratios = ratios
anchors_txt.write("Best Accuracy = " + str(round(best_accuracy, 2)) + '%' + "\r\n")
anchors_txt.write("Best Anchors = " + str(best_anchors) + "\r\n")
anchors_txt.write("Best Ratios = " + str(best_ratios))
anchors_txt.close()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
clauculate_anchors.py 內要修改為自己數據集的路徑,如下:
FILE_ROOT = "xxx" # 根路徑
ANNOTATION_ROOT = "xxx" # 數據集標簽文件夾路徑
ANNOTATION_PATH = FILE_ROOT + ANNOTATION_ROOT
1
2
3
運行clauculate_anchors.py跑完會生成一個文件 anchors.txt,里面有得出的建議先驗框anchors,內容如下:
2-2) 選擇一個你需要的模型
在yolov5目錄下的model文件夾下是模型的配置文件,這邊提供s、m、l、x版本,逐漸增大(隨着架構的增大,訓練時間也是逐漸增大),假設采用yolov5s.yaml,只用修改一個參數,把nc改成自己的類別數;如果anchors是重新生成的,也需要修改,根據anchors.txt 中的 Best Anchors 修改,需要取整(可選) 如下:
至此,自定義數據集已創建完畢,接下來就是訓練模型了。
三.模型訓練
1.下載預訓練模型
源碼中在yolov5目錄下的weights文件夾下提供了下載四種預訓練模型的腳本----download_weights.sh
執行這個shell腳本就可以下載,這里weights的下載可能因為網絡而難以進行,有人分享了百度網盤的下載地址,但是不一定是v3.0版本最新的預訓練模型,如果不是v3.0版本最新的預訓練模型,在訓練時會報錯如下:
出現這個問題原因是預訓練模型下載的不是最新的,例如V3.0的代碼,下載的是V2.0或者V1.0的模型權重就會報錯,重新下載最新的模型權重即可解決。我是通過官網源碼給的鏈接FQ在google雲盤上下載的。
2.訓練
在train.py進行以下幾個修改:
以上參數解釋如下:
epochs:指的就是訓練過程中整個數據集將被迭代多少次,顯卡不行你就調小點。
batch-size:一次看完多少張圖片才進行權重更新,梯度下降的mini-batch,顯卡不行你就調小點。
cfg:存儲模型結構的配置文件
data:存儲訓練、測試數據的文件
img-size:輸入圖片寬高,顯卡不行你就調小點。
rect:進行矩形訓練
resume:恢復最近保存的模型開始訓練
nosave:僅保存最終checkpoint
notest:僅測試最后的epoch
evolve:進化超參數
bucket:gsutil bucket
cache-images:緩存圖像以加快訓練速度
weights:權重文件路徑
name: 重命名results.txt to results_name.txt
device:cuda device, i.e. 0 or 0,1,2,3 or cpu
adam:使用adam優化
multi-scale:多尺度訓練,img-size +/- 50%
single-cls:單類別的訓練集
之后運行訓練命令如下:
python train.py --img 640 --batch 16 --epoch 300 --data data/ab.yaml --cfg models/yolov5s.yaml --weights weights/yolov5s.pt --device '0' # 0號GPU
1
根據自己的硬件配置修改參數,訓練好的模型會被保存在yolov5目錄下的runs/exp0/weights/last.pt和best.pt,詳細訓練數據保存在runs/exp0/results.txt文件中。
如果Cuda版本不對(不是>=10.1版本),在調用GPU訓練時會報錯如下:
3.訓練過程可視化
利用tensorboard可視化訓練過程,訓練開始會在yolov5目錄生成一個runs文件夾,利用tensorboard打開即可查看訓練日志,命令如下:
tensorboard --logdir=runs
1
由於TensorFlow2.0及以上版本現在支持CUDA10.0,還不支持CUDA10.1,因此我在使用TensorFlow2.0以上版本利用tensorboard打開訓練日志時報錯如下:
於是我改用tensorflow-gpu1.13.1版本的環境,利用tensorboard即可成功打開並查看訓練日志,可視化結果如上圖。
至此YOLOv5訓練自己的數據集,訓練階段已完畢。
YOLOv5訓練速度更快,准確率更高,個人感覺最大的優勢是相比YOLOv3,YOLOv5的模型更加輕量級,同樣的數據集訓練出來的模型大小是YOLOv3的將近四分之一大小。
四.模型測試
評估模型好壞就是在有標注的測試集或者驗證集上進行模型效果的評估,在目標檢測中最常使用的評估指標為mAP。在test.py文件中指定數據集配置文件和訓練結果模型,如下:
通過下面的命令進行模型測試:
python test.py --data data/ab.yaml --weights runs/exp1/weights/best.pt --augment
1
模型測試效果如下:
五.模型推理
最后,模型在沒有標注的數據集上進行推理,在detect.py文件中指定測試圖片和測試模型的路徑,其他參數(img_size、置信度object confidence threshold、IOU threshold for NMS)可自行修改,如下:
使用下面的命令(該命令中save_txt選項用於生成結果的txt標注文件,不指定則只會生成結果圖像),其中,weights使用最滿意的訓練模型即可,source則提供一個包含所有測試圖片的文件夾路徑即可。
python detect.py --weights runs/exp1/weights/best.pt --source inference/images/ --device 0 --save-txt
1
測試完畢后,每個測試圖片會在指定的inference/output輸出文件夾中生成結果圖片和同名的txt文件,如下:
每個txt會生成一行一個目標的信息,信息包括類別序號、xcenter ycenter w h,后面四個為bbox位置,均為歸一化數值,如下圖:
在進行模型推理時,無論是加載模型的速度還是對測試圖片的推理速度,都能明顯感覺到YOLOv5比YOLOv3速度快,尤其是加載模型的速度,因為同樣的數據集訓練出來的模型YOLOv5更加輕量級,模型大小減小為YOLOv3的將近四分之一。
至此YOLOv5訓練自己的數據集整個過程:制作數據集----模型訓練----模型測試----模型推理階段已全部完成。
————————————————
版權聲明:本文為CSDN博主「深度學習菜鳥」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/qq_36756866/article/details/109111065