日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

YOLOv5的详细使用教程,以及使用yolov5训练自己的数据集

發(fā)布時間:2023/12/9 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 YOLOv5的详细使用教程,以及使用yolov5训练自己的数据集 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
歡迎大家關(guān)注筆者,你的關(guān)注是我持續(xù)更博的最大動力

原創(chuàng)文章,轉(zhuǎn)載告知,盜版必究

YOLOv5的詳細使用教程,以及使用yolov5訓練自己的數(shù)據(jù)集

文章目錄:

  • 1 安裝環(huán)境依賴
    • 1.1 克隆項目
    • 1.2 安裝必要的環(huán)境依賴
  • 2 下載預(yù)訓練模型和標注的數(shù)據(jù)集
    • 2.1 下載預(yù)訓練模型
      • 2.1.1 執(zhí)行腳本下載預(yù)訓練模型
      • 2.1.2 直接下載預(yù)訓練模型,然后保存到`/yolov5/weights`目錄下即可,我已經(jīng)把預(yù)訓練模型的`url`提取出來
    • 2.2 下載標注的數(shù)據(jù)集
      • 2.2.1 執(zhí)行腳本下載
      • 2.2.2 如果下載比較慢,也可以通過url鏈接直接下載`coco128.zip`
  • 3 訓練下載的coco128數(shù)據(jù)集
    • 3.1 創(chuàng)建訓練數(shù)據(jù)集的配置文件Dataset.yaml
    • 3.2 創(chuàng)建標簽(Labels)
    • 3.3 組織文件結(jié)構(gòu)
    • 3.4 選擇一個模型訓練
    • 3.5 開始訓練
    • 3.5.1 訓練命令
    • 3.5.2 訓練常見錯誤1
    • 3.5.3 訓練常見錯誤2
    • 3.5.4 訓練常見錯誤3
    • 3.6 使用tensorboard可視化結(jié)果
    • 3.7 測試
  • 4 訓練自己的數(shù)據(jù)集
    • 4.1 準備數(shù)據(jù)集
    • 4.2 修改數(shù)據(jù)和模型配置文件
      • 4.2.1 修改數(shù)據(jù)配置文件
      • 4.2.2 修改模型配置文件
    • 4.3 訓練自己的數(shù)據(jù)集
    • 4.3.1 使用yolovs.pt預(yù)訓練模型進行訓練
      • 4.3.2 使用yolov5l.pt預(yù)訓練模型進行訓練
    • 4.4 使用訓練好的預(yù)訓練模型進行測試
    • 4.5 在Tensorbaord上查看數(shù)據(jù)的訓練過程中的一些指標
  • 5 推理測試
    • 5.1 圖像推理測試
    • 5.2 目錄推理測試
    • 5.3 視頻推理測試
    • 5.4 網(wǎng)絡(luò)攝像頭推理測試
    • 5.5 http流推理測試
    • 5.6 rtsp流推理測試
  • 6 可視化
    • 6.1 訓練的模型的測試表現(xiàn)可視化
    • 6.2 訓練損失和性能指標視化


本人環(huán)境聲明:

  • 系統(tǒng)環(huán)境:Ubuntu18.04.1
  • cuda版本:10.2.89
  • cudnn版本:7.6.5
  • torch版本:1.5.0
  • torchvision版本:0.6.0
  • 項目代碼yolov5,官網(wǎng),項目開源的時間:20200601

自定義數(shù)據(jù)集:

1 安裝環(huán)境依賴

1.1 克隆項目

git clone https://github.com/ultralytics/yolov5 # clone repo

如果下載比較慢,建議使用下面的鏡像下載:

git clone https://github.com.cnpmjs.org/ultralytics/yolov5 # clone repo

1.2 安裝必要的環(huán)境依賴

官方給出的要求是:python>=3.7、PyTorch>=1.5,安裝依賴:

cd yolov5
pip install -U -r requirements.txt
requirements.txt

# pip install -U -r requirements.txt Cython numpy==1.17 opencv-python torch>=1.5 matplotlib pillow tensorboard PyYAML>=5.3 torchvision scipy tqdm git+https://github.com/cocodataset/cocoapi.git#subdirectory=PythonAPI# Nvidia Apex (optional) for mixed precision training -------------------------- # git clone https://github.com/NVIDIA/apex && cd apex && pip install -v --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" . --user && cd .. && rm -rf apex# Conda commands (in place of pip) --------------------------------------------- # conda update -yn base -c defaults conda # conda install -yc anaconda numpy opencv matplotlib tqdm pillow ipython # conda install -yc conda-forge scikit-image pycocotools tensorboard # conda install -yc spyder-ide spyder-line-profiler # conda install -yc pytorch pytorch torchvision # conda install -yc conda-forge protobuf numpy && pip install onnx # https://github.com/onnx/onnx#linux-and-macos

2 下載預(yù)訓練模型和標注的數(shù)據(jù)集

2.1 下載預(yù)訓練模型

2.1.1 執(zhí)行腳本下載預(yù)訓練模型

/yolov5/weights/download_weights.sh腳本定義下載預(yù)訓練模型,腳本代碼內(nèi)容如下:

#!/bin/bash # Download common modelspython3 -c "from utils.google_utils import *; attempt_download('weights/yolov5s.pt'); attempt_download('weights/yolov5m.pt'); attempt_download('weights/yolov5l.pt'); attempt_download('weights/yolov5x.pt')"

attempt_download函數(shù)在/yolov5/utils/google_utils.py腳本中定義

2.1.2 直接下載預(yù)訓練模型,然后保存到/yolov5/weights目錄下即可,我已經(jīng)把預(yù)訓練模型的url提取出來

大家直接在google driver中下載即可,地址(可能需要科學上網(wǎng)):

點我——》帶你去:https://drive.google.com/drive/folders/1Drs_Aiu7xx6S-ix95f9kNsA6ueKRpN2J

2.2 下載標注的數(shù)據(jù)集

2.2.1 執(zhí)行腳本下載

python3 -c "from yolov5.utils.google_utils import gdrive_download; gdrive_download('1n_oKgR81BJtqk75b00eAjdv03qVCQn2f','coco128.zip')" # download dataset

執(zhí)行上面的代碼,會下載:coco128.zip數(shù)據(jù)集,該數(shù)據(jù)是COCO train2017數(shù)據(jù)的一部分,只取了coco數(shù)據(jù)集中的128張標注的圖片,coco128.zip下載完后解壓到/yolov5目錄下即可,解壓后的coco128文件結(jié)構(gòu)如下:

coco128 |-- LICENSE |-- README.txt # 相關(guān)說明 |-- annotations # 空目錄 |-- images # 128張jpg圖片 `-- labels # 128張標注的txt文件

/yolov5/utils/google_utils.py腳本是下載預(yù)訓練模型和標注的訓練數(shù)據(jù)集,該腳本代碼內(nèi)容如下:

# This file contains google utils: https://cloud.google.com/storage/docs/reference/libraries # pip install --upgrade google-cloud-storage # from google.cloud import storageimport os import time from pathlib import Pathdef attempt_download(weights):# Attempt to download pretrained weights if not found locallyweights = weights.strip()msg = weights + ' missing, try downloading from https://drive.google.com/drive/folders/1Drs_Aiu7xx6S-ix95f9kNsA6ueKRpN2J'r = 1if len(weights) > 0 and not os.path.isfile(weights):d = {'yolov3-spp.pt': '1mM67oNw4fZoIOL1c8M3hHmj66d8e-ni_', # yolov3-spp.yaml'yolov5s.pt': '1R5T6rIyy3lLwgFXNms8whc-387H0tMQO', # yolov5s.yaml'yolov5m.pt': '1vobuEExpWQVpXExsJ2w-Mbf3HJjWkQJr', # yolov5m.yaml'yolov5l.pt': '1hrlqD1Wdei7UT4OgT785BEk1JwnSvNEV', # yolov5l.yaml'yolov5x.pt': '1mM8aZJlWTxOg7BZJvNUMrTnA2AbeCVzS', # yolov5x.yaml}file = Path(weights).nameif file in d:r = gdrive_download(id=d[file], name=weights)if not (r == 0 and os.path.exists(weights) and os.path.getsize(weights) > 1E6): # weights exist and > 1MBos.remove(weights) if os.path.exists(weights) else None # remove partial downloadss = "curl -L -o %s 'https://storage.googleapis.com/ultralytics/yolov5/ckpt/%s'" % (weights, file)r = os.system(s) # execute, capture return values# Error checkif not (r == 0 and os.path.exists(weights) and os.path.getsize(weights) > 1E6): # weights exist and > 1MBos.remove(weights) if os.path.exists(weights) else None # remove partial downloadsraise Exception(msg)def gdrive_download(id='1HaXkef9z6y5l4vUnCYgdmEAj61c6bfWO', name='coco.zip'):# https://gist.github.com/tanaikech/f0f2d122e05bf5f971611258c22c110f# Downloads a file from Google Drive, accepting presented query# from utils.google_utils import *; gdrive_download()t = time.time()print('Downloading https://drive.google.com/uc?export=download&id=%s as %s... ' % (id, name), end='')os.remove(name) if os.path.exists(name) else None # remove existingos.remove('cookie') if os.path.exists('cookie') else None# Attempt file downloados.system("curl -c ./cookie -s -L \"https://drive.google.com/uc?export=download&id=%s\" > /dev/null" % id)if os.path.exists('cookie'): # large files = "curl -Lb ./cookie \"https://drive.google.com/uc?export=download&confirm=`awk '/download/ {print $NF}' ./cookie`&id=%s\" -o %s" % (id, name)else: # small files = "curl -s -L -o %s 'https://drive.google.com/uc?export=download&id=%s'" % (name, id)r = os.system(s) # execute, capture return valuesos.remove('cookie') if os.path.exists('cookie') else None# Error checkif r != 0:os.remove(name) if os.path.exists(name) else None # remove partialprint('Download error ') # raise Exception('Download error')return r# Unzip if archiveif name.endswith('.zip'):print('unzipping... ', end='')os.system('unzip -q %s' % name) # unzipos.remove(name) # remove zip to free spaceprint('Done (%.1fs)' % (time.time() - t))return r# def upload_blob(bucket_name, source_file_name, destination_blob_name): # # Uploads a file to a bucket # # https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python # # storage_client = storage.Client() # bucket = storage_client.get_bucket(bucket_name) # blob = bucket.blob(destination_blob_name) # # blob.upload_from_filename(source_file_name) # # print('File {} uploaded to {}.'.format( # source_file_name, # destination_blob_name)) # # # def download_blob(bucket_name, source_blob_name, destination_file_name): # # Uploads a blob from a bucket # storage_client = storage.Client() # bucket = storage_client.get_bucket(bucket_name) # blob = bucket.blob(source_blob_name) # # blob.download_to_filename(destination_file_name) # # print('Blob {} downloaded to {}.'.format( # source_blob_name, # destination_file_name))

2.2.2 如果下載比較慢,也可以通過url鏈接直接下載coco128.zip

點我——》帶你去:https://drive.google.com/uc?export=download&id=1n_oKgR81BJtqk75b00eAjdv03qVCQn2f

上面下載好預(yù)訓練

準備好上面的環(huán)境和下載好文件之后,就可以開始自定義自己的數(shù)據(jù)集,進行訓練啦!

3 訓練下載的coco128數(shù)據(jù)集

3.1 創(chuàng)建訓練數(shù)據(jù)集的配置文件Dataset.yaml

上面下載好coco128.zip小型數(shù)據(jù)集之后,這些數(shù)據(jù)集可以用于訓練和驗證
/content/yolov5/models/yolov5l.yaml。coco128.yaml中定義了:

  • 訓練圖片的路徑(或訓練圖片列表的.txt文件)
  • 與驗證集相同的圖片
  • 目標的類別數(shù)
  • 類名列表

下面是/data/coco128.yaml文件中定義的內(nèi)容:

# COCO 2017 dataset http://cocodataset.org - first 128 training images # Download command: python -c "from yolov5.utils.google_utils import gdrive_download; gdrive_download('1n_oKgR81BJtqk75b00eAjdv03qVCQn2f','coco128.zip')" # Train command: python train.py --data ./data/coco128.yaml # Dataset should be placed next to yolov5 folder: # /parent_folder # /coco128 # /yolov5# 訓練集和驗證集 (圖片的目錄路徑或 *.txt圖片路徑) train: ../coco128/images/train2017/ val: ../coco128/images/train2017/# 類別數(shù) number of classes nc: 80# 類別列表 class names names: ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light','fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow','elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee','skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard','tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple','sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch','potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone','microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear','hair drier', 'toothbrush']

3.2 創(chuàng)建標簽(Labels)

對數(shù)據(jù)集進行打標簽,可以選擇如下兩種打標工具:

  • Labelbox
  • CVAT
  • 也可以使用LabelImg,選用ylolo格式進行標注

將標簽導出為darknet格式,每個標注圖像有一個*.txt文件(如果圖像中沒有對象,則不需要*.txt文件),*.txt文件格式如下:

  • 每行一個對象
  • 每行都是:class x_center y_center width height格式
  • 框的坐標格式必須采用歸一化格式的xywh(從0到1),如果你框以像素為單位,則將x_center和width除以圖像寬度,將y_center和height除以圖像的高度
  • 類別是從索引0開始的

通過在器路徑名中將/images/*.jpg替換為/label/*.txt,可以定位每個圖像的標簽文件,示例圖像和標簽對為:

dataset/images/train2017/000000109622.jpg # image dataset/labels/train2017/000000109622.txt # label

例如:000000000009.txt標簽文件,表示000000000009.jpg圖片中標注了8個目標:

45 0.479492 0.688771 0.955609 0.5955 45 0.736516 0.247188 0.498875 0.476417 50 0.637063 0.732938 0.494125 0.510583 45 0.339438 0.418896 0.678875 0.7815 49 0.646836 0.132552 0.118047 0.096937 49 0.773148 0.129802 0.090734 0.097229 49 0.668297 0.226906 0.131281 0.146896 49 0.642859 0.079219 0.148063 0.148062

3.3 組織文件結(jié)構(gòu)

根據(jù)下圖整理自己的訓練集和驗證集圖片及標簽。注意:/coco128目錄應(yīng)該和yolov5目錄同級,同時確保coco128/labels和coco128/images兩個目錄同級!

3.4 選擇一個模型訓練

上面已經(jīng)修改了自定義數(shù)據(jù)集的配置文件,同時組織好了數(shù)據(jù)。下面就可以選擇一個模型進行訓練了。

從./models目錄下選擇一個模型的配置文件,這里我們選擇yolov5s.ymal,這是一個最小最快的模型。關(guān)于其他模型之間的比較下面介紹。選擇好模型之后,如果你使用的不是coco數(shù)據(jù)集進行訓練,而是自定義的數(shù)據(jù)集,此時只需要修改*.yaml配置文件中的nc: 80參數(shù)和數(shù)據(jù)的類別列表

下面是yolo5s.ymal配置文件的內(nèi)容:

# parameters nc: 80 # number of classes depth_multiple: 0.33 # model depth multiple width_multiple: 0.50 # layer channel multiple# anchors anchors:- [116,90, 156,198, 373,326] # P5/32- [30,61, 62,45, 59,119] # P4/16- [10,13, 16,30, 33,23] # P3/8# YOLOv5 backbone backbone:# [from, number, module, args][[-1, 1, Focus, [64, 3]], # 0-P1/2[-1, 1, Conv, [128, 3, 2]], # 1-P2/4[-1, 3, BottleneckCSP, [128]],[-1, 1, Conv, [256, 3, 2]], # 3-P3/8[-1, 9, BottleneckCSP, [256]],[-1, 1, Conv, [512, 3, 2]], # 5-P4/16[-1, 9, BottleneckCSP, [512]],[-1, 1, Conv, [1024, 3, 2]], # 7-P5/32[-1, 1, SPP, [1024, [5, 9, 13]]],]# YOLOv5 head head:[[-1, 3, BottleneckCSP, [1024, False]], # 9[-1, 1, Conv, [512, 1, 1]],[-1, 1, nn.Upsample, [None, 2, 'nearest']],[[-1, 6], 1, Concat, [1]], # cat backbone P4[-1, 3, BottleneckCSP, [512, False]], # 13[-1, 1, Conv, [256, 1, 1]],[-1, 1, nn.Upsample, [None, 2, 'nearest']],[[-1, 4], 1, Concat, [1]], # cat backbone P3[-1, 3, BottleneckCSP, [256, False]],[-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1]], # 18 (P3/8-small)[-2, 1, Conv, [256, 3, 2]],[[-1, 14], 1, Concat, [1]], # cat head P4[-1, 3, BottleneckCSP, [512, False]],[-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1]], # 22 (P4/16-medium)[-2, 1, Conv, [512, 3, 2]],[[-1, 10], 1, Concat, [1]], # cat head P5[-1, 3, BottleneckCSP, [1024, False]],[-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1]], # 26 (P5/32-large)[[], 1, Detect, [nc, anchors]], # Detect(P5, P4, P3)]

yolov5s.yaml配置文件中主要定義了:

  • 參數(shù)(parameters):類別等
  • anchor
  • YOLOv5 backbone
  • YOLOv5 head

3.5 開始訓練

3.5.1 訓練命令

上面一切準備就緒,可以開始訓練啦

運行下面的命令訓練coco128.ymal,訓練5epochs。可以有兩種訓練方式,如下參數(shù):

  • --cfg yolov5s.yaml --weights '':從頭開始訓練
  • --cfg yolov5s.yaml --weights yolov5s.pt:從預(yù)訓練的模型加載開始訓練

YOLOv5在coco128上訓練5epochs的命令:

python train.py --img 640 --batch 16 --epochs 5 --data ./data/coco128.yaml --cfg ./models/yolov5s.yaml --weights ''

訓練的更多可選參數(shù):

  • --epochs:訓練的epoch,默認值300
  • --batch-size:默認值16
  • --cfg:模型的配置文件,默認為yolov5s.yaml
  • --data:數(shù)據(jù)集的配置文件,默認為data/coco128.yaml
  • --img-size:訓練和測試輸入大小,默認為[640, 640]
  • --rect:rectangular training,布爾值
  • --resume:是否從最新的last.pt中恢復訓練,布爾值
  • --nosave:僅僅保存最后的checkpoint,布爾值
  • --notest:僅僅在最后的epoch上測試,布爾值
  • --evolve:進化超參數(shù)(evolve hyperparameters),布爾值
  • --bucket:gsutil bucket,默認值''
  • --cache-images:緩存圖片可以更快的開始訓練,布爾值
  • --weights:初始化參數(shù)路徑,默認值''
  • --name:如果提供,將results.txt重命名為results_name.txt
  • --device:cuda設(shè)備,例如:0或0,1,2,3或cpu,默認''
  • --adam:使用adam優(yōu)化器,布爾值
  • --multi-scale:改變圖片尺寸img-size +/0- 50%,布爾值
  • --single-cls:訓練單個類別的數(shù)據(jù)集,布爾值

3.5.2 訓練常見錯誤1

1、執(zhí)行訓練命令報錯:RuntimeError: Model replicas must have an equal number of parameters.,錯誤顯示,模型的副本必須有相同的參數(shù)

2、解決方式:
這個可能是由于Pytorch的版本問題導致的錯誤,我的torch版本為15.0,把版本降為1.4.0即可(參考):

pip install torch==1.4.0+cu100 torchvision==0.5.0+cu100 -f https://download.pytorch.org/whl/torch_stable.html

3.5.3 訓練常見錯誤2

1、執(zhí)行訓練命令報錯:ModuleNotFoundError: No module named 'yaml'

2、解決方式:
這是由于沒有安裝yaml庫包錯誤,雖然導入是:import yaml,但是安裝的名字卻不是yaml,下面是正確安裝yaml:

pip install PyYAML

3.5.4 訓練常見錯誤3

1、執(zhí)行訓練命令報錯:AttributeError: 'DistributedDataParallel' object has no attribute 'model'

2、錯誤解決方式:
這個是由于--device的默認值為'',此時默認會使用多GPU進行訓練,但是多GPU訓練時就會出現(xiàn)上面這個問題,這可能時一個bug(參考),解決方式就是使用單GPU,把訓練命令改成如下:

python train.py --img 640 --batch 16 --epochs 5 --data ./data/coco128.yaml --cfg ./models/yolov5s.yaml --weights '' --device 0

3.6 使用tensorboard可視化結(jié)果

在yolov5目錄下,使用:

tensorboard --logdir=runs

然后把返回的url地址粘貼到瀏覽器中即可!我測試顯示結(jié)果如下:

注意:
如果返回拒絕了我們的請求,可以在tensorboard的后面加上參數(shù)--port ip:

tensorboard --logdir=runs --host=192.168.0.134

3.7 測試

測試的更多可選參數(shù):

  • --weights :預(yù)訓練模型路徑,默認值weights/yolov5s.pt
  • --data:數(shù)據(jù)集的配置文件,默認為data/coco.yaml
  • --batch-size:默認值32
  • --img-size:推理大小(pixels),默認640
  • --conf-thres:目標置信度閾值,默認0.001
  • --iou-thres:NMS的IOU閾值,默認0.65
  • --save-json:把結(jié)果保存為cocoapi-compatible的json文件
  • --task:默認val,可選其他值:val, test, study
  • --device:cuda設(shè)備,例如:0或0,1,2,3或cpu,默認''
  • --half:半精度的FP16推理
  • --single-cls:將其視為單類別,布爾值
  • --augment:增強推理,布爾值
  • --verbose:顯示類別的mAP,布爾值

測試命令示例:

python test.py --weights yolov5s.pt --data ./data/coco.yaml --img 640

4 訓練自己的數(shù)據(jù)集

數(shù)據(jù)準備有兩種方式:

  • 一種是直接指定訓練集和測試集圖片的路徑(本文使用的這種方法)
  • 另外一種是給出訓練和測試集圖片的txt文件

4.1 準備數(shù)據(jù)集

yolov5中的數(shù)據(jù)集的標簽都是保存為YOLO格式的txt文件的,關(guān)于:

  • 怎么標注數(shù)據(jù)集
  • VOC數(shù)據(jù)和YOLO數(shù)據(jù)格式時是什么樣的
  • 怎么把VOC格式數(shù)據(jù)轉(zhuǎn)化為YOLO格式數(shù)據(jù)
  • 以及VOC格式和YOLO格式相互轉(zhuǎn)化計算過程

請參考:這篇博客,這里不在贅述!!!

數(shù)據(jù)集標注好之后,存放如下目錄格式:

(yolov5) shl@zfcv:~/shl/yolov5$ tree hat_hair_beard hat_hair_beard ├── images │ ├── train2017 # 訓練集圖片,這里我只列舉幾張示例 │ │ ├── 000050.jpg │ │ ├── 000051.jpg │ │ └── 000052.jpg │ └── val2017 # 驗證集圖片 │ ├── 001800.jpg │ ├── 001801.jpg │ └── 001802.jpg └── labels ├── train2017 # 訓練集的標簽文件│ ├── 000050.txt│ ├── 000051.txt│ └── 000052.txt└── val2017 # 驗證集的標簽文件├── 001800.txt├── 001801.txt└── 001802.txt6 directories, 13 files (yolov5) shl@zfcv:~/shl/yolov5$
  • had_hair_beard:存放數(shù)據(jù)的目錄,該目錄位于yolov5目錄下
  • images:目錄下存放的是圖片,包含訓練集和驗證集圖片
  • labels:目錄下存放的是標簽文件,包含訓練集和驗證集圖片對應(yīng)的標簽文件

按照上面的結(jié)構(gòu)組織好數(shù)據(jù)的目錄結(jié)構(gòu),然后就可以修改一些訓練相關(guān)的文件了!

4.2 修改數(shù)據(jù)和模型配置文件

4.2.1 修改數(shù)據(jù)配置文件

原先的配置文件為:./yolov5/data/coco128.yaml,該文件中內(nèi)容為:

(yolov5) shl@zfcv:~/shl/yolov5/data$ ls Annotations coco.yaml hat_hair_beard.yaml JPEGImages coco128.yaml get_coco2017.sh ImageSets VOC2007 (yolov5) shl@zfcv:~/shl/yolov5/data$ cat coco128.yaml # COCO 2017 dataset http://cocodataset.org - first 128 training images # Download command: python -c "from yolov5.utils.google_utils import gdrive_download; gdrive_download('1n_oKgR81BJtqk75b00eAjdv03qVCQn2f','coco128.zip')" # Train command: python train.py --data ./data/coco128.yaml # Dataset should be placed next to yolov5 folder: # /parent_folder # /coco128 # /yolov5# train and val datasets (image directory or *.txt file with image paths) train: ../coco128/images/train2017/ val: ../coco128/images/train2017/# number of classes nc: 80# class names names: ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light','fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow','elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee','skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard','tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple','sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch','potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone','microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear','hair drier', 'toothbrush'](yolov5) shl@zfcv:~/shl/yolov5/data$

我們把該文件拷貝一份(這是我個人的習慣,你也可以不改,直接在coco128.yaml文件中進修改)

cp coco128.yaml hat_hair_beard.yaml

然后在hat_hair_beard.yaml中需要修改3處內(nèi)容:

1、訓練集和驗證集圖片的路徑

train: /home/shl/shl/yolov5/hat_hair_beard/images/train2017 val: /home/shl/shl/yolov5/hat_hair_beard/images/val2017

注意:

最好用絕對路徑,我在使用相對路徑的時候報錯,說路徑存在

2、修改類別數(shù)nc

nc=7 #我數(shù)據(jù)集一共分7個類別

3、修改類別列表,把類別修改為自己的類別

names: ['hard_hat', 'other', 'regular', 'long_hair', 'braid', 'bald', 'beard']

修改后的hat_hair_beard.yaml完整配置內(nèi)容如下:

# COCO 2017 dataset http://cocodataset.org - first 128 training images # Download command: python -c "from yolov5.utils.google_utils import gdrive_download; gdrive_download('1n_oKgR81BJtqk75b00eAjdv03qVCQn2f','coco128.zip')" # Train command: python train.py --data ./data/coco128.yaml # Dataset should be placed next to yolov5 folder: # /parent_folder # /coco128 # /yolov5# train and val datasets (image directory or *.txt file with image paths) #train: ../my_dataset/hat_hair_beard/images/train2017/ #val: ../my_dataset/hat_hair_beard/images/train2017/#train: ../hat_hair_beard/images/train2017 train: /home/shl/shl/yolov5/hat_hair_beard/images/train2017 #val: ../hat_hair_beard/images/val2017 val: /home/shl/shl/yolov5/hat_hair_beard/images/val2017# number of classes nc: 7# class names names: ['hard_hat', 'other', 'regular', 'long_hair', 'braid', 'bald', 'beard']

4.2.2 修改模型配置文件

修改模型配置文件,這里我使用的是yolov5/models/yolov5s.yaml模型的配置文件,個人習慣我還是把改配置文件拷貝一份,為:hat_hair_beard_yolov5s.yaml(你也可以不改,直接在yolov5.yaml中修改)

yolov5s.yaml配置文件中原內(nèi)容為:

(yolov5) shl@zfcv:~/shl/yolov5/models$ cat yolov5s.yaml # parameters nc: 80 # number of classes depth_multiple: 0.33 # model depth multiple width_multiple: 0.50 # layer channel multiple# anchors anchors:- [10,13, 16,30, 33,23] # P3/8- [30,61, 62,45, 59,119] # P4/16- [116,90, 156,198, 373,326] # P5/32# yolov5 backbone backbone:# [from, number, module, args][[-1, 1, Focus, [64, 3]], # 1-P1/2[-1, 1, Conv, [128, 3, 2]], # 2-P2/4[-1, 3, Bottleneck, [128]],[-1, 1, Conv, [256, 3, 2]], # 4-P3/8[-1, 9, BottleneckCSP, [256]],[-1, 1, Conv, [512, 3, 2]], # 6-P4/16[-1, 9, BottleneckCSP, [512]],[-1, 1, Conv, [1024, 3, 2]], # 8-P5/32[-1, 1, SPP, [1024, [5, 9, 13]]],[-1, 6, BottleneckCSP, [1024]], # 10]# yolov5 head head:[[-1, 3, BottleneckCSP, [1024, False]], # 11[-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1]], # 12 (P5/32-large)[-2, 1, nn.Upsample, [None, 2, 'nearest']],[[-1, 6], 1, Concat, [1]], # cat backbone P4[-1, 1, Conv, [512, 1, 1]],[-1, 3, BottleneckCSP, [512, False]],[-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1]], # 17 (P4/16-medium)[-2, 1, nn.Upsample, [None, 2, 'nearest']],[[-1, 4], 1, Concat, [1]], # cat backbone P3[-1, 1, Conv, [256, 1, 1]],[-1, 3, BottleneckCSP, [256, False]],[-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1]], # 22 (P3/8-small)[[], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)] (yolov5) shl@zfcv:~/shl/yolov5/models$

因此,在hat_hair_beard.yaml中只需要修改一處,把nc修改為自己的類別數(shù)即可

nc : 7

上面數(shù)據(jù)的準備和配置文件的修改全部準備好之后,就可以開始訓練了!!!

4.3 訓練自己的數(shù)據(jù)集

4.3.1 使用yolovs.pt預(yù)訓練模型進行訓練

訓練命令:

python train.py --img 640 --batch 16 --epochs 300 --data ./data/hat_hair_beard.yaml --cfg ./models/hat_hair_beard_yolov5s.yaml --weights ./weights/yolov5s.pt --device 1

關(guān)于參數(shù)的介紹,上面已經(jīng)介紹了,這里不再贅述

正常訓練,如下圖:

訓練結(jié)束后,會生成兩個預(yù)訓練的模型:

  • best.pt:保存的是中間一共比較好模型
  • last.pt:訓練結(jié)束后保存的最后模型

我把最終訓練的模型保存拷貝一份,防止下載再訓練給覆蓋,白白訓練!

注意:

當使用--device參數(shù)設(shè)置多GPU進行訓練時,可能會報錯:RuntimeError: Model replicas must have an equal number of parameters. 具體錯誤如下圖,會報錯的命令:

  • --device 1:指定單個GPU不會報錯
  • --device 1,2,3:當使用兩個以上的GPU會報錯
  • 官方的iusses解決方式:把torch的把那本更新為torch1.4,而我的torch為1.5版本

4.3.2 使用yolov5l.pt預(yù)訓練模型進行訓練

這是用yolov5l.pt預(yù)訓練模型訓練的效果

可以看到,使用yolov5l.pt預(yù)訓練模型,保存的最終模型和最優(yōu)模型都比較大:

  • best.pt:382M
  • last.pt:192M

4.4 使用訓練好的預(yù)訓練模型進行測試

1、單張圖片測試命令:

python detect.py --source inference/1_input/1_img/hat3.jpg --we ights ./weights/last_hat_hair_beard_20200804.pt --output inference/2_output/1_img/ --device 1

原圖:

測試結(jié)果圖:

從結(jié)果可以看到,置信度還是很高的,而且目標都檢測到了!(保存的結(jié)果圖片,會把上一此保存的測試結(jié)果圖刪了,最終只保存最后一側(cè)測試的結(jié)果圖)

2、圖片目錄測試

python detect.py --source inference/1_input/2_imgs_hat --weights ./weights/last_hat_hair_beard_20200804.pt --output inference/2_output/2_imgs_hat --device 1

下面是測試圖片集的效果:

4.5 在Tensorbaord上查看數(shù)據(jù)的訓練過程中的一些指標

使用如下命令,然后在瀏覽器中查看一些數(shù)據(jù)指標的可視化圖

tensorbaord --logdir=runs

1、scalars

2、images

5 推理測試

使用預(yù)訓練的模型進行推理測試,YOLOv5支持多種數(shù)據(jù)源推理測試,如下:

  • 圖像
  • 目錄
  • 視頻
  • 網(wǎng)絡(luò)攝像頭
  • http流
  • rtsp流

使用python detect.py進行推理,關(guān)于推理的更多參數(shù)使用如下命令查看:

python detect.py -h

  • --weights :預(yù)訓練模型.pt的路徑,默認值為:weights/yolov5s.pt
  • --source:輸入的數(shù)據(jù)源,可以是:圖片、目錄、視頻、網(wǎng)絡(luò)攝像頭、http和rtsp流,默認值為:interence/images
  • --output: 輸出檢測結(jié)果的路徑,默認值為:inference/output
  • --img-size :用于推理圖片的大小(pixels),默認值為:640
  • --conf-thres:對象的置信度閾值(object confidence threshold),默認值為:0.4
  • --iou-thres :NMS的IOU閾值( IOU threshold for NMS),默認值為:0.5
  • --fourcc:輸出視頻的編碼格式(必須是ffmepeg支持的),例如:H264格式,默認格式為:mp4v
  • --half: 使用版精度F16推理(half precision FP16 inference),布爾值,默認為true
  • --device:cuda設(shè)備,例如:0或0,1,2,3或cpu,默認''
  • --view-img :顯示結(jié)果,‘布爾值,默認為true’
  • --save-txt :把結(jié)果保存到*.txt文件中
  • --classes:過濾類別 CLASSES [CLASSES …],filter by class
  • --agnostic-nms:類不可知 NMS
  • --augment:增強推理(augmented inference)

我把自己的推理的輸出和輸入組織成如下文件結(jié)構(gòu):

(yolov5) shl@zfcv:~/shl/yolov5/inference$ tree -L 2 . ├── 1_input # 輸入 │ ├── 1_img │ ├── 2_imgs │ ├── 3_video │ ├── 4_Webcam │ ├── 5_http │ └── 6_rtsp └── 2_output # 輸出├── 1_img├── 2_imgs├── 3_video├── 4_Webcam├── 5_http└── 6_rtsp

5.1 圖像推理測試

1、推理圖片命令

python detect.py --source inference/1_input/1_img/bus.jpg --weights ./weights/yolov5s.pt --output inference/2_output/1_img/

直接指定輸出結(jié)果保存的目錄即可,保存名字和輸入圖片命令相同!

2、測試結(jié)果如下

測試圖片:

測試結(jié)果:

5.2 目錄推理測試

1、推理目錄下圖片集命令

python detect.py --source inference/1_input/2_imgs --weights ./weights/yolov5s.pt --output inference/2_output/2_imgs

2、測試結(jié)果如下

如果檢測中有些圖片置信度比較低的可以通過--conf-thres參數(shù)過濾掉,例如:

python detect.py --source inference/1_input/2_imgs --weights ./weights/yolov5s.pt --output inference/2_output/2_imgs --conf-thres 0.8

默認--conf-thres的值為0.4,如果我們把置信度的閾值設(shè)置為0.8,此時在下面的這圖中就看不到檢測目標的框!

5.3 視頻推理測試

1、推理視頻命令

python detect.py --source test.mp4 --weights ./weights/yolov5s.pt --output test_result/3_video

如果想指定輸出視頻的fourcc格式,用如下命令:

python detect.py --source test.mp4 --weights ./weights/yolov5s.pt --output test_result/3_video --fourcc H264

關(guān)于ffmeg支持的fourcc格式(參考),注意:視頻的格式必須時四個字符長度

2、推理視頻結(jié)果

本來我是想上傳視頻的,但是CSDN目前只支持騰訊、優(yōu)酷、嗶哩嗶哩,沒有自己的視頻服務(wù)器,如果上傳還需要等待審核,比較慢,我我就直接放個gif動圖,大家簡單看下效果吧,又由于CSDN限制上傳圖片小于5M,因此只能截取不到1秒(淚奔,我不想再去壓縮一下,費勁):

5.4 網(wǎng)絡(luò)攝像頭推理測試

5.5 http流推理測試

5.6 rtsp流推理測試

推理測試命令:

# 示例語法(不要運行此單元格) python detect.py --source ./file.jpg # 圖片 ./file.mp4 # 視頻./dir # 目錄0 # 網(wǎng)絡(luò)攝像頭'rtsp://170.93.143.139/rtplive/470011e600ef003a004ee33696235daa' # rtsp流'http://112.50.243.8/PLTV/88888888/224/3221225900/1.m3u8' # http流

6 可視化

6.1 訓練的模型的測試表現(xiàn)可視化

1、訓練開始后,瀏覽train*.jpg圖像查看訓練的圖片(training images)、標簽(labels)和數(shù)據(jù)增強的結(jié)果。注意:mosaic數(shù)據(jù)增強的數(shù)據(jù)用于訓練(增強圖片如下圖所示),這是由UItralytics在YOLOv4中創(chuàng)建的一種圖像數(shù)據(jù)增強方法。如果你發(fā)現(xiàn)你標注的標簽有不正確的,你應(yīng)該回去重新標注!

Image(filename='./train_batch1.jpg', width=900) # view augmented training mosaics

2、第一個epoch完成之后,查看test_batch0_gt.jpg,可以看到測試batch 0 ground truth的標簽,如下圖所示:

Image(filename='./test_batch0_gt.jpg', width=900) # view test image labels

3、通過查看test_batch0_pred.jpg來查看test batch 0 predictions,結(jié)果下圖所示:

Image(filename='./test_batch0_pred.jpg', width=900) # view test image predictions

6.2 訓練損失和性能指標視化

訓練損失(training losses)和性能指標(performance metrrics)被保存到Tensorboard和results.txt日志文件中。result.txt繪制訓練完成之后的結(jié)果,保存為result.png。可以使用如下代碼,繪制部分完成的results.txt

from utils.utils import plot_results; plot_results() # plot results.txt as results.png Image(filename='./results.png', width=1000) # view results.png

這里我們顯示YOLOv5s在coco128上訓練100 epochs:

  • 橘黃色曲線:是從頭開始訓練
  • 藍色曲線:從預(yù)訓練的yolov5s.pt權(quán)重開始訓練,

參考1
參考2
參考3






? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ? ⊕ ?

總結(jié)

以上是生活随笔為你收集整理的YOLOv5的详细使用教程,以及使用yolov5训练自己的数据集的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。