最美情侣中文字幕电影,在线麻豆精品传媒,在线网站高清黄,久久黄色视频

歡迎光臨散文網(wǎng) 會員登陸 & 注冊

YOLOV5 環(huán)境搭建和使用記錄

2022-01-27 17:34 作者:Love丶伊卡洛斯  | 我要投稿

前言

yolov5 github:[https://github.com/ultralytics/yolov5](https://github.com/ultralytics/yolov5)

測試顯卡:GTX 2060

python版本:3.8.12

CUDA版本:11.6

pytorch版本:1.10.1

環(huán)境搭建和測試運行中 遇到相關報錯可參考?[報錯相關]

環(huán)境搭建

Anaconda

當然如果你不想用Anaconda,可以跳過這一步,直接安裝和配置你的python環(huán)境也可以。

我這采取的方案是 本地環(huán)境 [Anaconda](https://www.anaconda.com/)

python版本選的 python3.8.12,創(chuàng)建環(huán)境

yolov5克隆到本地

官方倉庫clone命令 `git clone https://github.com/ultralytics/yolov5`

我這采取的方案是fork了倉庫 同步到了gitee,然后clone

## 安裝相關依賴庫

如果你不想用pycharm,也可以直接cmd進入指定目錄,然后執(zhí)行pip安裝命令

我這采用pycharm打開工程,配置為 conda的環(huán)境

根據(jù)官方說明文檔進行安裝

激活我們剛才創(chuàng)建的環(huán)境 py38-img

執(zhí)行pip命令 `pip install -r requirements.txt`

完成安裝。

ps:我這已經(jīng)換了源

路徑:`C:\Users\用戶名\pip`

pip.ini 內(nèi)容為:

```ini

[global]

index-url = https://pypi.tuna.tsinghua.edu.cn/simple

[install]

trusted-host = https://pypi.tuna.tsinghua.edu.cn

```

安裝CUDA和cuDNN(有顯卡需求的話)

據(jù) [RuntimeError: CUDA error: no kernel image is available for execution on the device](https://blog.csdn.net/qq_43391414/article/details/110562749)得知,如果你要使用torch 1.7,GPU算力至少要達到5.2。那么根據(jù)博主提供的算力表,如果沒達標就不用裝了 pytorch安裝cpu版本。

*ps:我的顯卡是RTX2060*

參考文章:[win10安裝CUDA和cuDNN的正確姿勢](https://zhuanlan.zhihu.com/p/94220564?utm_source=wechat_session)

CUDA下載頁面:[https://developer.nvidia.com/cuda-downloads](https://developer.nvidia.com/cuda-downloads)

cuDNN下載頁面:[https://developer.nvidia.com/rdp/cudnn-download](https://developer.nvidia.com/rdp/cudnn-download)

根據(jù)教程 安裝和配置好環(huán)境, cudnn里面的文件 需要復制到 cuda的對應文件夾下。這里訪問比較困難

我這同步到了阿里云盤:「cuda_11.6.0_511.23_windows.exe」[https://www.aliyundrive.com/s/6Q4yRH9nJ8Q]

環(huán)境變量的配置

```

C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.6

C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.6\lib\x64

```


安裝完后的測試 `nvcc -V`


C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.6\extras\demo_suite 執(zhí)行測試程序



這是我的相關參數(shù)


pytorch單獨再次安裝(視情況采用)

如果你前面采用了pip安裝依賴,此處需要先卸載了 `pip uninstall torch torchvision`

因為pytorch這塊安裝有 cpu only的版本 所以我掉了很多次坑

參考:[Windows環(huán)境下Anaconda3安裝配置pytorch詳細步驟(踩坑匯總)](https://blog.csdn.net/qq_41282258/article/details/98961667)

[Pytorch版本、CUDA版本與顯卡驅動版本的對應關系](https://blog.csdn.net/kellyroslyn/article/details/109668001)

注意版本是否對應!

pytorch官網(wǎng):[https://pytorch.org/]

根據(jù)你的需求生成安裝命令,(后綴的 -c pytorch不刪 是走官網(wǎng)下載,可以嘗試刪除)

```bash

conda install pytorch torchvision torchaudio cudatoolkit=11.3 -c pytorch

```

查看 安裝的相關庫 `conda list` ,沒有帶 cpuonly 對頭

CPU版 `conda install pytorch torchvision torchaudio cpuonly -c pytorch`



測試官方demo

detect.py識別 bus.jpg

源碼里面寫了相關的使用命令和傳參,當然直接跑多半會報錯

正常情況運行命令 `python detect.py --weights yolov5s.pt --source data\images\bus.jpg`,可以完成圖片識別,顯示結果到runs下的exp里

當然 細心的你會發(fā)現(xiàn)缺少了 對應的權重文件 **yolov5s.pt**,相應的權重文件可以在官方github倉庫下載:[https://github.com/ultralytics/yolov5/releases](https://github.com/ultralytics/yolov5/releases)

當然如果你沒有下載,例程也會自動幫你運行下載程序,不過網(wǎng)絡不好的情況下多半會出現(xiàn)443等報錯然后下載失敗。


另外你例程會下載字體包 **Arial.ttf**,如果下載失敗可以自行去提示的官網(wǎng)下載,然后存放在指定路徑下 `C:\Users\用戶名\AppData\Roaming\Ultralytics`,并安裝字體包。


我這阿里云盤也上傳了:[https://www.aliyundrive.com/s/xzgh5fr6yLU]

train.py訓練模型

訓練官方提供的coco128

源碼里也同樣提供了 參考的命令 當然直接跑也是運行不了的啦

當然我這提供了運行命令,先創(chuàng)建文件夾 datasets,然后將coco128數(shù)據(jù)集下載后解壓進去(當然例程會自己下載,不過我這下載還是失敗了)


```bash

$ cd datasets

$ python ..\train.py --data ..\data\coco128.yaml --img 128

```


例程會讀取 `data\coco128.yaml` 文件,yaml里面寫了下載的數(shù)據(jù)集路徑,你可以手動下載然后解壓到datasets里面

[https://ultralytics.com/assets/coco128.zip]

再次執(zhí)行我們的訓練命令 ,開始訓練(默認訓練300輪 可以通過--epochs 修改輪數(shù),另外默認配置還是比較吃電腦配置的,如果只是測個程序而已,可以使用我這提供的第3條命令)

**(如果報錯:DefaultCPUAllocator: not enough memory,內(nèi)存不足,就需要調(diào)小配置 更多報錯參考文章末尾的目錄 報錯相關)**

```bash

$ cd datasets

$ python ..\train.py --data ..\data\coco128.yaml --img 128

$ python ..\train.py --data ..\data\coco128.yaml --epochs 3 --batch-size 1 --workers 1 --img 128

```

訓練自己的模型

當然可以不訓練這個了,自己隨便搞個test訓練訓練(這個test訓練集 由[labelimg](https://github.com/tzutalin/labelImg) 工具協(xié)助生成) labelimg相關使用可以參考下面的部分?

開始訓練 `python ..\train.py --data test\test.yaml --epochs 3 --batch-size 2? --weights ..\runs\train\exp26\weights\last.pt --nosave --cache` (注意我這里傳了不少參數(shù),如果你不需要可以不加 --epochs是訓練輪數(shù),因為測試所以先調(diào)小點,節(jié)約時間。*具體各個參數(shù)的含義可以看下面的參考圖或直接看源碼*)

報錯 OSError: [WinError 1455] 頁面文件太小,無法完成操作。你可以調(diào)小 --batch-size

配合 命令 ```nvidia-smi```,查看顯卡信息

下圖轉自 [yolov5訓練相關參數(shù)解釋](https://blog.csdn.net/weixin_41990671/article/details/107300314)

相關訓練參數(shù)可參考:[yolov5訓練相關參數(shù)解釋](https://blog.csdn.net/weixin_41990671/article/details/107300314)

我們調(diào)小 --batch-size?

`python ..\train.py --data test\test.yaml --epochs 3 --batch-size 2? --weights ..\runs\train\exp26\weights\last.pt --nosave --cache`,成功完成訓練。訓練結果默認存儲在 `runs\train\exp` 等下面,我們的權重文件 生成了2個 last.pt, best.pt。當然可能你只會生成1個last.pt,問題不大,繼續(xù)練。

訓練好后的權重 pt拿去 再次detect.py識別

相關命令

```bash

$ cd datasets

$ python ..\detect.py --weights ..\runs\train\exp29\weights\best.pt --source test\test --conf-thres 0.5

```

源碼有各傳參的解釋,我們這追加了 --conf-thres 傳入

因為這個模型我已經(jīng)提前鍛煉過,所以 準確性較高。

置信度還是很不錯的 ,當然你剛開始訓練的話,基本也就0.1差不多(粗略估計)

labelimg相關使用

下載

官方倉庫:[https://github.com/tzutalin/labelImg/releases]

使用

解壓,運行exe

刪除默認提供的類名(根據(jù)自己需要)

我這推薦的幾個實用的快捷鍵?


```bash

w 創(chuàng)建選框

a 前一張圖片

d 后一張圖片

ctrl+S 保存

```

準備需要標注的圖片數(shù)據(jù)集

我這按自己喜歡的結構創(chuàng)建,images 和 labels 文件夾 和 yaml文件,在外面套個文件夾

我們將要標注的原始圖片放在 images文件夾內(nèi)

從百度爬點圖片

然后我們開始用工具進行標注,“open dir”打開我們需要標注的圖片的文件夾

圖片會自動加載進來

“change save dir”設置保存labels的路徑為我們的 labels

修改標注的格式為**yolo**(點擊切換)

然后就是使用我們的快捷鍵 進行框選區(qū)域和打標簽了。(記得保存)

標注完,保存后,生成的配置都在 對應文件夾下,classes.txt為所有的labels,其他單個文件為 對應label的參數(shù)

修改 yaml文件的相關配置


```bash

# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]

path: ikaros? # dataset root dir

train: images? # train images (relative to 'path') 128 images

val: images? # val images (relative to 'path') 128 images

test:? # test images (optional)


# Classes

nc: 1? # number of classes

names: ['ikaros']? # class names

```


拉去訓練,1組報錯

追加一個類

改yaml為

```bash

# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]

path: ikaros? # dataset root dir

train: images? # train images (relative to 'path') 128 images

val: images? # val images (relative to 'path') 128 images

test:? # test images (optional)


# Classes

nc: 2? # number of classes

names: ['ikaros',

'ZhiShu']? # class names

```


從零開始的train.py訓練生活

前面準備工作做好后,開始訓練 先叫上GPU來100組俯臥撐(當然 你GPU兄弟累了 可以不叫他 誒嘿~)


```bash

$ cd datasets

$ python ..\train.py --data ikaros\ikaros.yaml --epochs 100 --batch-size 1 --nosave --cache

```


100組終于練好了。可以發(fā)現(xiàn)我們的鍛煉結果不咋滴哈,all mAP@.5只有 0.394,沒有0.5的置信度我很難辦事呀,兄弟還得練哈?

?我們先拿這個練完100組的權重兄去測一測,置信度閾值設為0.3

?

```bash

python ..\detect.py --weights ..\runs\train\exp35\weights\best.pt --source ikaros\images --conf-thres 0.3

```

還行 還得多練練

置信度閾值設為0.01

?

```bash

python ..\detect.py --weights ..\runs\train\exp35\weights\best.pt --source ikaros\images --conf-thres 0.01

```

差不多了 在多練練。前面練好的pt不要丟,叫上繼續(xù)訓練 再來100組


```bash

python ..\train.py --data ikaros\ikaros.yaml --epochs 100 --weights ..\runs\train\exp35\weights\best.pt --batch-size 1 --nosave --cache

```

再次 測試 `python ..\detect.py --weights ..\runs\train\exp36\weights\last.pt --source ikaros\images --conf-thres 0.5`,差不多得了,有興趣接著練

增加了樣本數(shù),繼續(xù)鍛煉


```bash

python ..\train.py --data ikaros\ikaros.yaml --epochs 100 --weights ..\runs\train\exp36\weights\last.pt --batch-size 1 --workers 4? --nosave --cache

```

mAP@.5 0.745 效果不錯了

找個視頻識別下


```bash

python ..\detect.py --weights ..\runs\train\ikaros\ikaros.pt --source ..\data\videos\FallenDown.mp4

```

拓展應用

打印信息只提取識別的結果(獲取類名和置信值),不顯示其他無用信息

效果如下:


替換detecy.py源碼

```python

# YOLOv5 ?? by Ultralytics, GPL-3.0 license

"""

Run inference on images, videos, directories, streams, etc.


python detect2.py --weights yolov5s.pt --source data\images\bus.jpg --nosave


Usage - sources:

? ? $ python path/to/detect.py --weights yolov5s.pt --source 0? ? ? ? ? ? ? # webcam

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?img.jpg? ? ? ? # image

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?vid.mp4? ? ? ? # video

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?path/? ? ? ? ? # directory

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?path/*.jpg? ? ?# glob

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?'https://youtu.be/Zgi9g1ksQHc'? # YouTube

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?'rtsp://example.com/media.mp4'? # RTSP, RTMP, HTTP stream


Usage - formats:

? ? $ python path/to/detect.py --weights yolov5s.pt? ? ? ? ? ? ? ? ?# PyTorch

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?yolov5s.torchscript? ? ? ? # TorchScript

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?yolov5s.onnx? ? ? ? ? ? ? ?# ONNX Runtime or OpenCV DNN with --dnn

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?yolov5s.xml? ? ? ? ? ? ? ? # OpenVINO

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?yolov5s.engine? ? ? ? ? ? ?# TensorRT

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?yolov5s.mlmodel? ? ? ? ? ? # CoreML (MacOS-only)

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?yolov5s_saved_model? ? ? ? # TensorFlow SavedModel

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?yolov5s.pb? ? ? ? ? ? ? ? ?# TensorFlow GraphDef

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?yolov5s.tflite? ? ? ? ? ? ?# TensorFlow Lite

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?yolov5s_edgetpu.tflite? ? ?# TensorFlow Edge TPU

"""


import argparse

import os

import sys

from pathlib import Path


import CV2

import torch

import torch.backends.cudnn as cudnn


FILE = Path(__file__).resolve()

ROOT = FILE.parents[0]? # YOLOv5 root directory

if str(ROOT) not in sys.path:

? ? sys.path.Append(str(ROOT))? # add ROOT to PATH

ROOT = Path(os.path.relpath(ROOT, Path.cwd()))? # relative


from models.common import DetectMultiBackend

from utils.datasets import IMG_FORMATS, VID_FORMATS, LoadImages, LoadStreams

from utils.general import (LOGGER, check_file, check_img_size, check_imshow, check_requirements, colorstr,

? ? ? ? ? ? ? ? ? ? ? ? ? ?increment_path, non_max_suppression, print_args, scale_coords, strip_optimizer, xyxy2xywh)

from utils.plots import Annotator, colors, save_one_box

from utils.torch_utils import select_device, time_sync



@torch.no_grad()

def run(weights=ROOT / 'yolov5s.pt',? # model.pt path(s)

? ? ? ? source=ROOT / 'data/images',? # file/dir/URL/glob, 0 for webcam

? ? ? ? data=ROOT / 'data/coco128.yaml',? # dataset.yaml path

? ? ? ? imgsz=(640, 640),? # inference size (height, width)

? ? ? ? conf_thres=0.25,? # confidence threshold

? ? ? ? iou_thres=0.45,? # NMS IOU threshold

? ? ? ? max_det=1000,? # maximum detections per image

? ? ? ? device='',? # cuda device, i.e. 0 or 0,1,2,3 or cpu

? ? ? ? view_img=False,? # show results

? ? ? ? save_txt=False,? # save results to *.txt

? ? ? ? save_conf=False,? # save confidences in --save-txt labels

? ? ? ? save_crop=False,? # save cropped prediction boxes

? ? ? ? nosave=False,? # do not save images/videos

? ? ? ? classes=None,? # filter by class: --class 0, or --class 0 2 3

? ? ? ? agnostic_nms=False,? # class-agnostic NMS

? ? ? ? augment=False,? # augmented inference

? ? ? ? visualize=False,? # visualize features

? ? ? ? update=False,? # update all models

? ? ? ? project=ROOT / 'runs/detect',? # save results to project/name

? ? ? ? name='exp',? # save results to project/name

? ? ? ? exist_ok=False,? # existing project/name ok, do not increment

? ? ? ? line_thickness=3,? # bounding box thickness (pixels)

? ? ? ? hide_labels=False,? # hide labels

? ? ? ? hide_conf=False,? # hide confidences

? ? ? ? half=False,? # use FP16 half-precision inference

? ? ? ? dnn=False,? # use OpenCV DNN for ONNX inference

? ? ? ? ):

? ? source = str(source)

? ? save_img = not nosave and not source.endswith('.txt')? # save inference images

? ? is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)

? ? is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))

? ? webcam = source.isnumeric() or source.endswith('.txt') or (is_url and not is_file)

? ? if is_url and is_file:

? ? ? ? source = check_file(source)? # download


? ? # Directories

? ? save_dir = increment_path(Path(project) / name, exist_ok=exist_ok)? # increment run

? ? (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True)? # make dir


? ? # Load model

? ? device = select_device(device)

? ? model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data)

? ? stride, names, pt, jit, onnx, engine = model.stride, model.names, model.pt, model.jit, model.onnx, model.engine

? ? imgsz = check_img_size(imgsz, s=stride)? # check image size


? ? # Half

? ? half &= (pt or jit or onnx or engine) and device.type != 'cpu'? # FP16 supported on limited backends with CUDA

? ? if pt or jit:

? ? ? ? model.model.half() if half else model.model.float()


? ? # Dataloader

? ? if webcam:

? ? ? ? view_img = check_imshow()

? ? ? ? cudnn.benchmark = True? # set True to speed up constant image size inference

? ? ? ? dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt)

? ? ? ? bs = len(dataset)? # batch_size

? ? else:

? ? ? ? dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt)

? ? ? ? bs = 1? # batch_size

? ? vid_path, vid_writer = [None] * bs, [None] * bs


? ? # Run inference

? ? model.warmup(imgsz=(1, 3, *imgsz), half=half)? # warmup

? ? dt, seen = [0.0, 0.0, 0.0], 0

? ? for path, im, im0s, vid_cap, s in dataset:

? ? ? ? # 自定義存儲輸出結果的變量

? ? ? ? out_str = ''

? ? ? ? out_str2 = ''


? ? ? ? t1 = time_sync()

? ? ? ? im = torch.from_numpy(im).to(device)

? ? ? ? im = im.half() if half else im.float()? # uint8 to fp16/32

? ? ? ? im /= 255? # 0 - 255 to 0.0 - 1.0

? ? ? ? if len(im.shape) == 3:

? ? ? ? ? ? im = im[None]? # expand for batch dim

? ? ? ? t2 = time_sync()

? ? ? ? dt[0] += t2 - t1


? ? ? ? # Inference

? ? ? ? visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False

? ? ? ? pred = model(im, augment=augment, visualize=visualize)

? ? ? ? t3 = time_sync()

? ? ? ? dt[1] += t3 - t2


? ? ? ? # NMS

? ? ? ? pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)

? ? ? ? dt[2] += time_sync() - t3


? ? ? ? # Second-stage classifier (optional)

? ? ? ? # pred = utils.general.Apply_classifier(pred, classifier_model, im, im0s)


? ? ? ? # Process predictions

? ? ? ? for i, det in enumerate(pred):? # per image

? ? ? ? ? ? seen += 1

? ? ? ? ? ? if webcam:? # batch_size >= 1

? ? ? ? ? ? ? ? p, im0, frame = path[i], im0s[i].copy(), dataset.count

? ? ? ? ? ? ? ? s += f'{i}: '

? ? ? ? ? ? else:

? ? ? ? ? ? ? ? p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)


? ? ? ? ? ? p = Path(p)? # to Path

? ? ? ? ? ? save_path = str(save_dir / p.name)? # im.jpg

? ? ? ? ? ? txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}')? # im.txt

? ? ? ? ? ? s += '%gx%g ' % im.shape[2:]? # print string

? ? ? ? ? ? gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]? # normalization gain whwh

? ? ? ? ? ? imc = im0.copy() if save_crop else im0? # for save_crop

? ? ? ? ? ? annotator = Annotator(im0, line_width=line_thickness, example=str(names))

? ? ? ? ? ? if len(det):

? ? ? ? ? ? ? ? # Rescale boxes from img_size to im0 size

? ? ? ? ? ? ? ? det[:, :4] = scale_coords(im.shape[2:], det[:, :4], im0.shape).round()


? ? ? ? ? ? ? ? # Print results

? ? ? ? ? ? ? ? for c in det[:, -1].unique():

? ? ? ? ? ? ? ? ? ? n = (det[:, -1] == c).sum()? # detections per class

? ? ? ? ? ? ? ? ? ? s += f"{n} {names[int(c)]}{'s' * (n > 1)}, "? # add to string

? ? ? ? ? ? ? ? ? ? out_str += f"{n} {names[int(c)]}{'s' * (n > 1)}, "? # add to string


? ? ? ? ? ? ? ? # Write results

? ? ? ? ? ? ? ? for *xyxy, conf, cls in reversed(det):

? ? ? ? ? ? ? ? ? ? # 標簽名 和 置信度

? ? ? ? ? ? ? ? ? ? out_str2 += f'{names[int(cls)]} {conf:.2f} '


? ? ? ? ? ? ? ? ? ? if save_txt:? # Write to file

? ? ? ? ? ? ? ? ? ? ? ? xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()? # normalized xywh

? ? ? ? ? ? ? ? ? ? ? ? line = (cls, *xywh, conf) if save_conf else (cls, *xywh)? # label format

? ? ? ? ? ? ? ? ? ? ? ? with open(txt_path + '.txt', 'a') as f:

? ? ? ? ? ? ? ? ? ? ? ? ? ? f.write(('%g ' * len(line)).rstrip() % line + '\n')


? ? ? ? ? ? ? ? ? ? if save_img or save_crop or view_img:? # Add bbox to image

? ? ? ? ? ? ? ? ? ? ? ? c = int(cls)? # integer class

? ? ? ? ? ? ? ? ? ? ? ? label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')

? ? ? ? ? ? ? ? ? ? ? ? annotator.box_label(xyxy, label, color=colors(c, True))

? ? ? ? ? ? ? ? ? ? ? ? if save_crop:

? ? ? ? ? ? ? ? ? ? ? ? ? ? save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)


? ? ? ? ? ? # Print time (inference-only)

? ? ? ? ? ? # LOGGER.info(f'{s}Done. ({t3 - t2:.3f}s)')


? ? ? ? ? ? # 輸出為:image 1/1 F:\github_pro\yolov5\data\images\bus.jpg: 640x480 4 persons, 1 bus, Done. (0.256s)

? ? ? ? ? ? # LOGGER.warning(f'{s}Done. ({t3 - t2:.3f}s)')

? ? ? ? ? ? # 輸出為:4 persons, 1 bus,

? ? ? ? ? ? LOGGER.warning(f'{out_str}')

? ? ? ? ? ? # 輸出為:person 0.31 bus 0.81 person 0.83 person 0.85 person 0.87

? ? ? ? ? ? LOGGER.warning(f'{out_str2}')


? ? ? ? ? ? # Stream results

? ? ? ? ? ? im0 = annotator.result()

? ? ? ? ? ? if view_img:

? ? ? ? ? ? ? ? CV2.imshow(str(p), im0)

? ? ? ? ? ? ? ? CV2.waitKey(1)? # 1 millisecond


? ? ? ? ? ? # Save results (image with detections)

? ? ? ? ? ? if save_img:

? ? ? ? ? ? ? ? if dataset.mode == 'image':

? ? ? ? ? ? ? ? ? ? CV2.imwrite(save_path, im0)

? ? ? ? ? ? ? ? else:? # 'video' or 'stream'

? ? ? ? ? ? ? ? ? ? if vid_path[i] != save_path:? # new video

? ? ? ? ? ? ? ? ? ? ? ? vid_path[i] = save_path

? ? ? ? ? ? ? ? ? ? ? ? if isinstance(vid_writer[i], CV2.VideoWriter):

? ? ? ? ? ? ? ? ? ? ? ? ? ? vid_writer[i].release()? # release previous video writer

? ? ? ? ? ? ? ? ? ? ? ? if vid_cap:? # video

? ? ? ? ? ? ? ? ? ? ? ? ? ? fps = vid_cap.get(CV2.CAP_PROP_FPS)

? ? ? ? ? ? ? ? ? ? ? ? ? ? w = int(vid_cap.get(CV2.CAP_PROP_FRAME_WIDTH))

? ? ? ? ? ? ? ? ? ? ? ? ? ? h = int(vid_cap.get(CV2.CAP_PROP_FRAME_HEIGHT))

? ? ? ? ? ? ? ? ? ? ? ? else:? # stream

? ? ? ? ? ? ? ? ? ? ? ? ? ? fps, w, h = 30, im0.shape[1], im0.shape[0]

? ? ? ? ? ? ? ? ? ? ? ? ? ? save_path += '.mp4'

? ? ? ? ? ? ? ? ? ? ? ? vid_writer[i] = CV2.VideoWriter(save_path, CV2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))

? ? ? ? ? ? ? ? ? ? vid_writer[i].write(im0)


? ? # Print results

? ? t = tuple(x / seen * 1E3 for x in dt)? # speeds per image

? ? LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t)

? ? if save_txt or save_img:

? ? ? ? s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''

? ? ? ? LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")

? ? if update:

? ? ? ? strip_optimizer(weights)? # update model (to fix SourceChangeWarning)



def parse_opt():

? ? parser = argparse.ArgumentParser()

? ? parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model path(s)')

? ? parser.add_argument('--source', type=str, default=ROOT / 'data/images', help='file/dir/URL/glob, 0 for webcam')

? ? parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='(optional) dataset.yaml path')

? ? parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w')

? ? parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold')

? ? parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold')

? ? parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')

? ? parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')

? ? parser.add_argument('--view-img', action='store_true', help='show results')

? ? parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')

? ? parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')

? ? parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')

? ? parser.add_argument('--nosave', action='store_true', help='do not save images/videos')

? ? parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --classes 0, or --classes 0 2 3')

? ? parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')

? ? parser.add_argument('--augment', action='store_true', help='augmented inference')

? ? parser.add_argument('--visualize', action='store_true', help='visualize features')

? ? parser.add_argument('--update', action='store_true', help='update all models')

? ? parser.add_argument('--project', default=ROOT / 'runs/detect', help='save results to project/name')

? ? parser.add_argument('--name', default='exp', help='save results to project/name')

? ? parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')

? ? parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')

? ? parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')

? ? parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')

? ? parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')

? ? parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')

? ? opt = parser.parse_args()

? ? opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1? # expand

? ? # print_args(FILE.stem, opt)

? ? return opt



def main(opt):

? ? # CRITICAL = 50

? ? # FATAL = CRITICAL

? ? # ERROR = 40

? ? # WARNING = 30

? ? # WARN = WARNING

? ? # INFO = 20

? ? # DEBUG = 10

? ? # NOTSET = 0

? ? LOGGER.setLevel(30)

? ? check_requirements(exclude=('tensorboard', 'thop'))

? ? run(**vars(opt))



if __name__ == "__main__":

? ? opt = parse_opt()

? ? main(opt)


```


報錯相關

RuntimeError: [enforce fail at ..\c10\core\CPUAllocator.cpp:76] data. DefaultCPUAllocator: not enough memory: you tried to allocate 131072000 bytes.

申請內(nèi)存過多,沒有足夠的內(nèi)存了。

解決方案:同樣也是 調(diào)小 --batch-size 和 --workers?

參考命令:


```bash

python ..\train.py --data ..\data\coco128.yaml --epochs 3 --batch-size 1 --workers 1 --img 128

```


報錯 OSError: [WinError 1455] 頁面文件太小,無法完成操作。

增加分配虛擬內(nèi)存,然后重啟。調(diào)小 --batch-size,或者改? --batch-size -1 自動識別(不過我這就經(jīng)常崩潰)

減小 --workers?


```bash

# 我的顯卡是RTX2060 測了幾套下來,基本上--batch-size 2 --workers 8 不能再高了

python ..\train.py --data ikaros\ikaros.yaml --epochs 100 --weights ..\runs\train\exp36\weights\last.pt --batch-size 1 --workers 4? --nosave --cache

```


不吃GPU 實則環(huán)境錯誤的情況

基本會報錯 `UserWarning: User provided device_type of 'cuda', but CUDA is not available.`

看看 CUDA 相關環(huán)境是否裝好;看 pytorch版本是否匹配,是否錯裝了 cpuonly版;命令是否寫錯了

Arial.ttf 字體包缺失

例程會下載字體包 Arial.ttf,如果下載失敗可以自行去提示的官網(wǎng)下載,然后存放在指定路徑下 `C:\Users\用戶名\AppData\Roaming\Ultralytics`,并安裝字體包。

我這阿里云盤也上傳了:[https://www.aliyundrive.com/s/xzgh5fr6yLU]

CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://repo.anaconda.co

參考:[CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://repo.anaconda.co](https://blog.csdn.net/qq_35443700/article/details/107951536)

Solving environment: failed with initial frozen solve. Retrying with flexible solve.

參考:[conda install 安裝很慢并且Solving environment: failed with initial frozen solve.](https://zhuanlan.zhihu.com/p/371346329)

PackagesNotFoundError: The following packages are not available from current channels:

? - torch

網(wǎng)上的方法不太管用,全部重裝算了。


```bash

pip uninstall -r requirements.txt

conda uninstall pytorch torchvision torchaudio cudatoolkit

```

還卸不掉了,呃?

直接環(huán)境刪了 算了?

重裝還是同樣的問題


換命令走官方鏡像

```bash

conda install pytorch torchvision torchaudio cudatoolkit=11.3 -c pytorch

```

Key already registered with the same priority: GroupSpatialSoftmax

參考:[(解決)Key already registered with the same priority: GroupSpatialSoftmax](https://www.baidu.com/link?url=4c8HnwK-0nAahcXBAqdCmrVDHrtXTsYSOlf2604sLzQGTsLIvpQqkY7j3-pySdzD43d9p_a0t6saoPapzuAwVao-wAseL2r-xh7LfJPqGoi&wd=&eqid=c4535a1700005f7d0000000561ef816e)

先嘗試卸載了 `conda uninstall pytorch` 和 `pip uninstall torch torchvision`

然后重新安裝 ```conda install pytorch torchvision torchaudio cudatoolkit=11.3 -c pytorch```


RuntimeError: CUDA error: no kernel image is available for execution on the device

訓練 報錯(測試顯卡 GT 720)

參考:[RuntimeError: CUDA error: no kernel image is available for execution on the device](https://blog.csdn.net/qq_43391414/article/details/110562749)

據(jù)參考文章解釋為更換低版本pytorch,低于1.2,那肯定是沒救了

換CPU版了

卸載前面裝的庫 `conda uninstall pytorch torchvision torchaudio cudatoolkit`

官網(wǎng)查看cpu版安裝命令 `conda install pytorch torchvision torchaudio cpuonly -c pytorch`

再次訓練,成功


YOLOV5 環(huán)境搭建和使用記錄的評論 (共 條)

分享到微博請遵守國家法律
酒泉市| 嘉黎县| 阿勒泰市| 皮山县| 三门峡市| 临武县| 浦北县| 呼图壁县| 嘉善县| 绥江县| 宁河县| 邵阳县| 睢宁县| 华容县| 政和县| 镇巴县| 汝州市| 大城县| 凌海市| 卢湾区| 阳山县| 和硕县| 荆门市| 自治县| 邹城市| 涡阳县| 广安市| 阳东县| 股票| 恩平市| 靖宇县| 邮箱| 鄂托克旗| 安图县| 庆元县| 巨鹿县| 南乐县| 沁源县| 综艺| 浦县| 沅江市|