Yolov5模型部署與訓練


模型部署

安裝

  • 保證CUDApytorch安裝好的基礎上,將YOLOv5的源碼拷到本地。
$ git clone https://github.com/ultralytics/yolov5.git
  • Anacondashell里面,安裝官方給好的配置文件requirements.txt
$ pip install -U -r requirements.txt

在下載好的YOLOv5源碼的目錄下執行。

報錯處理

  • 其實requirements.txt文件主要是對以下內容進行安裝,如果某一步報錯,針對問題切換方法即可。
bmatplotlib>=3.2.2
numpy>=1.18.5
opencv-python>=4.1.2
Pillow
PyYAML>=5.3.1
scipy>=1.4.1
torch>=1.7.0
torchvision>=0.8.1
tqdm>=4.41.0
tensorboard>=2.4.1
seaborn>=0.11.0
pandas
pycocotools>=2.0
thop

pycocotools安裝時容易出問題,建議提前在VS里面把SDK類東西裝好。

模型訓練

  • 找到對應數據集之后,使用標簽工具打上標簽,得到XML文件。
  • 由於YOLOv5只能訓練格式為{seqx_center/image_widthy_center/image_heightwidth/image_widthheight/image_height}的.txt文件,於是編寫python腳本將XML文件轉為.txt
import xml.dom.minidom as xmldom
import os

def data2txt(d1,d2,d3,d4,file_name):
    fd = open(file_name+'.txt','w')
    fd.write('0 '+str(d1)+' '+str(d2)+' '+str(d3)+' '+str(d4))
    fd.close

def xml2data(file_name):
    ele = xmldom.parse(os.path.abspath(file_name)).documentElement

    size = ele.getElementsByTagName("size")
    image_width = int(size[0].getElementsByTagName("width")[0].firstChild.data)
    image_height = int(size[0].getElementsByTagName("height")[0].firstChild.data)

    bndbox = ele.getElementsByTagName("bndbox")
    xmin = int(bndbox[0].getElementsByTagName("xmin")[0].firstChild.data)
    ymin = int(bndbox[0].getElementsByTagName("ymin")[0].firstChild.data)
    xmax = int(bndbox[0].getElementsByTagName("xmax")[0].firstChild.data)
    ymax = int(bndbox[0].getElementsByTagName("ymax")[0].firstChild.data)

    xcenter = (xmax + xmin)/2
    ycenter = (ymax + ymin)/2
    width = abs(xmax-xmin)
    height = abs(ymax-ymin)

    data2txt(xcenter/image_width,ycenter/image_height,width/image_width,height/image_height,file_name[:-4])

if __name__ == "__main__":
    for i in range(1,465):
        file_name = str(i)+'.xml'
        addlen = 10-len(file_name)
        for j in range(addlen):
            file_name = '0'+file_name
        xml2data(file_name)
  • 使用train.py對整理好的數據集進行訓練。
$ python train.py --img 640 --batch 16 --cfg ./models/yolov5s.yaml --weights ''

訓練好的數據集權重會放在./runs/train/exp/weights

  • train.py進行參數解析:
參數 作用
epochs 數據集被迭代的次數
batch 每次權重更新所需分析的圖片數
hyp 超參數配置文件
cfg 存儲模型結構的配置文件
data 數據集的配置文件
img 輸入圖片寬高
rect 矩形訓練
resume 恢復最近保存的模型訓練
nosave 僅保存最后的checkpoint
notest 僅測試最后的epoch
evolve 進化超參數
bucket gsutil bucket
cache-images 緩存圖像(加快訓練速度)
weights 權重文件
name 重命名
device 設備
adam 使用adam優化
multi-scale 多尺度訓練
single-cls 單類別訓練集

加粗的參數對計算機的性能有要求,可以根據實際情況調整。

其中epochs一般選擇50~200,太小欠擬合,太大過擬合。

模型使用

  • 圖片
$ python detect.py --source {image_file}
  • 視頻流
$ python detect.py --source {stream_url}
  • 使用自己訓練的數據集權重時,需要修改參數:
$ python detect.py --weights {pt_path}

參考


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM