目錄
0.下載編譯YOLOv2
YOLOv2主頁:https://pjreddie.com/darknet/yolov2/
系統環境:Ubuntu16.04、Nvidia TITAIN XP 顯卡、Nvidia TITAIN XP 顯卡驅動已經按照好。
0.首先按照官網的流程,將darknet 框架的代碼下載下來,根據自己的系統情況,適當修改Makefile文件,
一般用到GPU 和 CUDNN:
所以設置:
GPU=1
CUDNN=1
並根據NVIDIA GPU的 情況設置:
ARCH= -gencode arch=compute_30,code=sm_30 \
-gencode arch=compute_35,code=sm_35 \
-gencode arch=compute_50,code=[sm_50,compute_50] \
-gencode arch=compute_52,code=[sm_52,compute_52]
# -gencode arch=compute_20,code=[sm_20,sm_21] \ This one is deprecated?
# This is what I use, uncomment if you know your arch and want to specify
# ARCH= -gencode arch=compute_52,code=compute_52
再查看Training YOLO on VOC 一節
1.按照Pascal VOC的格式準備自己的數據
我這裏將所以VOC2007文件下的圖像數據作爲訓練/驗證集合;將VOC2012下的所以圖像文件作爲測試集合。
文件結構:
VOCdevkit 文件夾下有VOC2007文件夾 和 VOC2012文件夾
以VOC2007文件夾爲例:
VOC2007文件夾下有Annotations文件夾、ImageSets文件夾、JPEGImages文件夾;
Annotations文件夾裏是所以的VOC格式的目標標籤xml文件;
JPEGImages文件夾下是所有的jpg圖像文件;
一張jpg圖像文件 對於一個 xml標籤文件,且二者的命名相同 ,以.jpg / .xml後綴來區分。
ImageSets文件夾下面包含:Layout文件夾、Main文件夾、Segmentation文件夾,這裏,我們只做目標檢測,就用到Main文件夾,
Main文件夾下面有 訓練/驗收/測試 數據集標籤的txt文件;
需要使用python 代碼 根據 Annotations文件夾 和 JPEGImages文件夾的內容 生成 Main文件夾下面有 訓練/驗收/測試 數據集標籤的txt文件 。
generateFileNameLists.py如下:
#coding=utf-8
import os
import random
#其實就是將一批數據 按照比例劃分爲 訓練集:驗證集:測試集
#訓練集 和 測試集 會合併成 trainval 集
# trainval 包含訓練集和驗證集
#我這裏設置了 trainval_percent 佔所以圖像數據50%的比例;
#而在 trainval 集合內部,有劃分爲train 和 val 集合,二者比例爲 1:1
trainval_percent = 0.5 #trainval:test=1:1 劃分比例trainval比 test =1:1
train_percent = 0.5 #in trainval: train:val=1:1
xmlfilepath = 'Annotations'
txtsavepath = 'ImageSets/Main'
total_xml = os.listdir(xmlfilepath)
num=len(total_xml)
list=range(num)
tv=int(num*trainval_percent)
tr=int(tv*train_percent)
trainval= random.sample(list,tv)
train=random.sample(trainval,tr)
ftrainval = open(txtsavepath+'/trainval.txt', 'w')
ftest = open(txtsavepath+'/test.txt', 'w')
ftrain = open(txtsavepath+'/train.txt', 'w')
fval = open(txtsavepath+'/val.txt', 'w')
for i in list:
name=total_xml[i][:-4]+'\n' # 只顯示文件名 ,一行一個文件名
if i in trainval:
ftrainval.write(name)
if i in train:
ftrain.write(name)
else:
fval.write(name)
else:
ftest.write(name)
ftrainval.close()
ftrain.close()
fval.close()
ftest .close()
在正確的路徑下運行以上python腳本,就在Main文件夾下生成了,具體的劃分比例可以在以上代碼中修改。
test.txt
train.txt
trainval.txt
val.txt
就是將一批數據劃分爲了train.txt、test.txt 、 val.txt ;
trainval.txt 是train.txt 和 val.txt 的合併。
這些文件夾的每一行就是一張圖像的名稱(不帶後綴) 也是一張圖像中目標的標籤文件的名稱(不帶後綴):如下:
125_dirty_train
649_normal_train
796_normal_train
現在已經準備好了pascal voc 2007 和 2012數據集(jpg圖像文件、xml每張圖像的目標標籤文件 、txt 的數據集劃分文件)
2.根據Training YOLO on VOC 一節,將pascal voc數據集標籤格式轉換 darknet yolo 框架需要的標籤格式:
Generate Labels for VOC
Now we need to generate the label files that Darknet uses. Darknet wants a .txt
file for each image with a line for each ground truth object in the image that looks like:
<object-class> <x> <y> <width> <height>
Where x
, y
, width
, and height
are relative to the image's width and height. To generate these file we will run the voc_label.py
script in Darknet's scripts/
directory.
Darknet 目標檢測網絡 需要的標籤格式爲:
物體類別 物體框左上角x座標對圖像寬度的相對值 物體框左上角y座標對圖像高度的相對值 物體框寬度對圖像寬度的相對值 物體框高度對圖像高度的相對值
比如:一幅圖像 爲M*N 像素 在其中有一物體class1 的矩陣框座標以及矩形框寬高爲:(x',y',w',h')
所以,在VOCdevkit 下的VOC2007 和VOC2012 文件夾下的labels 文件夾下,將生成每一幅圖像對應的目標物體的標籤文件
.txt 文件,文件名與 圖像的文件名一致。
class1 x'/W y'/H w'/W h'/H
class2 x''/W y''/H w''/W h''/H
一個.txt 文件的每一行對應一幅圖像中的一個目標ground truth.
在darknet主目錄下運行以下腳本:voc_label.py
import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import join
sets=[('2007', 'train'), ('2007', 'val'), ('2007', 'test'),('2012', 'train'), ('2012', 'val'), ('2012', 'test')]
'''
classes = ["aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"]
'''
classes = ["1"]
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
w = w*dw
y = y*dh
h = h*dh
return (x,y,w,h)
def convert_annotation(year, image_id):
in_file = open('VOCdevkit/VOC%s/Annotations/%s.xml'%(year, image_id))
out_file = open('VOCdevkit/VOC%s/labels/%s.txt'%(year, 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))
bb = convert((w,h), b)
out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
wd = getcwd()
for year, image_set in sets:
if not os.path.exists('VOCdevkit/VOC%s/labels/'%(year)):
os.makedirs('VOCdevkit/VOC%s/labels/'%(year))
image_ids = open('VOCdevkit/VOC%s/ImageSets/Main/%s.txt'%(year, image_set)).read().strip().split()
list_file = open('%s_%s.txt'%(year, image_set), 'w')
for image_id in image_ids:
list_file.write('%s/VOCdevkit/VOC%s/JPEGImages/%s.jpg\n'%(wd, year, image_id))
convert_annotation(year, image_id)
list_file.close()
將在VOCdevkit 下的VOC2007 和VOC2012 文件夾下的labels 文件夾下 生成每一幅圖像對應的目標物體標籤文件
並且在darknet的主目錄下生成:
2007_train.txt 2007_val.txt 2007_test.txt
2012_train.txt 2012_val.txt 2012_test.txt
這些文件的每一行就是對應一幅圖像的相對路徑,比如:
/home/solanliu/yangbo/yolo/darknet/VOCdevkit/VOC2007/JPEGImages/360_normal_train.jpg
/home/solanliu/yangbo/yolo/darknet/VOCdevkit/VOC2007/JPEGImages/45_dirty_train.jpg
/home/solanliu/yangbo/yolo/darknet/VOCdevkit/VOC2007/JPEGImages/734_normal_train.jpg
這些文件夾就是劃分好的訓練/驗證/測試集合;
然後使用一個linux 命令 cat 將 所以的:2007_*.txt 文件裏包含的圖像作爲訓練/驗證數據集;
cat 2007_*.txt > train.txt
將所以的2012_*.txt 文件裏包含的圖像數據作爲測試集;
cat 2012_*.txt > test.txt
darknet 框架的yolo 目標檢測網絡的訓練,就需要每一幅圖像 和 該幅圖像 裏所有的目標物體的信息;
該幅圖像通過train.txt或test.txt 裏的每一行(相對路徑)找到,而該圖中的標籤信息則是通過 VOCdevkit的目錄結構下的VOC2007和VOC2012文件夾下的labels文件夾下的對應的.txt 標籤文件得到。
2.訓練準備
2.1.修改cfg/yolov2.cfg 配置文件
首先將開頭處的 training階段的batch 和subdivisions 修改如下:
將testing階段註釋掉:
[net]
# Testing
#batch=1
#subdivisions=1
# Training
batch=64
subdivisions=8
width=608
height=608
channels=3
momentum=0.9
decay=0.0005
angle=0
saturation = 1.5
exposure = 1.5
hue=.1
learning_rate=0.001
burn_in=1000
max_batches = 500200
policy=steps
steps=400000,450000
scales=.1,.1
其中,max_batches = 500200是最大迭代次數。
然後就最後一層卷積層[convolutional] 的濾波器個數據修改爲自己的類別計算得到的值:
[region]下面的 classes=1 代表只有一個目標類別;
coords=4 爲 目標的座標信息(x,y,w,h)
num=5
所以:filters=num×(classes + coords + 1)=5×(1+4+1)=30
#//修改最後一層卷積層核參數個數,計算公式是依舊自己數據的類別數filters=num×(classes + coords + 1)=5×(1+4+1)=30
[convolutional]
size=1
stride=1
pad=1
filters=30
activation=linear
[region]
anchors = 0.57273, 0.677385, 1.87446, 2.06253, 3.33843, 5.47434, 7.88282, 3.52778, 9.77052, 9.16828
bias_match=1
classes=1
coords=4
num=5
softmax=1
jitter=.3
rescore=1
cfg/yolov2.cfg 文件如下:
[net]
# Testing
#batch=1
#subdivisions=1
# Training
batch=64
subdivisions=8
width=608
height=608
channels=3
momentum=0.9
decay=0.0005
angle=0
saturation = 1.5
exposure = 1.5
hue=.1
learning_rate=0.001
burn_in=1000
max_batches = 500200
policy=steps
steps=400000,450000
scales=.1,.1
[convolutional]
batch_normalize=1
filters=32
size=3
stride=1
pad=1
activation=leaky
[maxpool]
size=2
stride=2
[convolutional]
batch_normalize=1
filters=64
size=3
stride=1
pad=1
activation=leaky
[maxpool]
size=2
stride=2
[convolutional]
batch_normalize=1
filters=128
size=3
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=64
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=128
size=3
stride=1
pad=1
activation=leaky
[maxpool]
size=2
stride=2
[convolutional]
batch_normalize=1
filters=256
size=3
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=128
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=256
size=3
stride=1
pad=1
activation=leaky
[maxpool]
size=2
stride=2
[convolutional]
batch_normalize=1
filters=512
size=3
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=256
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=512
size=3
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=256
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=512
size=3
stride=1
pad=1
activation=leaky
[maxpool]
size=2
stride=2
[convolutional]
batch_normalize=1
filters=1024
size=3
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=512
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=1024
size=3
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=512
size=1
stride=1
pad=1
activation=leaky
[convolutional]
batch_normalize=1
filters=1024
size=3
stride=1
pad=1
activation=leaky
#######
[convolutional]
batch_normalize=1
size=3
stride=1
pad=1
filters=1024
activation=leaky
[convolutional]
batch_normalize=1
size=3
stride=1
pad=1
filters=1024
activation=leaky
[route]
layers=-9
[convolutional]
batch_normalize=1
size=1
stride=1
pad=1
filters=64
activation=leaky
[reorg]
stride=2
[route]
layers=-1,-4
[convolutional]
batch_normalize=1
size=3
stride=1
pad=1
filters=1024
activation=leaky
[convolutional]
size=1
stride=1
pad=1
filters=30
activation=linear
[region]
anchors = 0.57273, 0.677385, 1.87446, 2.06253, 3.33843, 5.47434, 7.88282, 3.52778, 9.77052, 9.16828
bias_match=1
classes=1
coords=4
num=5
softmax=1
jitter=.3
rescore=1
object_scale=5
noobject_scale=1
class_scale=1
coord_scale=1
absolute=1
thresh = .6
random=1
2.2 修改cfg/voc.data文件
然後再修改:Modify Cfg for Pascal Data cfg/voc.data文件:
1 classes= 20
2 train = <path-to-voc>/train.txt
3 valid = <path-to-voc>2007_test.txt
4 names = data/voc.names
5 backup = backup
改爲如下:
classes= 1
train = /home/solanliu/yangbo/yolo/darknet/train.txt
valid = /home/solanliu/yangbo/yolo/darknet/test.txt
names = data/voc.names
backup = backup
2.3修改data/voc.names 文件
data/voc.names 文件的每一行是一個目標的名稱(英文或數字即可):我的只有一個目標就是第0行 的 insulator :
insulator
預訓練模型可以不下載。
2.3訓練模型
然後可以直接開始訓練模型:
Train The Model:
./darknet detector train cfg/obj.data cfg/yolov2.cfg [weights] 2>&1 | tee log.txt
[weight]文件是預先訓練好的模型,可以選。
2>&1 | tee log.txt 實現輸出log 文件
多gpu訓練需要再編譯darknet的時候要再Makefile中設置:NVCC;若沒安裝MVCC 則只能指定一塊GPU進行訓練。
3.訓練參數解讀
參考:[1] https://blog.csdn.net/xiaomifanhxx/article/details/81095074
訓練中參數的意義:
Loaded: 0.181631 seconds
Region Avg IOU: 0.020407, Class: 1.000000, Obj: 0.108007, No Obj: 0.517779, Avg Recall: 0.000000, count: 1
Region Avg IOU: 0.139675, Class: 1.000000, Obj: 0.767618, No Obj: 0.516833, Avg Recall: 0.000000, count: 1
1: 466.579468, 466.579468 avg, 0.000000 rate, 0.042577 seconds, 2 images
Loaded: 0.365526 seconds
Region Avg IOU: 0.238722, Class: 1.000000, Obj: 0.293486, No Obj: 0.516995, Avg Recall: 0.000000, count: 1
Region Avg IOU: 0.394324, Class: 1.000000, Obj: 0.628484, No Obj: 0.512732, Avg Recall: 0.000000, count: 1
2: 437.570038, 463.678528 avg, 0.000000 rate, 0.019141 seconds, 4 images
Loaded: 0.451992 seconds
Region Avg IOU: 0.012798, Class: 1.000000, Obj: 0.546785, No Obj: 0.519375, Avg Recall: 0.000000, count: 1
Region Avg IOU: 0.119224, Class: 1.000000, Obj: 0.419430, No Obj: 0.518452, Avg Recall: 0.000000, count: 1
3: 472.883972, 464.599060 avg, 0.000000 rate, 0.019275 seconds, 6 images
(1)Region Avg IOU:平均的IOU,代表着預測的Bounding Box和Ground truth的交集與並集之比,(batch/subdivision)期望該值趨近於1。(2)Class:是標註物體的概率,期望該值趨近於1。(3)Obj:期望該值趨近於1。(4)No Obj:期望該值越來越小,但不爲0。(5)AvgRecall:期望該值趨近於1,召回率比較高說明效果較好(6)count表示輸出有多少個目標總和
訓練完一個batch後的參數的意義:
3: 472.883972, 464.599060 avg, 0.000000 rate, 0.019275 seconds, 6 images
(1)3表示是第3個batch。(2)表示總體的損失。(3)表示平均損失,該數值越低越好。(4)代表當前的學習率。(5)表示當前批次訓練花費的總時間。(6)表示參與訓練的圖片數目的總和。
4.發佈模型
訓練完成後在darknet 主目錄下的backup 文件夾下得到模型快照:... 、yolov2_500000.weights、yolov2_final.weights
發佈模型需要 .weight 文件,yolov2.cfg 文件 ,voc.names 文件
通過opencv 的dnn 模塊來調用,進行目標檢測。