1 配置環(huán)境
本機環(huán)境
系統(tǒng):Windows10
- OpenCV:3.42
下載地址:https://opencv.org/releases.html
安裝完后需配置系統(tǒng)環(huán)境變量
Python:3
IDE:VS2017
- CUDA:10.2
下載地址:https://developer.nvidia.com/cuda-downloads
配置系統(tǒng)環(huán)境變量后,cmd輸入
nvcc -V
會出現(xiàn)版本信息
CUDNN:7.65
需預(yù)先注冊賬號后下載:https://developer.nvidia.com/rdp/cudnn-download
下載完后復(fù)制內(nèi)容到CUDA對應(yīng)文件夾內(nèi)-
神經(jīng)網(wǎng)絡(luò):Darknet
下載命令:git clone https://github.com/AlexeyAB/darknet
需使用VS2017編譯[Release|64],使用VS2017,且使用gpu踪旷,打開以下sln文件
darknet-master\darknet-master\build\darknet\darknet.sln
并使用文本文檔編輯darknet.vcxproj
鸣奔,搜索得到兩處CUDA版本號,替換成自己的
編譯需添加OpenCV環(huán)境依賴
VC++ 目錄—>包含目錄—>編輯面褐,添加以下三項[選擇自己安裝位置的絕對路徑]
C:\opencv\build\include
C:\opencv\build\include\opencv
C:\opencv\build\include\opencv2
VC++ 目錄—>庫目錄中添加
C:\opencv\build\x64\vc15\lib
鏈接器->輸入->附加依賴項添加[根據(jù)自己安裝的版本]
opencv_world342d.lib
opencv_world342.lib
編譯完成后,darknet.exe
會在x64
文件夾中
2 數(shù)據(jù)集準備
2.1以VOC格式準備自己的數(shù)據(jù)集文件夾
├─VOCdevkit2007
│ └─VOC2007
│ ├─Annotations
│ ├─ImageSets
│ │ └─Main
│ ├─JPEGImages
│ └─labels
- JPEGImages 用于放置待標注的圖像,格式為jpg
2.2使用腳本批量更改圖片名稱
import os
path = r'C:\Users\Dexter0ion\Desktop\TrainData\VOCdevkit2007\VOC2007\JPEGImages'
filelist = os.listdir(path) # 該文件夾下所有的文件(包括文件夾)
count=0 # 編號從0開始
for file in filelist:
print(file)
for file in filelist:
# 遍歷所有文件
Olddir=os.path.join(path,file) # 原來的文件路徑
if os.path.isdir(Olddir): # 如果是文件夾則跳過
continue
filename=os.path.splitext(file)[0] # 文件名
filetype=os.path.splitext(file)[1] # 文件擴展名
Newdir=os.path.join(path,str(count).zfill(6)+filetype) # 用字符串函數(shù)zfill 以0補全所需位數(shù)
os.rename(Olddir,Newdir) # 重命名
count+=1
運行命令
python ./rename.py
2.3使用labelImg軟件對數(shù)據(jù)進行標注
labelImg下載地址:http://tzutalin.github.io/labelImg/
解壓后在data/predefined_classes.txt中修改預(yù)設(shè)的class名字
- Open Dir[Ctrl+u] 選擇圖片目錄為JPEGImages
- Change Save Dir[Ctrl+r] 選擇標注結(jié)果xml目錄為Annotations
即可開始標注寥茫,快捷鍵流程
[w]框選
[Ctrl+s]保存
[d]下一張
3.處理標注后的數(shù)據(jù)
3.1生成Main目錄下的txt文件
import os
import random
trainval_percent = 0.7 # trainval占總數(shù)的比例
train_percent = 0.5 # train占trainval的比例
xmlfilepath = r'C:\Users\Dexter0ion\Desktop\TrainData\VOCdevkit2007\VOC2007\Annotations'
txtsavepath = r'C:\Users\Dexter0ion\Desktop\TrainData\VOCdevkit2007\VOC2007\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 + r'\trainval.txt', 'w')
ftest = open(txtsavepath + r'\test.txt', 'w')
ftrain = open(txtsavepath + r'\train.txt', 'w')
fval = open(txtsavepath + r'\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 ./generatetxt.py
3.2生成darknet可用的yolo類型數(shù)據(jù)
將VOCdevkit2007文件夾整個復(fù)制到
darknet-master\darknet-master\build\darknet
文件夾下
進入
darknet-master\darknetmaster\build\darknet\VOCdevkit2007
文件夾
創(chuàng)建voc_label.py腳本
voc_label.py[此次只訓(xùn)練一個目標,在classes中改為你要訓(xùn)練的目標名字顽耳,多個則用逗號分隔]
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')]
classes = ["redbox"]
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(year, image_id):
in_file = open('VOC%s/Annotations/%s.xml'%(year, image_id))
out_file = open('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('VOC%s/labels/'%(year)):
os.makedirs('VOC%s/labels/'%(year))
image_ids = open('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/VOC%s/JPEGImages/%s.jpg\n'%(wd, year, image_id))
convert_annotation(year, image_id)
list_file.close()
os.system("cat 2007_train.txt 2007_val.txt 2012_train.txt 2012_val.txt > train.txt")
os.system("cat 2007_train.txt 2007_val.txt 2007_test.txt 2012_train.txt 2012_val.txt > train.all.txt")
之后會在VOC2007同目錄下得到
│ 2007_test.txt
│ 2007_train.txt
│ 2007_val.txt
4 訓(xùn)練準備
需要配置
- 下載
darknet53.conv.74
預(yù)訓(xùn)練權(quán)重
下載地址:http://pjreddie.com/media/files/darknet53.conv.74
下載后移動到:darknet-master\build\darknet\x64
文件夾下
- 創(chuàng)建
data/obj.data
訓(xùn)練文本路徑配置
classes= 1
#自己先前生成文件的絕對路徑
train = C:\Users\Dexter0ion\Desktop\TrainData\darknet-master\darknet-master\build\darknet\VOCdevkit2007\2007_train.txt
valid = C:\Users\Dexter0ion\Desktop\TrainData\darknet-master\darknet-master\build\darknet\VOCdevkit2007\2007_test.txt
names = data/obj.names
backup = backup/
- 創(chuàng)建
data/obj.name
分類名稱
redbox
- 修改
darknet-master\build\darknet\x64
文件夾下yolov3.cfg
訓(xùn)練配置坠敷,并重命名為yolo-obj.cfg
修改batch
和subdivisions
修改max_batches
(作者聲明最好是2000*訓(xùn)練目標個數(shù)妙同,但不要小于4000)和steps
(80%,90%膝迎,降低學(xué)習(xí)率閾值)
修改三處[convolutional] [yolo]
filters = 3*(5+classes數(shù)目) classes = 本次訓(xùn)練目標數(shù)粥帚,即1個
5 開始訓(xùn)練
在darknet-master\build\darknet\x64
目錄下運行指令
./darknet.exe detector train data/obj.data yolo-obj.cfg darknet53.conv.74 mjpeg_port 8090 -ext_output | Out-File ./alpha_train_log.txt
注意:前100次loss會很高,之后會逐步下降
訓(xùn)練完成的權(quán)重文件默認保存在backup
文件夾中
6 測試訓(xùn)練結(jié)果
復(fù)制yolo-obj.cfg
且重命名為yolo-obj-test.cfg
在darknet-master\build\darknet\x64
目錄下運行指令
./darknet detector test data/obj.data yolo-obj-test.cfg backup/yolo-obj_last.weights -thresh 0.1