目錄
-
yolov5 pytorch工程准備與環境部署
-
yolov5訓練數據准備
-
yolov5訓練
-
pycharm遠程連接
-
pycharm解釋器配置
-
測試
1. yolov5 pytorch工程准備與環境部署
(1)下載yolov5工程pytorch版本源碼
https://github.com/ultralytics/yolov5
(2)環境部署
用anaconda創建新的虛擬環境(如tp_env_yolov5),並激活。在該環境下安裝yolov5工程需要的python包。
pip install -r requirements.txt
或 conda install -r requirements.txt
(3) 下載預訓練權重
將weights文件夾下的download_weights.sh腳本文件移到上一層執行,下載不同網絡規模的預訓練權重。
2. yolov5訓練數據准備
(1) 數據格式轉換
新建voc_labels_yolov5.py文件,代碼如下:
# _*_ utf-8 _*_
'''
通過該腳本將 JPEGs和xml文件轉換為yolov5需要的數據格式。
'''
import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import join
import random
from shutil import copyfile
# 根據自己的數據標簽修改
#classes=["Pedestrian", "Cyclist", "Vehicle"]
classes = ["car", "bus", "truck", "nm_vehicle", "pedestrian", "s_pedestrian", "f_cyclist", "l_cyclist","b_cyclist"]
def clear_hidden_files(path):
dir_list = os.listdir(path)
for i in dir_list:
abspath = os.path.join(os.path.abspath(path), i)
if os.path.isfile(abspath):
if i.startswith("._"):
os.remove(abspath)
else:
clear_hidden_files(abspath)
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(xml_path, labels_path, image_id):
in_file = open(xml_path+'%s.xml' %image_id)
out_file = open(labels_path+'%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 :
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')
in_file.close()
out_file.close()
if __name__ == "__main__":
wd = os.getcwd()
data_base_dir = os.path.join(wd, "NVS_DATA/")
if not os.path.isdir(data_base_dir):
os.mkdir(data_base_dir)
work_sapce_dir = os.path.join(data_base_dir, "ADAS_202108/")
if not os.path.isdir(work_sapce_dir):
os.mkdir(work_sapce_dir)
'''
create xml file foder,store our data
after folder created, move our xml data to this folder,then run this py again
'''
annotation_dir = os.path.join(work_sapce_dir, "xml/")
if not os.path.isdir(annotation_dir):
os.mkdir(annotation_dir)
clear_hidden_files(annotation_dir)#clear hidden files
'''
create image file foder,store our data
after folder created, move our image data to this folder,then run this py again
'''
image_dir = os.path.join(work_sapce_dir, "JPEGImages/")
if not os.path.isdir(image_dir):
os.mkdir(image_dir)
clear_hidden_files(image_dir)
'''
create label file foder, generate new data, translate from xml files
'''
yolo_labels_dir = os.path.join(work_sapce_dir, "labels/")
if not os.path.isdir(yolo_labels_dir):
os.mkdir(yolo_labels_dir)
clear_hidden_files(yolo_labels_dir)
yolov5_images_dir = os.path.join(data_base_dir, "images/")
if not os.path.isdir(yolov5_images_dir):
os.mkdir(yolov5_images_dir)
clear_hidden_files(yolov5_images_dir)
yolov5_labels_dir = os.path.join(data_base_dir, "labels/")
if not os.path.isdir(yolov5_labels_dir):
os.mkdir(yolov5_labels_dir)
clear_hidden_files(yolov5_labels_dir)
yolov5_images_train_dir = os.path.join(yolov5_images_dir, "train/")
if not os.path.isdir(yolov5_images_train_dir):
os.mkdir(yolov5_images_train_dir)
clear_hidden_files(yolov5_images_train_dir)
yolov5_images_test_dir = os.path.join(yolov5_images_dir, "val/")
if not os.path.isdir(yolov5_images_test_dir):
os.mkdir(yolov5_images_test_dir)
clear_hidden_files(yolov5_images_test_dir)
yolov5_labels_train_dir = os.path.join(yolov5_labels_dir, "train/")
if not os.path.isdir(yolov5_labels_train_dir):
os.mkdir(yolov5_labels_train_dir)
clear_hidden_files(yolov5_labels_train_dir)
yolov5_labels_test_dir = os.path.join(yolov5_labels_dir, "val/")
if not os.path.isdir(yolov5_labels_test_dir):
os.mkdir(yolov5_labels_test_dir)
clear_hidden_files(yolov5_labels_test_dir)
train_file = open(os.path.join(wd, "yolov5_train.txt"), 'w')
test_file = open(os.path.join(wd, "yolov5_val.txt"), 'w')
train_file.close()
test_file.close()
train_file = open(os.path.join(wd, "yolov5_train.txt"), 'a')
test_file = open(os.path.join(wd, "yolov5_val.txt"), 'a')
list_imgs = os.listdir(image_dir) # list image files
probo = random.randint(1, 100)
print("Probobility: %d" % probo)
for i in range(0,len(list_imgs)):
path = os.path.join(image_dir,list_imgs[i])
if os.path.isfile(path):
image_path = image_dir + list_imgs[i]
voc_path = list_imgs[i]
(nameWithoutExtention, extention) = os.path.splitext(os.path.basename(image_path))
(voc_nameWithoutExtention, voc_extention) = os.path.splitext(os.path.basename(voc_path))
annotation_name = nameWithoutExtention + '.xml'
annotation_path = os.path.join(annotation_dir, annotation_name)
label_name = nameWithoutExtention + '.txt'
label_path = os.path.join(yolo_labels_dir, label_name)
probo = random.randint(1, 100)
print("Probobility: %d" % probo)
if(probo < 80): # train dataset
if os.path.exists(annotation_path):
train_file.write(image_path + '\n')
convert_annotation(annotation_dir, yolo_labels_dir,nameWithoutExtention) # convert label
copyfile(image_path, yolov5_images_train_dir + voc_path)
copyfile(label_path, yolov5_labels_train_dir + label_name)
else: # test dataset
if os.path.exists(annotation_path):
test_file.write(image_path + '\n')
convert_annotation(annotation_dir, yolo_labels_dir,nameWithoutExtention) # convert label
copyfile(image_path, yolov5_images_test_dir + voc_path)
copyfile(label_path, yolov5_labels_test_dir + label_name)
train_file.close()
test_file.close()
注:該文件運行兩次,一次生成相應的文件夾結構,將自己的jpg數據和標注xml數據拷貝到生成的文件夾里,再次執行該文件即可生成目標數據,不然為空。此處稍微繁瑣,以后有時間簡化。
通過該腳本將 JPEGs和xml文件轉換為yolov5需要的數據格式。

(2)新建數據配置文件
在yolov5-master目錄下的data文件夾下新建一個nvs.yaml文件(可以自定義命名),內容如下:

train: /home/tianpeng/tpWorkSpace/tpDemo/yolov5/tp_yolov5/tools/NVS_DATA/images/train/ #如果是遠程的話,需要將本地生成的該文件夾傳輸至遠程服務器,並配置相應路徑
val: /home/tianpeng/tpWorkSpace/tpDemo/yolov5/tp_yolov5/tools/NVS_DATA/images/val/ #如果是遠程的話,需要將本地生成的該文件夾傳輸至遠程服務器,並配置相應路徑
#如我的遠程地址是:
#train: /home/zg-alg/Workspace/tpWork/tpTrainingData/yolov5_training_data/images/train/
#val: /home/zg-alg/Workspace/tpWork/tpTrainingData/yolov5_training_data/images/val/
# number of classes
nc: 9
# class names
names: ["car", "bus", "truck", "nm_vehicle", "pedestrian", "s_pedestrian", "f_cyclist", "l_cyclist","b_cyclist"]
(3) 修改模型配置文件
在models文件下選擇訓練用的網絡模型,打開模型文件:

將類別(nc)修改為我們分類數,將anchors改成重新聚類的結果,也可以不改,保存退出。
3. yolov5訓練
在train.py文件里進行以下幾處修改:

以上參數解釋如下:
epochs:指的就是訓練過程中整個數據集將被迭代多少次,顯卡不行你就調小點。
batch-size:一次看完多少張圖片才進行權重更新,梯度下降的mini-batch,顯卡不行你就調小點。
cfg:存儲模型結構的配置文件
data:存儲訓練、測試數據的文件
img-size:輸入圖片寬高,顯卡不行你就調小點。
rect:進行矩形訓練
resume:恢復最近保存的模型開始訓練
nosave:僅保存最終checkpoint
notest:僅測試最后的epoch
evolve:進化超參數
bucket:gsutil bucket
cache-images:緩存圖像以加快訓練速度
weights:權重文件路徑
name: 重命名results.txt to results_name.txt
device:cuda device, i.e. 0 or 0,1,2,3 or cpu
adam:使用adam優化
multi-scale:多尺度訓練,img-size +/- 50%
single-cls:單類別的訓練集
開始訓練:

訓練過程可視化
利用tensorboard可視化訓練過程,訓練開始會在yolov5目錄生成一個runs文件夾,利用tensorboard打開即可查看訓練日志,命令如下:
tensorboard --logdir=runs
在瀏覽器中打開生成的鏈接即可查看。

4. pycharm遠程連接服務器
pycharm需要專業版,社區版不行。
Pycharm菜單欄,如下圖所示,依次點擊 Tools -> Deployment -> Configration…

Connection下,協議最好選擇sftp,接下來填寫服務器主機IP,用戶名,密碼。

Mappings下可先不配,后面配置解釋器再將其關聯起來。

5. pycharm解釋器配置
使用服務器調試Python程序的前提時在服務器上安裝了Python解釋器,如果沒安裝,請先安裝。
在菜單欄,File -> Settings… -> Project ×× -> Project Interpreter,點擊右側 Add按鈕,添加解釋器。

選擇SSH Interpreter,Existing server configuration,選擇上一步連接的服務器,如果沒有則新建一個服務器連接。

選擇遠程服務器上Python解釋器的位置,服務器上的遠程同步文件夾Sync folders,可以選擇多個。如果不知道Python安裝在哪,可以遠程連接服務器后,使用 命令 which python 找到Python安裝位置。

點擊Sync folder 右側的文件夾圖標,填寫本地工程目錄和要映射到服務器的工程路徑,這一步將上一步mappings關聯起來。
Finish,配置結束。該項目現在使用的就是遠程服務器上的Python解釋器了。以后的項目若想/不想使用該解釋器,手動更改解釋器即可。
使用遠程解釋器運行本地Python程序
將測試代碼上傳至遠程服務器(Tools -> Deployment -> Upload to ××)。
將服務器程序生成的模型文件或文件夾下載到本地如下操作:
Tools -> Deployment -> Browse Remote Host, 選擇相應文件或文件夾,下載下來即可。

執行測試代碼,可以看到現在代碼是在遠程服務器上運行了。
6. 測試
測試圖片:
python detect.py --source ../../../tpAdasData/images_dir/test_set/guide5000/ --weights ./runs/train/exp4/weights/best.pt
測試視頻:
python detect.py --source ../../test_video/car_sunny_20210508.avi --weights ./runs/train/exp4/weights/best.pt
