openvino推理yolov5,onnx和IR和pytorch对比

本文使用openvino对onnx和IR进行推理并比较推理速度

环境要求和参考链接

环境安装好

onnx==1.9.0
onnxruntime==1.8.0
protobuf==3.19.4
openvino-dev==2022.1.0

参考

文件夹结构

giihub上下载YOLOv5的官方project,以及YOLOv5s.pt权重文件
使用export.py可导出onnx和IR文件
导出onnx文件命令

python export.py --weights yolov5s.pt --include onnx

导出IR文件命令

python export.py --weights yolov5s.pt --include openvino

得到onnx文件
在这里插入图片描述
得到IR文件夹
在这里插入图片描述

具体代码内容

在yolov5文件夹下新建py文件

1、导入需要的库
import cv2
import numpy as np
import torch
from PIL import Image
from openvino.runtime import Core
from utils.augmentations import letterbox
from utils.general import scale_coords, non_max_suppression
from draw_box_utils import draw_objs
import time
from models.experimental import attempt_load
2、一些路径
coco80_names = ['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']
weights = './yolov5s.pt'
onnx_path = './yolov5s.onnx'
img_path = "./data/street.jpg"
ir_path = './yolov5s_openvino_model/yolov5s.xml'
num_images = 20
3、图像预处理函数
# 图像预处理
def preprocess():
    img_size = (640, 640)  # h, w
    origin_img = cv2.cvtColor(cv2.imread(img_path), cv2.COLOR_BGR2RGB)
    reshape_img, ratio, pad = letterbox(origin_img/255, img_size, auto=False)
    processed_img = np.expand_dims(np.transpose(reshape_img, [2, 0, 1]), 0).astype(np.float32)
    return processed_img,reshape_img,origin_img,ratio,pad
4、预测结果后处理函数
# 后处理
def post_process(result,reshape_img,origin_img,ratio,pad,save_name):
    result = non_max_suppression(torch.Tensor(result))[0]
    boxes = result[:, :4].numpy() # 坐标
    scores = result[:, 4].numpy() # 置信度
    cls = result[:, 5].numpy().astype(int)
    boxes = scale_coords(reshape_img.shape, boxes, origin_img.shape, (ratio, pad))

    draw_img = draw_objs(Image.fromarray(origin_img),
                         boxes,
                         cls,
                         scores,
                         category_index=dict([(str(i), v) for i, v in enumerate(coco80_names)]))
    draw_img.save(save_name)
5、使用onnx进行推理
# onnx模型推理
def onnx_infer(input_img):
    ie = Core()
    compiled_model_onnx = ie.compile_model(model=onnx_path, device_name='CPU')
    output_layer_onnx = compiled_model_onnx.output(0)
    # Run inference on the input image
    res_onnx = compiled_model_onnx([input_img])[output_layer_onnx]
    return res_onnx,compiled_model_onnx
# onnx推理20张图所用时间
def onnx_20(input_img,compiled_model_onnx):
    start = time.perf_counter()
    for _ in range(num_images):
        compiled_model_onnx([input_img])
    end = time.perf_counter()
    time_onnx = end - start
    print(
        f"ONNX model in Inference Engine/CPU: {time_onnx / num_images:.3f} "
        f"seconds per image, FPS: {num_images / time_onnx:.2f}"
    )```
#### 6、使用IR进行推理

```python
# 用IR模型推理
def IR_infer(input_img):
    ie = Core()
    model_ir = ie.read_model(model=ir_path)
    compiled_model_ir = ie.compile_model(model=model_ir, device_name="CPU")
    # Get input and output layers
    output_layer_ir = compiled_model_ir.output(0)
    # Run inference on the input image
    res_ir = compiled_model_ir([input_img])[output_layer_ir]
    return res_ir,compiled_model_ir

# IR推理20张图所用时间
def IR_20(input_img,compiled_model_ir):
    start = time.perf_counter()
    for _ in range(num_images):
        compiled_model_ir([input_img])
    end = time.perf_counter()
    time_ir = end - start
    print(
        f"IR model in Inference Engine/CPU: {time_ir / num_images:.3f} "
        f"seconds per image, FPS: {num_images / time_ir:.2f}"
    )
7、使用pytorch模型推理时间
#使用pytorch模型推理
def pytorch_20(input_img):
    model = attempt_load(weights, device='cpu', inplace=True, fuse=True)
    with torch.no_grad():
        start = time.perf_counter()
        for _ in range(num_images):
            model(torch.as_tensor(input_img).float())
        end = time.perf_counter()
        time_torch = end - start
    print(
        f"PyTorch model on CPU: {time_torch / num_images:.3f} seconds per image, "
        f"FPS: {num_images / time_torch:.2f}"
    )
8、主函数
if __name__ == '__main__':
    input_img,reshape_img,origin_img,ratio,pad = preprocess()
    res_onnx, compiled_model_onnx = onnx_infer(input_img)
    res_ir,compiled_model_ir = IR_infer(input_img)
    onnx_20(input_img, compiled_model_onnx)
    IR_20(input_img,compiled_model_ir)
    pytorch_20(input_img)
    post_process(res_onnx,reshape_img,origin_img,ratio,pad,'predict_onnx.jpg')
    post_process(res_ir, reshape_img, origin_img, ratio, pad, 'predict_ir.jpg')

结果展示

onnx推理结果在这里插入图片描述
IR推理结果
在这里插入图片描述

三种推理速度结果

使用openvino进行推理还是明显快于pytorch cpu推理结果
在这里插入图片描述

  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
首先,您需要将Yolov5模型转换为ONNX格式。您可以使用PyTorch将模型转换为ONNX格式,然后使用ONNX Runtime C++ API加载和运行模型。 以下是一些步骤: 1. 安装PyTorchONNX Runtime 2. 使用PyTorchYolov5模型转换为ONNX格式。您可以使用以下代码: ``` import torch import torchvision # Load the model model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True) # Export the model to ONNX format input_shape = (1, 3, 640, 640) torch.onnx.export(model, torch.randn(*input_shape), "yolov5s.onnx", opset_version=11) ``` 3. 在C++中加载和运行模型。您可以使用以下代码: ``` #include <iostream> #include <vector> #include <chrono> #include <opencv2/opencv.hpp> #include "onnxruntime_cxx_api.h" using namespace std; using namespace cv; using namespace std::chrono; using namespace onnxruntime; int main() { // Load the model Ort::SessionOptions session_options; session_options.SetIntraOpNumThreads(1); session_options.SetGraphOptimizationLevel(GraphOptimizationLevel::ORT_ENABLE_ALL); Ort::Env env(ORT_LOGGING_LEVEL_WARNING, "test"); Ort::Session session(env, "yolov5s.onnx", session_options); // Get input and output names auto input_names = session.GetInputNames(); auto output_names = session.GetOutputNames(); // Create input tensor Ort::AllocatorWithDefaultOptions allocator; Ort::Value input_tensor(nullptr); Ort::MemoryInfo memory_info = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU); vector<int64_t> input_shape = {1, 3, 640, 640}; input_tensor = Ort::Value::CreateTensor<float>(memory_info, reinterpret_cast<float*>(new float[input_shape[0] * input_shape[1] * input_shape[2] * input_shape[3]]), input_shape.data(), input_shape.size()); // Load image Mat image = imread("test.jpg"); cvtColor(image, image, COLOR_BGR2RGB); resize(image, image, Size(640, 640)); float* input_data = input_tensor.GetTensorMutableData<float>(); for (int i = 0; i < 640 * 640 * 3; i++) { input_data[i] = image.data[i] / 255.0; } // Run inference auto start = high_resolution_clock::now(); vector<Ort::Value> output_tensors = session.Run(output_names, &input_names[0], &input_tensor, 1); auto end = high_resolution_clock::now(); auto duration = duration_cast<milliseconds>(end - start); cout << "Inference time: " << duration.count() << " ms" << endl; // Get output tensor Ort::Value& output_tensor = output_tensors[0]; float* output_data = output_tensor.GetTensorMutableData<float>(); // Process output for (int i = 0; i < 25200; i++) { if (output_data[i * 6 + 4] > 0.5) { int x1 = output_data[i * 6 + 0] * 640; int y1 = output_data[i * 6 + 1] * 640; int x2 = output_data[i * 6 + 2] * 640; int y2 = output_data[i * 6 + 3] * 640; cout << "Object detected: " << output_data[i * 6 + 5] << " (" << x1 << ", " << y1 << ") (" << x2 << ", " << y2 << ")" << endl; } } return 0; } ``` 这个例子假设您有一张名为“test.jpg”的图像,它将被用作模型的输入。它还假设您的模型输出是一个大小为[1, 25200, 6]的张量,其中25200是预测的边界框数,6是每个边界框的属性数(左上角和右下角坐标,置信度和类别)。 请注意,这只是一个简单的例子,您需要根据您的模型和数据进行适当的修改。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值