如何將Yolov5的detect.py修改為可以直接調(diào)用的函數(shù)詳解
前幾天學(xué)習(xí)了Yolov5,當(dāng)我想實際將Yolov5實際運用的時候卻不知道怎么辦了
然后我決定對Yolov5的detect.py修改為可以直接調(diào)用的函數(shù)
因為我只需要識別圖片,所以我將detect.py修改為只要傳入一張圖片他就可以返回坐標(biāo)
ps:我這里用的是Yolov5(6.0版本)
# Copyright (c) 2022 guluC
#導(dǎo)入需要的庫
import os
import sys
from pathlib import Path
import numpy as np
import cv2
import torch
import torch.backends.cudnn as cudnn
#初始化目錄
FILE = Path(__file__).resolve()
ROOT = FILE.parents[0] # 定義YOLOv5的根目錄
if str(ROOT) not in sys.path:
sys.path.append(str(ROOT)) # 將YOLOv5的根目錄添加到環(huán)境變量中(程序結(jié)束后刪除)
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
#導(dǎo)入letterbox
from utils.augmentations import Albumentations, augment_hsv, copy_paste, letterbox, mixup, random_perspective
weights=ROOT / 'yolov5s.pt' # 權(quán)重文件地址 .pt文件
source=ROOT / 'data/images' # 測試數(shù)據(jù)文件(圖片或視頻)的保存路徑
data=ROOT / 'data/coco128.yaml' # 標(biāo)簽文件地址 .yaml文件
imgsz=(640, 640) # 輸入圖片的大小 默認(rèn)640(pixels)
conf_thres=0.25 # object置信度閾值 默認(rèn)0.25 用在nms中
iou_thres=0.45 # 做nms的iou閾值 默認(rèn)0.45 用在nms中
max_det=1000 # 每張圖片最多的目標(biāo)數(shù)量 用在nms中
device='0' # 設(shè)置代碼執(zhí)行的設(shè)備 cuda device, i.e. 0 or 0,1,2,3 or cpu
classes=None # 在nms中是否是只保留某些特定的類 默認(rèn)是None 就是所有類只要滿足條件都可以保留 --class 0, or --class 0 2 3
agnostic_nms=False # 進行nms是否也除去不同類別之間的框 默認(rèn)False
augment=False # 預(yù)測是否也要采用數(shù)據(jù)增強 TTA 默認(rèn)False
visualize=False # 特征圖可視化 默認(rèn)FALSE
half=False # 是否使用半精度 Float16 推理 可以縮短推理時間 但是默認(rèn)是False
dnn=False # 使用OpenCV DNN進行ONNX推理
# 獲取設(shè)備
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) # 檢查圖片尺寸
# Half
# 使用半精度 Float16 推理
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()
def detect(img):
# Dataloader
# 載入數(shù)據(jù)
dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt)
# Run inference
# 開始預(yù)測
model.warmup(imgsz=(1, 3, *imgsz), half=half) # warmup
dt, seen = [0.0, 0.0, 0.0], 0
#對圖片進行處理
im0 = img
# Padded resize
im = letterbox(im0, imgsz, stride, auto=pt)[0]
# Convert
im = im.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB
im = np.ascontiguousarray(im)
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
# 預(yù)測
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
#用于存放結(jié)果
detections=[]
# Process predictions
for i, det in enumerate(pred): # per image 每張圖片
seen += 1
# im0 = im0s.copy()
if len(det):
# Rescale boxes from img_size to im0 size
det[:, :4] = scale_coords(im.shape[2:], det[:, :4], im0.shape).round()
# Write results
# 寫入結(jié)果
for *xyxy, conf, cls in reversed(det):
xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4))).view(-1).tolist()
xywh = [round(x) for x in xywh]
xywh = [xywh[0] - xywh[2] // 2, xywh[1] - xywh[3] // 2, xywh[2],
xywh[3]] # 檢測到目標(biāo)位置,格式:(left,top,w,h)
cls = names[int(cls)]
conf = float(conf)
detections.append({'class': cls, 'conf': conf, 'position': xywh})
#輸出結(jié)果
for i in detections:
print(i)
#推測的時間
LOGGER.info(f'({t3 - t2:.3f}s)')
return detections
path = 'C://Users//25096//Desktop//yoloV5//yolov5//yolov5-master//data//images//zidane.jpg'
img = cv2.imread(path)
#傳入一張圖片
detect(img)我這里用的是Yolov5自帶的zidane.jpg

這是輸出結(jié)果

class:標(biāo)簽的名稱
conf:置信度
position:xywh ( 左上角x,左上角y,寬,高 )
總結(jié)
到此這篇關(guān)于如何將Yolov5的detect.py修改為可以直接調(diào)用的函數(shù)的文章就介紹到這了,更多相關(guān)Yolov5的detect.py直接調(diào)用函數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python實現(xiàn)控制手機電腦拍照并自動發(fā)送郵箱
這篇文章主要介紹了如何實現(xiàn)利用Python控制手機電腦拍照并自動發(fā)送郵箱,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起動手試一試2022-02-02
詳解Python如何使用Self類型實現(xiàn)返回類的實例對象
在 Python 中,類方法通常會返回類的實例對象,本文將詳細(xì)介紹如何在 Python 中使用 Self 類型來返回類的實例對象,并提供豐富的示例代碼幫助更好地理解,快跟隨小編一起學(xué)習(xí)起來吧2024-02-02
Python3實現(xiàn)的判斷環(huán)形鏈表算法示例
這篇文章主要介紹了Python3實現(xiàn)的判斷環(huán)形鏈表算法,涉及Python針對環(huán)形鏈表的遍歷、判斷相關(guān)操作技巧,需要的朋友可以參考下2019-03-03
python實現(xiàn)dnspod自動更新dns解析的方法
這篇文章主要介紹了python實現(xiàn)的dnspod自動更新dns解析的方法,需要的朋友可以參考下2014-02-02
初學(xué)者學(xué)習(xí)Python好還是Java好
在本篇文章里小編給大家分享的是關(guān)于初學(xué)者學(xué)習(xí)Python好還是Java好的相關(guān)內(nèi)容,需要的朋友們可以學(xué)習(xí)下。2020-05-05

