yolov8训练检测部署(二)yolov8_cls python版Tensorrt推理加速


前言

TensorRT是由NVIDIA开发的一个深度学习推理(inference)引擎,它能够优化深度学习模型以实现高性能的推理。TensorRT可以接受来自多种深度学习框架(如TensorFlow, PyTorch, Caffe等)的模型,并通过一系列优化步骤来提高模型的推理速度,同时减少模型的内存占用。

一、tensort_python 安装

首先下载tensort
界面为:
在这里插入图片描述
根据自己所在的环境进行安装,我选择的第一个tar压缩包
在这里插入图片描述
下载好之后对压缩包进行解压解压完成之后的界面为:
在这里插入图片描述
执行下面代码即可完成tensorrt_python:

conda activate Yolov8
cd /home/build/下载/TensorRT-8.4.3.1.Linux.x86_64-gnu.cuda-11.6.cudnn8.4/TensorRT-8.4.3.1/python
pip install xxx.whl

二、yolov8_cls tensorrt推理

注:下面代码的库一般都放在yolov8目录下的models文件夹中,只要将推理代码放在项目文件中的根目录下即可进行推理

from models import TRTModule  # isort:skip
# 从models模块中导入TRTModule类

import argparse
# 导入argparse模块,用于解析命令行参数

from pathlib import Path
# 导入Path类,用于处理文件路径

import cv2
# 导入cv2模块,用于进行图像处理

import torch
# 导入torch模块,提供张量操作以及与TensorRT模块的交互

from models.utils import blob, path_to_list
# 从models.utils模块中导入blob函数和path_to_list函数,用于图像预处理和路径处理

def main(args: argparse.Namespace) -> None:
    # 定义主函数,接收一个argparse.Namespace对象作为参数,不返回任何值
    device = torch.device(args.device)
    # 根据命令行参数创建一个torch.device对象,用于指定TensorRT模块的运行设备

    Engine = TRTModule(args.engine, device)
    # 实例化TRTModule类,传入engine文件路径和设备信息

    H, W = Engine.inp_info[0].shape[-2:]
    # 从Engine对象的inp_info属性中获取输入图像的高度和宽度

    images = path_to_list(args.imgs)
    # 调用path_to_list函数,将命令行参数中的imgs路径转换为图像路径列表

    print(images)
    # 打印图像路径列表

    save_path = Path(args.out_dir)
    # 创建一个Path对象,表示输出目录的路径

    if not args.show and not save_path.exists():
        save_path.mkdir(parents=True, exist_ok=True)
    # 如果命令行参数中未设置显示结果且输出目录不存在,则创建输出目录

    for image in images:
        # 遍历图像路径列表
        save_image = save_path / image.name
        # 构建输出图像的完整路径

        bgr = cv2.imread(str(image))
        # 使用cv2.imread读取图像,得到BGR格式的图像

        draw = bgr.copy()
        # 复制BGR图像,用于后续绘制结果

        bgr = cv2.resize(bgr, (W, H))
        # 将图像缩放到与模型输入尺寸一致

        rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
        # 将BGR图像转换为RGB图像

        tensor = blob(rgb, return_seg=False)
        # 调用blob函数处理RGB图像,得到模型输入的张量

        tensor = torch.asarray(tensor, device=device)
        # 将张量移动到指定设备上

        # inference
        data = Engine(tensor)
        # 对图像进行推理,得到模型输出

        print(data)
        # 打印模型输出

        score, cls_id = data[0].max(0)
        # 获取最高分数和对应的类别ID

        score = float(score)
        # 将分数转换为浮点数

        cls_id = int(cls_id)
        # 将类别ID转换为整数

        print(cls_id)
        # 打印类别ID

        text = f'{cls_id}:{score:.3f}'
        # 构建要显示的文本

        (_w, _h), _bl = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, 0.8, 1)
        # 获取文本的尺寸和基线

        _y1 = min(10, draw.shape[0])
        # 计算文本框的y坐标

        cv2.rectangle(draw, (10, _y1), (10 + _w, _y1 + _h + _bl), (0, 0, 255), -1)
        # 在图像上绘制文本框

        cv2.putText(draw, text, (10, _y1 + _h), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (255, 255, 255), 2)
        # 在图像上绘制文本

        if args.show:
            cv2.imshow('result', draw)
            cv2.waitKey(0)
        else:
            cv2.imwrite(str(save_image), draw)
        # 根据命令行参数决定是显示图像还是保存图像

def parse_args() -> argparse.Namespace:
    # 定义解析命令行参数的函数,返回一个argparse.Namespace对象
    parser = argparse.ArgumentParser()
    # 创建一个ArgumentParser对象

    parser.add_argument('--engine', type=str, help='Engine file',default="/home/build/下载/ultralytics-main-2/smoke.engine")
    # 添加命令行参数engine,用于指定engine文件路径

    parser.add_argument('--imgs', type=str, help='Images file',default="/home/build/桌面/date/test")
    # 添加命令行参数imgs
### 回答1: 你好,以下是 YOLOv8 实时检测推理 Python 代码的示例: ``` import cv2 import numpy as np # Load YOLOv8 model net = cv2.dnn.readNet("yolov8.weights", "yolov8.cfg") # Load input image img = cv2.imread("input.jpg") # Resize image to input size of the model img = cv2.resize(img, (416, 416)) # Create a blob from the image blob = cv2.dnn.blobFromImage(img, 0.00392, (416, 416), (0, 0, 0), True, crop=False) # Feed the blob to the model net.setInput(blob) # Get the output layer names of the model layer_names = net.getLayerNames() layer_names = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()] # Perform forward pass to get detections detections = net.forward(layer_names) # Get the detections from the output detections = np.squeeze(detections) # Get the class IDs and confidences for each detection class_ids, confidences, boxes = [], [], [] for detection in detections: scores = detection[5:] class_id = np.argmax(scores) confidence = scores[class_id] if confidence > 0.5: center_x, center_y, w, h = (detection[0:4] * np.array([img.shape[1], img.shape[0], img.shape[1], img.shape[0]])).astype('int') x, y = int(center_x - w / 2), int(center_y - h / 2) boxes.append([x, y, int(w), int(h)]) confidences.append(float(confidence)) class_ids.append(class_id) # Perform non-maximum suppression to get the final detections indices = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4) # Draw the detections on the image for i in indices: i = i[0] box = boxes[i] x, y, w, h = box[0], box[1], box[2], box[3] cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) # Display the image cv2.imshow("detections", img) cv2.waitKey() cv2.destroyAllWindows() ``` 希望这对你有帮助。 ### 回答2: YOLOv8是一个实时目标检测算法,它是YOLO(You Only Look Once)系列的最新本。下面是一个示例的Python代码,用于进行YOLOv8实时检测推理: ```python import cv2 import torch from torchvision import transforms from yolov5.models.experimental import attempt_load from yolov5.utils.general import non_max_suppression, scale_coords from yolov5.utils.torch_utils import select_device # 加载模型 weights = 'yolov5s.pt' # 替换为YOLOv8的权重文件路径 device = select_device('') model = attempt_load(weights, map_location=device) stride = int(model.stride.max()) # 计算特征提取步长 # 准备图像 img_size = 640 # 设置输入图像的大小 transform = transforms.Compose([ transforms.ToPILImage(), transforms.Resize(img_size), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) # 设置阈值和类别 conf_thres = 0.3 # 检测置信度阈值 iou_thres = 0.5 # 非最大值抑制的IOU阈值 names = model.module.names if hasattr(model, 'module') else model.names # 开启实时摄像头 cap = cv2.VideoCapture(0) while cap.isOpened(): success, frame = cap.read() if not success: break # 图像预处理 img = transform(frame).unsqueeze(0).to(device) img /= 255.0 # 像素值归一化到[0, 1] if img.ndimension() == 3: img = img.unsqueeze(0) # 检测推理 pred = model(img)[0] pred = non_max_suppression(pred, conf_thres, iou_thres)[0] pred = scale_coords(img_size, pred[:, :4], frame.shape).round() # 绘制边界框和标签 for x1, y1, x2, y2, conf, cls in pred: cv2.rectangle(frame, (x1, y1), (x2, y2), (255, 0, 0), 2) cv2.putText(frame, f'{names[int(cls)]} {conf:.2f}', (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 0, 0), 2) # 展示结果 cv2.imshow('YOLOv8 - Real-time Object Detection', frame) if cv2.waitKey(1) == 27: break # 释放资源 cap.release() cv2.destroyAllWindows() ``` 这段代码使用了OpenCV和PyTorch,首先加载YOLOv8模型的权重文件,然后设置输入图像的大小和预处理方式。接下来,通过调用摄像头获取实时图像,并将其进行预处理。然后通过模型进行推理,获得目标检测结果。最后,将检测结果绘制在原始图像上,并实时展示在窗口中。用户可以按下ESC键停止检测。 注意,这段代码仅提供了一个基本的框架,可能需要根据具体情况进行适当的调整和优化。 ### 回答3: YOLOv8是一种实时目标检测算法,它在Python中有相应的推理代码YOLOv8推理代码可以用来将模型训练所得的权重文件加载到内存中,并使用这些权重来进行实时目标检测。 在Python中,我们首先需要安装相应的库和依赖项,如PyTorch、OpenCV等。安装完成后,我们可以编写推理代码推理代码的第一步是加载YOLOv8的模型权重文件。通过调用PyTorch提供的相关函数,我们可以将预训练好的权重文件加载到内存中。 接下来,我们需要定义模型的输入和输出。对于YOLOv8,输入是一张图像,输出是检测到的目标的边界框和类别信息。 在推理过程中,我们将输入图像传递给模型,模型将返回一组预测框。然后,我们可以根据预测框的置信度和类别信息进行筛选和筛除,以得到最终的检测结果。 为了实现实时检测,我们可以将推理过程放入一个循环中。在每一次循环中,我们读取一帧图像,并将其传递给模型进行检测。然后,我们可以将检测结果可视化或保存下来。 需要注意的是,YOLOv8推理代码需要在具备足够计算资源的机器上运行,因为它需要高性能的GPU来实现实时检测。 总之,YOLOv8的实时检测推理Python代码包括加载权重文件、定义输入输出、进行推理过程,以及在循环中实现实时检测。这些代码可以帮助我们实现基于YOLOv8的目标检测应用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值