源代码
我所使用的是yolov5-v6.1版本,下载地址:
yolov5-6.1代码
解压完成后,在Anaconda Prompt中进入代码所在文件夹,执行以下代码:
pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
它可以帮助我们安装所需要的依赖,并且不会重复安装
准备数据集
使用官方数据集
初次训练我是用的是官方提供的数据集:Pascal VOC Dataset,下载地址:
Pascal VOC Dataset
解压后得到以下文件夹:
其中我们需要的是Annotations和JPEGImages这两个文件夹,后一个文件夹中存放的是大量图片,前一张图片中存放的是每一张图片对应的标签信息,为.xml格式。我们需要将这两个文件夹放入yolov5-6.1文件夹中data文件夹下,并且将JPEGImages重命名为images
制作自己的数据集
制作自己的数据集需要用到工具:LabelImg
LabelImg工具下载地址
在Anaconda Prompt中进入Labelimg-master文件夹,依次输入以下命令:
conda install pyqt=5
conda install -c anaconda lxml
pyrcc5 -o libs/resources.py resources.qrc
安装好后便可以打开工具使用,在这之前,我们可以将文件夹data中的predefined_classes.txt文件根据自己的需求做好更改:
命令行输入:
python labelImg.py
打开工具箱如图(将查看下自动保存模式勾选上):
左侧PascalVOC表示保存类型为我们需要的.xml格式。我们可以点击创建区块来自己绘制图框:
绘制完成后点保存即可
划分数据集
进入yolov5-6.1文件夹,创建.py文件:maketxt.py,程序内容如下:
# coding:utf-8
import os
import random
import argparse
parser = argparse.ArgumentParser()
#xml文件的地址,根据自己的数据进行修改 xml一般存放在Annotations下
parser.add_argument('--xml_path', default='data/Annotations', type=str, help='input xml label path')
#数据集的划分,地址选择自己数据下的ImageSets/Main
parser.add_argument('--txt_path', default='data/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()
在data文件夹中创建ImageSets文件夹,然后执行:
python maketxt.py
可以看到ImageSets/Main文件夹生成了如下四个文件:
返回yolov5-6.1文件夹,创建.py文件:voc_label.py,内容如下:
# -*- coding: utf-8 -*-
import xml.etree.ElementTree as ET
import os
from os import getcwd
sets = ['train', 'val', 'test']
classes = ['person','bird','cat','cow','dog','horse','bicycle','boat','bus','car','motorbike','train','bottle','chair','diningtable','pottedplant','sofa','tvmonitor'] # 改成自己的类别
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('D:/AI_learning/YOLO/yolov5/yolov5-6.1/data/Annotations/%s.xml' % (image_id), encoding='UTF-8')
out_file = open('D:/AI_learning/YOLO/yolov5/yolov5-6.1/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('D:/AI_learning/YOLO/yolov5/yolov5-6.1/data/labels/'):
os.makedirs('D:/AI_learning/YOLO/yolov5/yolov5-6.1/data/labels/')
image_ids = open('D:/AI_learning/YOLO/yolov5/yolov5-6.1/data/ImageSets/Main/%s.txt' % (image_set)).read().strip().split()
if not os.path.exists('D:/AI_learning/YOLO/yolov5/yolov5-6.1/data/dataSet_path/'):
os.makedirs('D:/AI_learning/YOLO/yolov5/yolov5-6.1/data/dataSet_path/')
list_file = open('data/dataSet_path/%s.txt' % (image_set), 'w')
for image_id in image_ids:
list_file.write('D:/AI_learning/YOLO/yolov5/yolov5-6.1/data/images/%s.jpg\n' % (image_id))
convert_annotation(image_id)
list_file.close()
注意将其中的classes以及路径改成自己的
在data文件夹创建dataSet_path和labels文件夹,执行:
python voc_label.py
可以看到labels文件夹生成了对应的标签数字信息,dataSet_path文件夹生成了每张图片对应的路径信息
写自己的配置文件
在data文件夹新建一个.yaml文件:myyolov5.yaml(名字自定义即可),内容如下:
train: D:/AI_learning/YOLO/yolov5/yolov5-6.1/data/dataSet_path/train.txt
val: D:/AI_learning/YOLO/yolov5/yolov5-6.1/data/dataSet_path/val.txt
# number of classes
nc: 20 #训练的类别
# class names
names: ['person','bird','cat','cow','dog','horse','bicycle','boat','bus','car','motorbike','train','bottle','chair','diningtable','pottedplant','sofa','tvmonitor']
包括刚生成的train、val文件的绝对路径,检测种类数与标签
聚类生成先验框
data文件下下创建: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") # 如果报这个错,可以把这行改成pass即可
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))
之后创建.py文件:calculate_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 = "D:/AI_learning/YOLO/yolov5/yolov5-6.1/data/" # 根路径
ANNOTATION_ROOT = "Annotations" # 数据集标签文件夹路径
ANNOTATION_PATH = FILE_ROOT + ANNOTATION_ROOT
ANCHORS_TXT_PATH = "D:/AI_learning/YOLO/yolov5/yolov5-6.1/data/anchors.txt" #anchors文件保存位置
CLUSTERS = 9
CLASS_NAMES = ['person','bird','cat','cow','dog','horse','bicycle','boat','bus','car','motorbike','train','bottle','chair','diningtable','pottedplant','sofa','tvmonitor']
#类别名称
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()
注意将路径信息与类别名称修改为自己的,之后执行:
python calculate_anchors.py
会生成anchors.txt,它是根据标签框信息自动生成的先验框,之后会用到
修改配置文件
回到yolov5-6.1文件夹,打开models文件夹,其中有五种.yaml文件:x s n m l,选择哪个进行训练我们就修改哪个,这里我们使用yolov5s.yaml:
首先将训练类别数改成自己需要的,然后根据刚才生成的anchors.txt文件中的Best Anchors一一修改anchors(需要取整),改好后保存即可
训练
以上全部执行过后便可开始训练,在yolov5-6.1文件夹下执行以下命令:
python train.py --data data/myyolov5.yaml --cfg models/yolov5s.yaml --weights '' --batch-size 16 --epochs 100
其中后几个参数根据自己机器性能修改即可,训练过程及结果截图:
我们在runs/train/exp4中可以看到以下内容:
其中weights文件夹中包含我们的训练模型best.pt,用于测试使用
测试
在data文件夹创建sample文件夹,将待检测图片放入其中,回到yolov5-6.1文件夹,执行:
python detect.py --weights runs/train/exp4/weights/best.pt --source data/sample/xxx.xxx
检测结果如图:
打开结果显示保存至的文件夹,可以看到测试结果:
至此我们基本完成了基于yolov5的目标检测任务。文章来源:https://www.toymoban.com/news/detail-444298.html
参考文章文章来源地址https://www.toymoban.com/news/detail-444298.html
到了这里,关于利用yolov5完成目标检测详细过程的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!