Python API使用TensorRT模型进行推理

本文介绍了如何在Python中加载和使用NVIDIATensorRT引擎进行图像识别模型的高效推理,包括读取引擎文件、设置输入形状、数据传输以及执行和获取输出的过程。
摘要由CSDN通过智能技术生成
import cv2
import numpy as np
import tensorrt as trt
import pycuda.driver as cuda
import torch
from typing import Union, Optional, Sequence,Dict,Any
import torchvision.transforms as transforms
from PIL import Image



def load_engine(self, engine_file_path):
    TRT_LOGGER = trt.Logger()
    assert os.path.exists(engine_file_path)
    print("Reading engine from file {}".format(engine_file_path))
    with open(engine_file_path, "rb") as f, trt.Runtime(TRT_LOGGER) as runtime:
        return runtime.deserialize_cuda_engine(f.read())
    

def engine_infer(self, engine, input_image):
    """
    engine: load_engine函数返回的trt模型引擎
    input_image: 模型推理输入图像,尺寸为(batch_size, channel, height, width)
    output:Unet模型推理的结果,尺寸为(batch_size, class_num, height, width)
    """
    batch_size = input_image.shape[0]
    image_channel = input_image.shape[1]
    image_height = input_image.shape[2]
    image_width = input_image.shape[3]

    with engine.create_execution_context() as context:
        # Set input shape based on image dimensions for inference
        context.set_binding_shape(engine.get_binding_index("input"), (batch_size, image_channel, image_height, image_width))

        # Allocate host and device buffers
        bindings = []
        for binding in engine:
            binding_idx = engine.get_binding_index(binding)
            size = trt.volume(context.get_binding_shape(binding_idx))
            dtype = trt.nptype(engine.get_binding_dtype(binding))
            if engine.binding_is_input(binding):
                input_buffer = np.ascontiguousarray(input_image)
                input_memory = cuda.mem_alloc(input_image.nbytes)
                bindings.append(int(input_memory))
            else:
                output_buffer = cuda.pagelocked_empty(size, dtype)
                output_memory = cuda.mem_alloc(output_buffer.nbytes)
                bindings.append(int(output_memory))

        stream = cuda.Stream()
        # Transfer input data to the GPU.
        cuda.memcpy_htod_async(input_memory, input_buffer, stream)
        # Run inference
        context.execute_async_v2(bindings=bindings, stream_handle=stream.handle)
        # Transfer prediction output from the GPU.
        cuda.memcpy_dtoh_async(output_buffer, output_memory, stream)
        # Synchronize the stream
        stream.synchronize()

    output = np.reshape(output_buffer, (batch_size, self.num_classes, image_height, image_width))
    return output

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在 Python推理 TensorRT 模型,您需要使用 TensorRT Python APITensorRT Python API 是一个 Python 包,它提供了一组用于加载、优化和推理 TensorRT 模型的函数和类。 下面是一些步骤,帮助您在 Python推理 TensorRT 模型: 1. 安装 TensorRT Python API:您需要从 NVIDIA 的官方网站下载和安装 TensorRT Python API。请确保您的系统满足 TensorRT Python API 的要求。 2. 加载和优化 TensorRT 模型使用 TensorRT Python API 的函数和类来加载和优化 TensorRT 模型。您可以使用 TensorRT Python API 的 Builder 类来构建和优化 TensorRT 引擎。 3. 推理 TensorRT 模型使用 TensorRT Python API 的函数和类来推理 TensorRT 模型。您可以使用 TensorRT Python API 的 Engine 类来执行推理操作。 4. 处理输出:您可以使用 Python 来处理 TensorRT 模型的输出。您可以将 TensorRT 模型的输出转换为 NumPy 数组,并使用 NumPy 函数对其进行处理。 下面是一个简单的示例,展示如何在 Python推理 TensorRT 模型: ```python import tensorrt as trt import numpy as np # 加载 TensorRT 模型 TRT_LOGGER = trt.Logger(trt.Logger.WARNING) with open("model.trt", "rb") as f: engine = trt.Runtime(TRT_LOGGER).deserialize_cuda_engine(f.read()) # 创建 TensorRT 推理上下文 context = engine.create_execution_context() # 准备输入数据 input_data = np.random.normal(size=(1, 3, 224, 224)).astype(np.float32) # 执行推理操作 bindings = [None] * engine.num_bindings inputs_idx = [engine.get_binding_index(name) for name in input_names] outputs_idx = [engine.get_binding_index(name) for name in output_names] bindings[inputs_idx[0]] = input_data output_data = np.empty(shape=engine.get_binding_shape(outputs_idx[0]), dtype=np.float32) bindings[outputs_idx[0]] = output_data context.execute_v2(bindings) # 处理输出数据 output_data = output_data.reshape(1, -1) output_data = np.argmax(output_data, axis=1) print(output_data) ``` 在这个示例中,我们首先加载了一个 TensorRT 模型,并创建了一个 TensorRT 推理上下文。然后,我们准备了输入数据,并使用 TensorRT 推理上下文执行了推理操作。最后,我们将输出数据转换为 NumPy 数组,并使用 NumPy 函数对其进行处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值