YoloV5剛剛于2021年1月發(fā)布了4.0版本,涉及的變化主要包括:替換激活函數(shù)、精簡模型結(jié)構(gòu)、引入W&B等?,F(xiàn)準(zhǔn)備嘗試基于YoloV5訓(xùn)練安全帽檢測模型,借此熟悉YoloV5的網(wǎng)絡(luò)結(jié)構(gòu)、損失函數(shù)、數(shù)據(jù)增強方法等。
地址:https://github.com/ultralytics/yolov5
環(huán)境配置
由于4.0版本引入的nn.SiLU() 是在pytorch1.7.0才開始支持,因此pytorch版本需>=1.7.0。
git clone https://github.com/ultralytics/yolov5.git
mv yolov5/ yolov5-4.0/
mkvirtualenv yolov5-4.0
pip install https://download.pytorch.org/whl/cu102/torch-1.7.0-cp36-cp36m-linux_x86_64.whl
pip install torchvision==0.8.1
cd yolov5-4.0/
pip install -r requirements.txt
數(shù)據(jù)準(zhǔn)備
數(shù)據(jù)集來源于https://github.com/njvisionpower/Safety-Helmet-Wearing-Dataset,下載數(shù)據(jù)集解壓后目錄結(jié)構(gòu)如下圖:

其中, Annotations文件夾中是xml格式的標(biāo)簽文件,JPEGImages文件夾中是圖像文件。為了基于該數(shù)據(jù)集訓(xùn)練Yolov5模型,我們需要進一步將其處理為Yolov5適配的格式和目錄結(jié)構(gòu)。
首先按照下圖創(chuàng)建目錄結(jié)構(gòu):

然后運行下列代碼生成適配YoloV5格式的數(shù)據(jù)集:
import os, sys
import shutil
from tqdm import tqdm
import xml.etree.ElementTree as ET
classes = ["hat", "person"]
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 # x_center
y = y * dh # y_center
w = w * dw # width
h = h * dh # height
return (x, y, w, h)
def parse_xml(xml_path, dst_label_path):
anno_xml = xml_path
anno_txt = dst_label_path
if os.path.exists(anno_xml):
xml = open(anno_xml, "r")
txt = open(anno_txt, "w")
tree = ET.parse(xml)
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'):
cls = obj.find('name').text
difficult = obj.find('difficult').text
if cls not in classes or difficult == 1:
continue
cls_id = classes.index(cls)
xmlbox = obj.find('bndbox')
bbox = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text),
float(xmlbox.find('ymax').text))
yolo_bbox = convert((w, h), bbox)
yolo_anno = str(cls_id) + " " + " ".join([str(i) for i in yolo_bbox]) + '\n'
txt.write(yolo_anno)
xml.close()
txt.close()
else:
print(anno_xml, "文件不存在")
def copy_to(src, dst):
shutil.copyfile(src, dst)
if __name__== "__main__":
sets = ["train", "val", "test"]
for s in sets:
name_path = "VOC2028/ImageSets/Main/{}.txt".format(s)
f = open(name_path, "r")
names = f.readlines()
f.close()
for name in tqdm(names):
name = name.replace('\n', '').replace('\r', '')
image_path = r"VOC2028/JPEGImages/{}.jpg".format(name)
xml_path = r"VOC2028/Annotations/{}.xml".format(name)
dst_image_path = r"SHWD/images/{}/{}.jpg".format(s, name)
dst_label_path = r"SHWD/labels/{}/{}.txt".format(s, name)
if os.path.exists(image_path) and os.path.exists(xml_path):
parse_xml(xml_path, dst_label_path)
if not os.path.exists(dst_image_path):
copy_to(image_path, dst_image_path)
else:
print(dst_image_path, "文件已存在")
else:
print(image_path, xml_path)
注意:由于數(shù)據(jù)集中存在少量后綴為大寫JPG的圖像,因此在運行上述代碼時會漏掉部分數(shù)據(jù)沒處理,需要修改image_path = r"VOC2028/JPEGImages/{}.jpg".format(name)為image_path = r"VOC2028/JPEGImages/{}.JPG".format(name)后再次運行,才能完成全部數(shù)據(jù)的處理。
處理完成后的每一幅圖像和其對應(yīng)標(biāo)簽文件的路徑只有文件后綴名以及images-labels字段的區(qū)別,代碼讀取數(shù)據(jù)集時則只需要替換這兩個位置就可訪問相對應(yīng)的數(shù)據(jù):
SHWD/images/train/001320.jpg
SHWD/labels/train/001320.txt
轉(zhuǎn)換后的txt標(biāo)簽文件中如下圖所示,每一行表示一個目標(biāo)框,行內(nèi)五個元素分別是類別、中心點x坐標(biāo)、中心點y坐標(biāo)、寬、高,數(shù)值都進行了歸一化處理。


訓(xùn)練模型
- 創(chuàng)建shwd.yaml文件配置數(shù)據(jù)
# train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/]
train: SHWD/images/train
val: SHWD/images/val
test: SHWD/images/test
# number of classes
nc: 2
# class names
names: ["hat", "no-hat"]
- 訓(xùn)練

這里選擇YOLOv5s網(wǎng)絡(luò)來訓(xùn)練安全帽檢測,
$ python train.py --img 640 --batch 16 --epochs 50 --data data/shwd.yaml --weights yolov5s.pt
W&B可視化
Weights & Biases現(xiàn)在集成到了YOLOV5的4.0版本,用于實時可視化訓(xùn)練記錄,可以更好地觀測和對比網(wǎng)絡(luò)的訓(xùn)練情況。
首先用pip安裝wandb:
pip install wandb
然后在運行上一節(jié)的訓(xùn)練命令時,終端會提示進行wandb的相關(guān)配置:

按照要求創(chuàng)建賬戶后,會提供一個API key用于終端賬戶驗證,然后在網(wǎng)絡(luò)訓(xùn)練期間,可以訪問https://www.wandb.com/查看實時更新。

參考
https://blog.csdn.net/ayiya_Oese/article/details/112249173
https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data