【tph-yolov5】使用tph-Yolov5训练自己的数据集

一、环境配置及源代码运行

推荐参考我前一篇博客

二、数据集准备

1、新建数据集文件夹dataset
因为其他项目还要用到这个数据,所以我这里是单独建了一个数据集文件夹,没这个要求的可讲文件夹直接放在你的TPH-Yolov5目录下。
2、在dataset下新建两个文件夹images和annotations
**images:**用于存放要标准的图片(jpg格式);
**annotations:**用于存放图片标注文件,采用voc格式。
在这里插入图片描述3、图片重命名
因为原始图片命名比较乱,这里我在数据标准前先将数据统一命名,也方便后面数据检查。
重命名前图片名称
重命名前图片名称重命名后图片名称
在这里插入图片描述

三、使用labelImg标注图片

1.安装labelImg
labelImg官方下载连接
官方提供了各种安装方法,本人直接下载了打包软件。如果你无法进入github,这里给出了百度网盘链接。
标注文件链接:https://pan.baidu.com/s/1hFX4j_dZAamU9YIEp3uiZA
提取码:70al
2.使用labelImag
官方安装版本运行比较麻烦,请按照官方说明文件进行。建议直接下载我给的链接文件,点开后可直接运行。

  1. 自动保存标注文件
    点击上面导航栏view,勾选auto saving自动保存,标注文件存储格式可自行选择,默认为XML格式,可更改为yolo,这里因为其他项目需求直接使用默认格式,后面再转为yolo。
    在这里插入图片描述
  2. 物体标注
    点击左方边栏或者屏幕右键选择Create RectBox即可进行标注。标注物体时尽可能拟合物体外框就行,具体要求参考个人项目标准。
    在这里插入图片描述
  3. 快捷键推荐
    A:移动到上一张图片
    D:移动到下一张图片
    W:标注图片

四、划分数据集以及修改配置文件

1、划分训练集、验证集、测试集
程序如下:

# 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()

划分后结果如图,这里我没有单独划分测试集,有需要的朋友可自行修改。

在这里插入图片描述2、XML格式转yolo_txt格式
代码如下:(可按照注释进行修改)

# -*- coding: utf-8 -*-
import xml.etree.ElementTree as ET
import os
from os import getcwd

sets = ['train', 'val', 'test']
classes = ["meter"]   # 改成自己的类别
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/hm/LFY/dataset/annotations/%s.xml' % (image_id), encoding='UTF-8')
    out_file = open('/home/hm/LFY/dataset/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/hm/LFY/dataset/labels/'):
        os.makedirs('/home/hm/LFY/dataset/labels/')
#上一步得到的文件名称
    image_ids = open('/home/hm/LFY/dataset/split/demo/%s.txt' % (image_set)).read().strip().split()
#生成yolo标注文件的绝对路径,方便之后模型读取图片和标签  
    if not os.path.exists('/home/hm/LFY/dataset/dataSet_path/'):
        os.makedirs('/home/hm/LFY/dataset/dataSet_path/')
     
    list_file = open('dataSet_path/%s.txt' % (image_set), 'w')
    # 这行路径不需更改,这是相对路径
    for image_id in image_ids:
        list_file.write('/home/hm/LFY/dataset/images/%s.jpg\n' % (image_id))
        convert_annotation(image_id)
    list_file.close()

转换完之后会生成一个labels文件夹,里面为不同图像yolo格式的标注文件。每个图像都对应一个txt文件,文件每一行为一个目标信息,第一列为目标类别,往后依次是x_center, y_center, width, height。
在这里插入图片描述

dataSet_path文件夹包含三个数据集的txt文件,train.txt等txt文件为划分后图像所在位置的绝对路径,如train.txt就含有所有训练集图像的绝对路径。

在这里插入图片描述
存储了图片的绝对路径,可按照自己的需求更改。

在这里插入图片描述
3、配置文件
在tph-yolov5目录的data文件夹下新建一个dataset.yaml文件(自定义命名),用记事本打开。输入内容:训练集以及验证集(train.txt和val.txt)的绝对路径(前一步通过xml_to_yolo.py生成的),然后就是目标的类别数目和类别名称。

在这里插入图片描述

给出模板:冒号后面需要加空格

train: D:/Yolov5/yolov5/VOCData/dataSet_path/train.txt
val: D:/Yolov5/yolov5/VOCData/dataSet_path/val.txt

# number of classes
nc: 2

# class names
names: ["light", "post"]

4、聚类获得先验框

  • 4.1生成anchors文件

在dataset目录下创建两个程序kmeans.py和clauculate_anchors.py,不需要运行 kmeans.py,运行 clauculate_anchors.py 即可。
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))

运行clauculate_anchors.p后,会调用kmeans.py聚类生成新的anchors。

# -*- coding: utf-8 -*-
# 根据标签文件求先验框

import os
import numpy as np
import xml.etree.cElementTree as et
from kmeans import kmeans, avg_iou

FILE_ROOT = "D:/Yolov5/yolov5/VOCData/"     # 根路径
ANNOTATION_ROOT = "Annotations"   # 数据集标签文件夹路径
ANNOTATION_PATH = FILE_ROOT + ANNOTATION_ROOT

ANCHORS_TXT_PATH = "D:/Yolov5/yolov5/VOCData/anchors.txt"   #anchors文件保存位置

CLUSTERS = 9
CLASS_NAMES = ['light', 'post']   #类别名称

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()

会生成anchors文件。如果生成文件为空,重新运行即可。

  • 4.2修改模型配置文件
    在tph-yolov5目录的models文件夹下是模型的配置文件,有很多版本,官方选择的训练版本是yolov5l-xs-tph.yaml,这里我们也同样选用这个版本。
    这里我们需要修改两个参数
    首先把nc改成自己的标注类别数;然后需要将anchors修改为上一步得到的结果(此处需要取整,向上/向下取整都可)。保持yaml中anchors格式不变,按照顺序一一对应即可。

五、模型训练

  1. 开始训练
    回到tph-yolov5目录下查看train.py程序,注意查看weights、cfg、data、hyp、epochs、batchsize、imgsz、device这几个参数,根据实际情况进行修改。
    训练命令:

python train.py --img 1536 --adam --batch 4 --epochs 80 --data ./data/VisDrone.yaml --weights yolov5l.pt --hyp data/hyps/hyp.VisDrone.yaml --cfg models/yolov5l-xs-tph.yaml --name v5l-xs-tph

上面是官方命令,每一项可根据自身实际情况进行修改。
参数解释:
img:这里我暂时不明白,先猜测一下是输入图片大小。
batch、epochs:这个不用多说了
data :存储训练、测试数据的文件
weights:预训练权重
hyp:一些参数值,可不更改
cfg:网络配置文件
name:命名

  • 2.训练过程

下面是我训练的截图,只是一个示范。模型的P、R都是零,可能是其他地方出现了问题,之后在新的博客说明原因。此处只是给出一个可以训练的完整路程。
在这里插入图片描述
模型训练结果会存放在yolov5目录下的runs/train/下。
到此一个训练的过程就结束了,后续先解决上面P、R为零的问题。在进行代码的解析和验证以及模型评估。

六、参考链接

Yolov5训练自己的数据集(详细完整版)

七、补充

上课的时候随便随便试了一下,问题解决了。所以决定把测试过程写完结束。

  • 相关问题
    1、OOM
    如果出现OOM,可尝试调小图片或者减少batch-size。如果不行可以降低epoch,或者降低线程workes,其默认为8。

建议第一次试用的时候图片数量为50+,epoch在50以上。我这样就解决了上面P、R为零的问题。

在这里插入图片描述图中cls为零,是因为我采用的是单类图片,即图片只有一个类别,所以cls本就为0。
2、重复训练
这里我没遇到,提前写着预备一下,可清除缓存。
在这里插入图片描述

  • 测试效果

可使用刚刚训练好的模型best.pt来测试,模型存储在tph-yolov5目录下的runs/train/下。

python path/to/detect.py --source path/to/img.jpg --weights yolov5s.pt --img 640

测试结果保存在tph-yolov5/runs/detect/exp下。

到此,基础的跑通就结束了,接下来就是加大数据集然后进行模型优化了。

  • 6
    点赞
  • 85
    收藏
    觉得还不错? 一键收藏
  • 36
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 36
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值