🔥本文 GitHub https://github.com/kzbkzb/Python-AI已收錄
大家好,我是K同學啊!
我們接著上一篇文章 深度學習100例 | 第51天-目標檢測演算法(YOLOv5)(入門篇) 配置完YOLOv5需要的環境后,今天我們試著用YOLOv5訓練自己的資料,(在開始本教程前,記得先跑一遍入門篇,確保其他環境是正常的)
有圖有真相,先看看我昨天的運行結果

【YOLOv5 原始碼地址】
🚀 我的環境:
- 語言環境:Python3.8
- 編譯器:PyCharm
- 深度學習環境:
- torch==1.10.0+cu113
- torchvision==0.11.1+cu113
- 顯卡:GeForce RTX 3080
文章目錄
- 一、準備好自己的資料
- 二、運行 split_train_val.py 檔案
- 三、生成 train.txt、test.txt、val.txt 檔案
- 四、創建 ab.yaml 檔案
- 五、聚類得出先驗框
- 六、開始用自己的資料集訓練模型
一、準備好自己的資料
我的目錄結構是這樣子的
- 主目錄
- paper_data(自己創建一個檔案夾,將資料放到這里)
- Annotations(放置我們的.xml檔案)
- images(放置圖片檔案)
- ImageSets
- Main(會在該檔案夾內自動生成 train.txt、val.txt、test.txt 和 trainval.txt 四個檔案,存放訓練集、驗證集、測驗集圖片的名字)
- paper_data(自己創建一個檔案夾,將資料放到這里)
你將會看如下的目錄結構:

Annotations檔案夾為xml檔案,我的檔案如下:

我images檔案位.png格式,官方的為.jpg,不過問題不大后面改一下代碼即可(后面會講解)

二、運行 split_train_val.py 檔案
ImageSets檔案夾下面有個Main子檔案夾,其下面存放了 train.txt、val.txt、test.txt 和 trainval.txt 四個檔案,它們是通過 split_train_val.py 檔案來生成的,
split_train_val.py 檔案的位置如下:

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()
運行 split_train_val.py 檔案后你將得到 train.txt、val.txt、test.txt 和 trainval.txt 四個檔案,結果如下:

三、生成 train.txt、test.txt、val.txt 檔案
先看看我們要生成的檔案位置

開始辦事,現在我們需要的是 voc_label.py 檔案,其位置如下:

voc_label.py 檔案的內容如下:
# -*- coding: utf-8 -*-
import xml.etree.ElementTree as ET
import os
from os import getcwd
sets = ['train', 'val', 'test']
classes = ["unripe citrus"] # 改成自己的類別
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('./Annotations/%s.xml' % (image_id), encoding='UTF-8')
out_file = open('./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
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('./labels/'):
os.makedirs('./labels/')
image_ids = open('./ImageSets/Main/%s.txt' % (image_set)).read().strip().split()
list_file = open('./%s.txt' % (image_set), 'w')
for image_id in image_ids:
list_file.write(abs_path + '/images/%s.png\n' % (image_id)) # 注意你的圖片格式,如果是.jpg記得修改
convert_annotation(image_id)
list_file.close()
運行 voc_label.py 檔案,你將會得到上面截圖中 train.txt、test.txt、val.txt三個檔案,檔案內容如下:

四、創建 ab.yaml 檔案
這個檔案名是我隨意取的,這個可以做出改變的哈
ab.yaml 檔案的位置如下:

我的 ab.yaml 檔案內容如下:
#path: ../datasets/coco # dataset root dir
train: ./paper_data/train.txt # train images (relative to 'path') 118287 images
val: ./paper_data/val.txt # train images (relative to 'path') 5000 images
#test: test-dev2017.txt
nc: 1 # number of classes
names: ['unripe citrus'] # 改成自己的類別
五、聚類得出先驗框
首先,我們需要準備 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.py 的檔案,該檔案同樣位于主目錄下,其內容如下:
# -*- coding: utf-8 -*-
# 根據標簽檔案求先驗框
import os
import numpy as np
import xml.etree.cElementTree as et
from kmeans import kmeans, avg_iou
FILE_ROOT = "./paper_data/" # 根路徑
ANNOTATION_ROOT = "Annotations" # 資料集標簽檔案夾路徑
ANNOTATION_PATH = FILE_ROOT + ANNOTATION_ROOT
print(ANNOTATION_PATH)
ANCHORS_TXT_PATH = "./data/anchors.txt"
CLUSTERS = 1 # 類別數注意修改
CLASS_NAMES = ['unripe citrus'] #修改為自己的類別
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 = []
print(train_boxes)
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()
運行 clauculate_anchors.py 檔案,我們將會得到 anchors.txt 檔案

六、開始用自己的資料集訓練模型
輸入命令:
python train.py --img 900 --batch 2 --epoch 100 --data data/ab.yaml --cfg models/yolov5s.yaml --weights weights/yolov5s.pt --device '0'
就可以直接訓練我們自己的資料集啦,我最后的運行結果如下:

如果你還有問題無法解決可以加我微信(mtyjkh_)或者直接在下面留言哈,看到后都會盡快回復你的,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/348385.html
標籤:其他
上一篇:程式與邏輯演算法學習03
