YOLOv10部署教程,使用tensorRT部署,有轉化和推理代碼

YOLOv10部署教程,使用tensorRT部署,有轉化和推理代碼

  • 一、使用平臺
    • 1. 轉化onnx模型
    • 轉化trt模型
  • 模型推理
  • 全部的代碼

論文題目:YOLOv10: Real-Time End-to-End Object Detection
研究單位:清華大學
論文鏈接:http://arxiv.org/abs/2405.14458
代碼鏈接:https://github.com/THU-MIG/yolov10

作者提供的模型性能評價圖,如下:
在這里插入圖片描述
YOLOv10-N:https://github.com/jameslahm/yolov10/releases/download/v1.0/yolov10n.pt
YOLOv10-S:https://github.com/jameslahm/yolov10/releases/download/v1.0/yolov10s.pt
YOLOv10-M:https://github.com/jameslahm/yolov10/releases/download/v1.0/yolov10m.pt
YOLOv10-B:https://github.com/jameslahm/yolov10/releases/download/v1.0/yolov10b.pt
YOLOv10-L:https://github.com/jameslahm/yolov10/releases/download/v1.0/yolov10l.pt
YOLOv10-X:https://github.com/jameslahm/yolov10/releases/download/v1.0/yolov10x.pt
推理時間速度很快,最主要是不需要后處理,就是網絡比較難訓練,有spa多占用了幾g顯存,并且收斂較慢

一、使用平臺

win10、TensorRT=8.6.1

1. 轉化onnx模型

git clone https://github.com/THU-MIG/yolov10.git
conda create -n YOLO python=3.9
conda activate YOLO
cd yolov10
pip install -r requirements.txt

下載pt模型
用下面代碼轉化

# -*- coding: utf-8 -*-
# @Time    : 2024/6/13 10:54
# @Site    : 
# @File    : export.py
# @Comment :
from ultralytics import YOLOv10# Load a model
model = YOLOv10(r"yolov10s.pt")  # load an official model# Export the model
model.export(format="onnx",device='0',batch=2,opset=12, half=True)"""
Argument	Type	Default	Description
format	str	'torchscript'	Target format for the exported model, such as 'onnx', 'torchscript', 'tensorflow', or others, defining compatibility with various deployment environments.
imgsz	int or tuple	640	Desired image size for the model input. Can be an integer for square images or a tuple (height, width) for specific dimensions.
keras	bool	False	Enables export to Keras format for TensorFlow SavedModel, providing compatibility with TensorFlow serving and APIs.
optimize	bool	False	Applies optimization for mobile devices when exporting to TorchScript, potentially reducing model size and improving performance.
half	bool	False	Enables FP16 (half-precision) quantization, reducing model size and potentially speeding up inference on supported hardware.
int8	bool	False	Activates INT8 quantization, further compressing the model and speeding up inference with minimal accuracy loss, primarily for edge devices.
dynamic	bool	False	Allows dynamic input sizes for ONNX and TensorRT exports, enhancing flexibility in handling varying image dimensions.
simplify	bool	False	Simplifies the model graph for ONNX exports with onnxslim, potentially improving performance and compatibility.
opset	int	None	Specifies the ONNX opset version for compatibility with different ONNX parsers and runtimes. If not set, uses the latest supported version.
workspace	float	4.0	Sets the maximum workspace size in GiB for TensorRT optimizations, balancing memory usage and performance.
nms	bool	False	Adds Non-Maximum Suppression (NMS) to the CoreML export, essential for accurate and efficient detection post-processing.
batch	int	1	Specifies export model batch inference size or the max number of images the exported model will process concurrently in predict mode.
"""

轉化trt模型

import onnx
import tensorrt as trt
# import sys
# sys.setrecursionlimit(500000)def onnx_export_engine(workspace,onnx_path,trt_path):#創建構建器logger=trt.Logger(trt.Logger.WARNING)builder=trt.Builder(logger)#創建一個構建配置config=builder.create_builder_config()config.max_workspace_size=workspace*1<<30#創建網絡定義flag=(1<<int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH))network=builder.create_network(flag)#導入onnx模型parser=trt.OnnxParser(network,logger)if not parser.parse_from_file(str(onnx_path)):raise RuntimeError(f'failed to load ONNX file: {onnx}')inputs=[network.get_input(i) for i in range(network.num_inputs)]outputs=[network.get_output(i) for i in  range(network.num_outputs)]# network.get_input(0).setAllowedFormats(int)# network.get_input(1).setAllowedFormats(int)# for inp in inputs:#     LOGGER.info(f'{prefix}\tinput "{inp.name}" with shape {inp.shape} and dtype {inp.dtype}')# for out in outputs:#     LOGGER.info(f'{prefix}\toutput "{out.name}" with shape {out.shape} and dtype {out.dtype}')## LOGGER.info(f'{prefix} building FP{16 if builder.platform_has_fast_fp16 else 32} engine in {f}')# if builder.platform_has_fast_fp16:##     config.set_flag(trt.BuilderFlag.FP16)# config.set_flag(trt.BuilderFlag.FP16)engine_path=trt_pathwith builder.build_serialized_network(network,config) as engine:with open(engine_path,'wb') as t:# t.write(engine.serialize())t.write(engine)print('轉化完成')if __name__ == '__main__':onnx_path='weights2/best.onnx'trt_path='end2end.engine'onnx_export_engine(4,onnx_path,trt_path)

模型推理

  • 定義變量
from models import TRTModule  # isort:skip
import argparse
import cv2
from numpy import ndarray
import time
import random
import numpy as np
import os
import pickle
from collections import defaultdict, namedtuple
from pathlib import Path
from typing import List, Optional, Tuple, Union
import onnx
import tensorrt as trt
import torchos.environ['CUDA_MODULE_LOADING'] = 'LAZY'
random.seed(0)# detection model classes
CLASSES = ('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')
# # three:
# CLASSES = (
#     'person', 'sports ball', 'car'
# )# colors for per classes
COLORS = {cls: [random.randint(0, 255) for _ in range(3)]for i, cls in enumerate(CLASSES)
}
# image suffixs
SUFFIXS = ('.bmp', '.dng', '.jpeg', '.jpg', '.mpo', '.png', '.tif', '.tiff','.webp', '.pfm')
  • 定義模型加載類
class TRTModule(torch.nn.Module):dtypeMapping = {trt.bool: torch.bool,trt.int8: torch.int8,trt.int32: torch.int32,trt.float16: torch.float16,trt.float32: torch.float32}def __init__(self, weight: Union[str, Path],device: Optional[torch.device]) -> None:super(TRTModule, self).__init__()self.weight = Path(weight) if isinstance(weight, str) else weightself.device = device if device is not None else torch.device('cuda:0')self.stream = torch.cuda.Stream(device=device)self.__init_engine()self.__init_bindings()def __init_engine(self) -> None:logger = trt.Logger(trt.Logger.WARNING)trt.init_libnvinfer_plugins(logger, namespace='')with trt.Runtime(logger) as runtime:model = runtime.deserialize_cuda_engine(self.weight.read_bytes())context = model.create_execution_context()num_bindings = model.num_bindingsnames = [model.get_binding_name(i) for i in range(num_bindings)]self.bindings: List[int] = [0] * num_bindingsnum_inputs, num_outputs = 0, 0for i in range(num_bindings):if model.binding_is_input(i):num_inputs += 1else:num_outputs += 1self.num_bindings = num_bindingsself.num_inputs = num_inputsself.num_outputs = num_outputsself.model = modelself.context = contextself.input_names = names[:num_inputs]self.output_names = names[num_inputs:]self.idx = list(range(self.num_outputs))def __init_bindings(self) -> None:idynamic = odynamic = FalseTensor = namedtuple('Tensor', ('name', 'dtype', 'shape'))inp_info = []out_info = []for i, name in enumerate(self.input_names):assert self.model.get_binding_name(i) == namedtype = self.dtypeMapping[self.model.get_binding_dtype(i)]shape = tuple(self.model.get_binding_shape(i))if -1 in shape:idynamic |= Trueinp_info.append(Tensor(name, dtype, shape))for i, name in enumerate(self.output_names):i += self.num_inputsassert self.model.get_binding_name(i) == namedtype = self.dtypeMapping[self.model.get_binding_dtype(i)]shape = tuple(self.model.get_binding_shape(i))if -1 in shape:odynamic |= Trueout_info.append(Tensor(name, dtype, shape))if not odynamic:self.output_tensor = [torch.empty(info.shape, dtype=info.dtype, device=self.device)for info in out_info]self.idynamic = idynamicself.odynamic = odynamicself.inp_info = inp_infoself.out_info 

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/43723.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/43723.shtml
英文地址,請注明出處:http://en.pswp.cn/web/43723.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

每天一個數據分析題(四百二十三)- 置信區間

在給定的顯著性水平下&#xff0c;某一特定的X水平上&#xff0c;總體Y分布的離散度越大&#xff0c;即σ^2越大&#xff0c;則 A. 預測區間越寬&#xff0c;精度越低 B. 預測區間越寬&#xff0c;預測誤差越小 C. 預測區間越窄&#xff0c;精度越高 D. 預測區間越窄&#…

如何在idea安裝git,使用gitee?

一、什么是git&#xff0c;git與gitee、GitHub的關系&#xff1f; 1.什么是git&#xff1f; Git 是一個開源的分布式版本控制系統&#xff0c;用于企業項目中程序員協同開發。 2.git與gitee、GitHub的關系是什么&#xff1f; git &#xff1a;Git是一種版本控制系統&#x…

看完這篇,你的服務設計能力將再次進化!

引言 在當今快速演變的技術場景中&#xff0c;服務設計不僅僅是遵循通用的設計規范和最佳實踐的問題&#xff0c;它更深層次地觸及到如何在滿足這些標準的同時&#xff0c;確保服務能夠靈活適應未來的變化、滿足用戶的期望。本篇文章旨在探討在遵循通用設計規范之外&#xff0…

Three.js相機簡明教程

相機校準是 3D 計算機圖形學中的一個基本概念&#xff0c;涉及設置虛擬相機以模擬真實世界相機的視角和行為。在 Three.js&#xff08;一種流行的 3D 渲染 JavaScript 庫&#xff09;中&#xff0c;了解相機校準對于創建逼真且身臨其境的 3D 場景至關重要。在本文中&#xff0c…

UML類圖的建立過程

1. 概念層類圖 概念層的類圖描述的是現實世界中對問題領域的概念理解&#xff0c;類圖中表達的類與現實世界的問題領域中的實際事物有著明顯的對應關系&#xff0c;類之間的關系也與問題領域中實際事物之間的關系有著明顯的對應關系。在概念層類圖階段很少考慮或者幾乎不需要考…

07-7.5.1 散列表的基本概念

&#x1f44b; Hi, I’m Beast Cheng &#x1f440; I’m interested in photography, hiking, landscape… &#x1f331; I’m currently learning python, javascript, kotlin… &#x1f4eb; How to reach me --> 458290771qq.com 喜歡《數據結構》部分筆記的小伙伴可以…

指令v-el的作用是什么

在Vue.js的早期版本中&#xff08;特別是Vue 1.x版本&#xff09;&#xff0c;v-el 指令被用來給元素注冊引用信息&#xff08;即DOM元素的引用&#xff09;。這樣&#xff0c;開發者就可以在Vue實例的方法中直接訪問到這個DOM元素。然而&#xff0c;需要注意的是&#xff0c;從…

28.IP核理論知識(Xilinx)

&#xff08;1&#xff09;ip核是什么&#xff1f; IP&#xff08;Intellectual Property&#xff09;即知識產權&#xff0c;在半導體產業中&#xff0c;將IP核定義為“用于ASIC或FPGA中的預先設計好的電路功能模塊”&#xff0c;簡而言之&#xff0c;這里的IP即電路功能模塊。…

Element輪播圖組件切換太單調?手把手帶你重寫切換效果

前言&#xff1a; 最近在逛山東博物館網站的時候&#xff0c;發現該網站主頁淡入淡出的輪播圖非常的優雅&#xff0c;所以就想來復刻一下&#xff0c;也算是對組件進行了二次的封裝和修改 工具準備&#xff1a; Vue3Element Plus走馬燈組件 注意事項&#xff1a; Element …

GPX文件的元素內容詳解

GPX文件的來源 GPX文件&#xff08;GPS eXchange Format&#xff09;是一種用于存儲GPS數據的開放標準格式&#xff0c;它可以包含航路點、軌跡和路線等信息。這些文件通常來源于GPS設備、戶外活動追蹤應用程序、地圖服務或用戶之間的數據共享。用戶可以通過各種軟件和硬件設備…

Python爬蟲:基礎爬蟲架構及爬取證券之星全站行情數據!

爬蟲成長之路&#xff08;一&#xff09;里我們介紹了如何爬取證券之星網站上所有A股數據&#xff0c;主要涉及網頁獲取和頁面解析的知識。爬蟲成長之路&#xff08;二&#xff09;里我們介紹了如何獲取代理IP并驗證&#xff0c;涉及了多線程編程和數據存儲的知識。此次我們將在…

網絡編程學習之tcp

按下*&#xff08;星號&#xff09;可以搜索當前光標下的單詞。 Tcp編程的過程 打開網絡設備 Bind&#xff1a;給服務地址把ip號和端口號連接進去 Tcp是有狀態的 Listen是進入監聽狀態&#xff0c;看有沒有客戶端來連接服務器 Tcp比udp消耗過多資源 Upd類似于半雙工&#…

D50SB100-ASEMI逆變焊機專用D50SB100

編輯&#xff1a;ll D50SB100-ASEMI逆變焊機專用D50SB100 型號&#xff1a;D50SB100 品牌&#xff1a;ASEMI 封裝&#xff1a;DSB-5 批號&#xff1a;2024 現貨&#xff1a;50000 正向電流&#xff08;Id&#xff09;&#xff1a;50A 反向耐壓&#xff08;VRRM&#xf…

編程語言沒落了?揭開真相的四大謎團、五大趨勢、六大挑戰與七大未來

編程語言沒落了&#xff1f;揭開真相的四大謎團、五大趨勢、六大挑戰與七大未來 在科技飛速發展的今天&#xff0c;有人宣稱編程語言已經沒落&#xff0c;這一觀點似乎讓人困惑不已。然而&#xff0c;真相究竟如何&#xff1f;本文將從四個方面揭示編程語言的現狀&#xff0c;…

【AIGC】二、mac本地采用GPU啟動keras運算

mac本地采用GPU啟動keras運算 一、問題背景二、技術背景三、實驗驗證本機配置安裝PlaidML安裝plaidml-keras配置默認顯卡 運行采用 CPU運算的代碼step1 先導入keras包&#xff0c;導入數據cifar10&#xff0c;這里可能涉及外網下載&#xff0c;有問題可以參考[keras使用基礎問題…

echarts中tooltip添加點擊事件代碼示例

echarts中tooltip添加點擊事件代碼示例_javascript技巧_腳本之家 點擊事件無法使用this 或者 this無法使用&#xff1a;

Qt圖形編輯類使用總結

Qt的圖形編輯通常會涉及以下三個類:QGraphicsView類、QGraphicsScene類及QGraphicsItem類。 QGraphicsView 是構建復雜圖形用戶界面的強大工具,尤其適用于那些需要動態更新、可交互的2D圖形化應用程序,如圖表繪制、流程圖編輯器、游戲地圖顯示等等。通過結合使用 QGraphics…

13--memcache與redis

前言&#xff1a;數據庫讀取速度較慢一直是無法解決的問題&#xff0c;大型網站應對的方式主要是使用緩存服務器來緩解這種情況&#xff0c;減少數據庫訪問次數&#xff0c;以提高動態Web等應用的速度、提高可擴展性。 1、簡介 Memcached/redis是高性能的分布式內存緩存服務器…

ret2csu簡單總結

一個比較進階的rop利用方式。 Why ret to csu&#xff1f; 當程序給的gadget不夠&#xff0c;或者輸入長度受限時&#xff0c;可以考慮利用csu中的眾多gadget以及一個call指令來劫持控制流。 __libc_csu_init 匯編源碼: .text:0000000000400790 ; void __fastcall _libc_c…

無人直播賺錢的底層邏輯是什么?一文揭曉!

當前&#xff0c;網絡直播已經成為各類商家提高曝光和引流獲客的主要渠道之一&#xff0c;這在為商家帶來新機遇的同時&#xff0c;也讓他們因人手不足或資金匱乏等原因而陷入無人問津窘境之中。在此背景下&#xff0c;無人直播軟件一經出現&#xff0c;便引起了眾多商家的關注…