YOLOv8-Openvino和ONNXRuntime推理【CPU】

这篇具有很好参考价值的文章主要介绍了YOLOv8-Openvino和ONNXRuntime推理【CPU】。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

1 环境:

CPU:i5-12500

2 安装Openvino和ONNXRuntime

2.1 Openvino简介

Openvino是由Intel开发的专门用于优化和部署人工智能推理的半开源的工具包,主要用于对深度推理做优化。

Openvino内部集成了Opencv、TensorFlow模块,除此之外它还具有强大的Plugin开发框架,允许开发者在Openvino之上对推理过程做优化。

Openvino整体框架为:Openvino前端→ Plugin中间层→ Backend后端
Openvino的优点在于它屏蔽了后端接口,提供了统一操作的前端API,开发者可以无需关心后端的实现,例如后端可以是TensorFlow、Keras、ARM-NN,通过Plugin提供给前端接口调用,也就意味着一套代码在Openvino之上可以运行在多个推理引擎之上,Openvino像是类似聚合一样的开发包。

2.2 ONNXRuntime简介

ONNXRuntime是微软推出的一款推理框架,用户可以非常便利的用其运行一个onnx模型。ONNXRuntime支持多种运行后端包括CPU,GPU,TensorRT,DML等。可以说ONNXRuntime是对ONNX模型最原生的支持。

虽然大家用ONNX时更多的是作为一个中间表示,从pytorch转到onnx后直接喂到TensorRT或MNN等各种后端框架,但这并不能否认ONNXRuntime是一款非常优秀的推理框架。而且由于其自身只包含推理功能(最新的ONNXRuntime甚至已经可以训练),通过阅读其源码可以解深度学习框架的一些核心功能原理(op注册,内存管理,运行逻辑等)
总体来看,整个ONNXRuntime的运行可以分为三个阶段,Session构造,模型加载与初始化和运行。和其他所有主流框架相同,ONNXRuntime最常用的语言是python,而实际负责执行框架运行的则是C++。

2.3 安装

pip install openvino -i  https://pypi.tuna.tsinghua.edu.cn/simple
pip install onnxruntime -i  https://pypi.tuna.tsinghua.edu.cn/simple

3 准备YOLOv8s.onnx文件

YOLOv8官网
.pt文件转.onnx文件示例代码【注意自己转需要安装YOLOv8的环境】:

from ultralytics import YOLO
model = YOLO("yolov8s.pt")  # load a pretrained model
path = model.export(format="onnx", dynamic=True)  # export the mode l to ONNX format

4 Openvino和ONNXRuntime推理脚本

4.1 预处理

注:其中pad部分去除能减少预处理时间,且推理精度几乎一致。

def preprocess(image, img_h, img_w):
    '''
    Yolo系列算法通用预处理
    '''
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    scale = max(image.shape[0] / img_h, image.shape[1] / img_w)
    image = cv2.resize(image, (int(image.shape[1] / scale), int(image.shape[0] / scale)))
   
    wpad = img_w - image.shape[1]
    hpad = img_h - image.shape[0]
    image_pad = np.ones((image.shape[0]+hpad, image.shape[1]+wpad, 3)) * 114.0
    image_pad[:image.shape[0], :image.shape[1], :] = image
    image_array = image_pad
    
    image_array = image_array / 255.0
    image_array = image_array.transpose((2, 0, 1))
    image_array = image_array.astype(np.float32)
    input_array = np.ascontiguousarray(np.expand_dims(image_array, 0))
    return input_array, scale, image.shape[0], image.shape[1]

4.2 后处理

注:尝试多种后处理写法,该种写法速度最快。

def postprocess(pred, conf_thres, iou_thres, img_w, img_h):
    """
    Args:
        pred: np.array([(x, y, w, h, cls1_conf, cls2_conf, cls3_conf, ...), ...]), shape=(-1, 4 + num_cls)
        conf_thres: 置信度阈值
        iou_thres: IOU阀值,若两个box的交并比大于该值,则置信度较小的box将会被抑制
        img_w: 原图w大小
        img_h: 原图h大小
        Returns:
        out: 经过NMS后的值,np.array([(x, y, w, h, conf, cls), ...]), shape=(-1, 4 + 1 + 1)
    """
    pred = np.squeeze(pred).transpose((1, 0))  # (1, 80+4, -1) -> (80+4, -1) -> (-1, 80+4)
    # 按置信度过滤
    conf = np.max(pred[..., 4:], axis=-1)
    mask = conf >= conf_thres

    # Where the score larger than score_threshold
    box = pred[mask][..., :4]
    confidences = conf[mask]
  	clsid = np.argmax(pred[mask][..., 4:], axis=1)  
    
    # 下面进行非极大抑制NMS处理
    # 对box进行转换,以及对不同类别分不同区间处理
    bounding_boxes = np.zeros_like(box)
    bounding_boxes[:, 0] = (box[:, 0] - box[:, 2] / 2) + clsid * img_w  # xmin + 每个类别分不同区间
    bounding_boxes[:, 1] = (box[:, 1] - box[:, 3] / 2) + clsid * img_h  # ymin + 每个类别分不同区间
    bounding_boxes[:, 2] = box[:, 2]  # w
    bounding_boxes[:, 3] = box[:, 3]  # h
    # xywh2xyxy
    bounding_boxes[:, 2] += bounding_boxes[:, 0]
    bounding_boxes[:, 3] += bounding_boxes[:, 1]
    if bounding_boxes.shape[0] != confidences.shape[0]:
        raise ValueError("Bounding box 与 Confidence 的数量不一致")
    if bounding_boxes.shape[0] == 0:
        return []
    bounding_boxes, confidences = bounding_boxes.astype(np.float32), np.array(confidences)
    x1, y1, x2, y2 = bounding_boxes[:, 0], bounding_boxes[:, 1], bounding_boxes[:, 2], bounding_boxes[:, 3]
    areas = (x2 - x1 + 1) * (y2 - y1 + 1)
    idxs = np.argsort(confidences)

    pick = []
   	while len(idxs) > 0:
        # 因为idxs是从小到大排列的,last_idx相当于idxs最后一个位置的索引
        last_idx = len(idxs) - 1
        # 取出最大值在数组上的索引
        max_value_idx = idxs[last_idx]
        # 将这个添加到相应索引上
      	pick.append(max_value_idx)

        xx1 = np.maximum(x1[max_value_idx], x1[idxs[: last_idx]])
        yy1 = np.maximum(y1[max_value_idx], y1[idxs[: last_idx]])
        xx2 = np.minimum(x2[max_value_idx], x2[idxs[: last_idx]])
        yy2 = np.minimum(y2[max_value_idx], y2[idxs[: last_idx]])
        w, h = np.maximum(0, xx2 - xx1 + 1), np.maximum(0, yy2 - yy1 + 1)
        iou = w * h / areas[idxs[: last_idx]]

        # 删除最大的value,并且删除iou > threshold的bounding boxes
        idxs = np.delete(idxs, np.concatenate(([last_idx], np.where(iou > iou_thres)[0])))
    out = np.concatenate([box[pick], confidences[pick].reshape(-1, 1), clsid[pick].reshape(-1, 1)], axis=1)
    return out

4.3 全部代码

import os
import time

# openvino速度比onnxruntime快一倍
from openvino.runtime import Core  # pip install openvino -i  https://pypi.tuna.tsinghua.edu.cn/simple
import onnxruntime as rt  # 使用onnxruntime推理用上,pip install onnxruntime
import numpy as np
import cv2

def preprocess(image, img_h, img_w):
    '''
    Yolo系列算法通用预处理
    '''
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    scale = max(image.shape[0] / img_h, image.shape[1] / img_w)
    image = cv2.resize(image, (int(image.shape[1] / scale), int(image.shape[0] / scale)))
   
    wpad = img_w - image.shape[1]
    hpad = img_h - image.shape[0]
    image_pad = np.ones((image.shape[0]+hpad, image.shape[1]+wpad, 3)) * 114.0
    image_pad[:image.shape[0], :image.shape[1], :] = image
    image_array = image_pad
    
    image_array = image_array / 255.0
    image_array = image_array.transpose((2, 0, 1))
    image_array = image_array.astype(np.float32)
    input_array = np.ascontiguousarray(np.expand_dims(image_array, 0))
    return input_array, scale, image.shape[0], image.shape[1]

def postprocess(pred, conf_thres, iou_thres, img_w, img_h):
    """
    Args:
        pred: np.array([(x, y, w, h, cls1_conf, cls2_conf, cls3_conf, ...), ...]), shape=(-1, 4 + num_cls)
        conf_thres: 置信度阈值
        iou_thres: IOU阀值,若两个box的交并比大于该值,则置信度较小的box将会被抑制
        img_w: 原图w大小
        img_h: 原图h大小
        Returns:
        out: 经过NMS后的值,np.array([(x, y, w, h, conf, cls), ...]), shape=(-1, 4 + 1 + 1)
    """
    pred = np.squeeze(pred).transpose((1, 0))  # (1, 80+4, -1) -> (80+4, -1) -> (-1, 80+4)
    # 按置信度过滤
    conf = np.max(pred[..., 4:], axis=-1)
    mask = conf >= conf_thres

    # Where the score larger than score_threshold
    box = pred[mask][..., :4]
    confidences = conf[mask]
  	clsid = np.argmax(pred[mask][..., 4:], axis=1)  
    
    # 下面进行非极大抑制NMS处理
    # 对box进行转换,以及对不同类别分不同区间处理
    bounding_boxes = np.zeros_like(box)
    bounding_boxes[:, 0] = (box[:, 0] - box[:, 2] / 2) + clsid * img_w  # xmin + 每个类别分不同区间
    bounding_boxes[:, 1] = (box[:, 1] - box[:, 3] / 2) + clsid * img_h  # ymin + 每个类别分不同区间
    bounding_boxes[:, 2] = box[:, 2]  # w
    bounding_boxes[:, 3] = box[:, 3]  # h
    # xywh2xyxy
    bounding_boxes[:, 2] += bounding_boxes[:, 0]
    bounding_boxes[:, 3] += bounding_boxes[:, 1]
    if bounding_boxes.shape[0] != confidences.shape[0]:
        raise ValueError("Bounding box 与 Confidence 的数量不一致")
    if bounding_boxes.shape[0] == 0:
        return []
    bounding_boxes, confidences = bounding_boxes.astype(np.float32), np.array(confidences)
    x1, y1, x2, y2 = bounding_boxes[:, 0], bounding_boxes[:, 1], bounding_boxes[:, 2], bounding_boxes[:, 3]
    areas = (x2 - x1 + 1) * (y2 - y1 + 1)
    idxs = np.argsort(confidences)

    pick = []
   	while len(idxs) > 0:
        # 因为idxs是从小到大排列的,last_idx相当于idxs最后一个位置的索引
        last_idx = len(idxs) - 1
        # 取出最大值在数组上的索引
        max_value_idx = idxs[last_idx]
        # 将这个添加到相应索引上
      	pick.append(max_value_idx)

        xx1 = np.maximum(x1[max_value_idx], x1[idxs[: last_idx]])
        yy1 = np.maximum(y1[max_value_idx], y1[idxs[: last_idx]])
        xx2 = np.minimum(x2[max_value_idx], x2[idxs[: last_idx]])
        yy2 = np.minimum(y2[max_value_idx], y2[idxs[: last_idx]])
        w, h = np.maximum(0, xx2 - xx1 + 1), np.maximum(0, yy2 - yy1 + 1)
        iou = w * h / areas[idxs[: last_idx]]

        # 删除最大的value,并且删除iou > threshold的bounding boxes
        idxs = np.delete(idxs, np.concatenate(([last_idx], np.where(iou > iou_thres)[0])))
    out = np.concatenate([box[pick], confidences[pick].reshape(-1, 1), clsid[pick].reshape(-1, 1)], axis=1)
    return out

def draw(img, xscale, yscale, pred, color=(255, 0, 0), tmp=True):
    img_ = img.copy()
    if len(pred):
        for detect in pred:
            caption = str('{:.2f}_{}'.format(detect[4], int(detect[5])))
            detect = [int((detect[0] - detect[2] / 2) * xscale), int((detect[1] - detect[3] / 2) * yscale),
                      int((detect[0] + detect[2] / 2) * xscale), int((detect[1] + detect[3] / 2) * yscale)]
            img_ = cv2.rectangle(img, (detect[0], detect[1]), (detect[2], detect[3]), color, 2)

            # 是否显示置信度类别
            if tmp:
                cv2.putText(img, caption, (detect[0], detect[1] - 5), 0, 1, color, 2, 16)
            
    return img_

class OpenvinoInference(object):
    def __init__(self, onnx_path):
        self.onnx_path = onnx_path
        ie = Core()
        self.model_onnx = ie.read_model(model=self.onnx_path)
        self.compiled_model_onnx = ie.compile_model(model=self.model_onnx, device_name="CPU")
        self.output_layer_onnx = self.compiled_model_onnx.output(0)

    def predirts(self, datas):
        predict_data = self.compiled_model_onnx([datas])[self.output_layer_onnx]
        return predict_data

if __name__ == '__main__':
    
    height, width = 640, 640  # 修改1:图像resize大小
    conf, nms_iou = 0.15, 0.6  # 修改2:置信度阈值与nms的iou阈值
    openvino_tmp = True  # 修改3:是否进行openvino推理,False为onnxruntime推理

    onnx_path = 'D:\\C++\\yolov8s.onnx'  # 修改4:onnx文件路径
    input_path = 'D:\\C++\\bus.jpg'  # 修改5:原图路径
    output_path = 'D:\\C++\\out.jpg'  # 修改6:图像保存路径

    img = cv2.imread(input_path)
    
    if openvino_tmp:
        model = OpenvinoInference(onnx_path)
    else:
    	sess = rt.InferenceSession(onnx_path)

    t1 = time.time()
    data, scale, img_w, img_h = preprocess(img, height, width)  # resize_img
    print('预处理时间:{:.3f}s'.format(time.time() - t1))

	t2 = time.time()
    if openvino_tmp:
        pred = model.predirts(data)
    else:
        input_name = sess.get_inputs()[0].name
        label_name = sess.get_outputs()[0].name
        pred = sess.run([label_name], {input_name: data.astype(np.float32)})[0]
    print('推理时间:{:.3f}s'.format(time.time() - t2))

	t3 = time.time()
    result = postprocess(pred, conf, nms_iou, img_w, img_h)
    print('后处理时间:{:.3f}s'.format(time.time() - t3))

    ret_img = draw(img, scale, scale, result, color=(0, 255, 0), tmp=True)
    cv2.imwrite(output_path, ret_img)      

5 结果

YOLOv8-Openvino和ONNXRuntime推理【CPU】,YOLO,openvino,人工智能,yolov8,目标检测

具体时间消耗:

预处理时间:0.014s(预处理无Pad为0.007s)
推理时间:0.08s
后处理时间:0.001s
注:640×640下,Openvino和ONNXRuntime推理速度相差不大,1280×1280下,Openvino速度更快。文章来源地址https://www.toymoban.com/news/detail-831040.html

到了这里,关于YOLOv8-Openvino和ONNXRuntime推理【CPU】的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包赞助服务器费用

相关文章

  • onnxruntime推理时切换CPU/GPU以及修改onnx输入输出为动态

    前言 onnx模型作为中间模型,相较于pytorch直接推理,是有加速度效果的,且推理代码简单,不需要load各种网络。最近某些项目因为显存不够,onnxruntime推理时切换CPU/GPU,实现某些模型在CPU上推理,某些在GPU上推理。 查了一些别人的文章发现很多人都说onnxruntime推理没法像py

    2024年02月12日
    浏览(13)
  • 如何加载模型YOLOv8 ONNXRuntime

    如何加载模型YOLOv8 ONNXRuntime

    YOLOv8 是 YOLO(You Only Look Once)目标检测系统的最新版本(v8)。YOLO 是一种实时、一次性目标检测系统,旨在在网络的单次前向传递中执行目标检测,使其快速高效。YOLOv8是之前YOLO模型的改进版本,具有更高的精度和更快的推理速度。 ONNX(开放神经网络交换)是一种表示深度

    2024年02月14日
    浏览(11)
  • yolov8量化部署(基于openvino和tensorrt)

    yolov8量化部署(基于openvino和tensorrt)

    环境配置: 将pytorch模型转为openvino模型: python量化脚本:(改编自https://github.com/openvinotoolkit/openvino_notebooks/blob/main/notebooks/230-yolov8-optimization/230-yolov8-optimization.ipynb) python推理: C++推理:(openvino库读取xml文件在compile_model时报错,暂时不明原因,改用onnx格式推理) 参考:h

    2024年02月09日
    浏览(11)
  • YOLOV8 Onnxruntime Opencv DNN C++部署

    YOLOV8 Onnxruntime Opencv DNN C++部署

          OpenCV由各种不同组件组成。OpenCV源代码主要由OpenCV core(核心库)、opencv_contrib和opencv_extra等子仓库组成。近些年,OpenCV的主仓库增加了深度学习相关的子仓库:OpenVINO(即DLDT, Deep Learning Deployment Toolkit)、open_model_zoo,以及标注工具CVAT等。         OpenCV深度学习模块只

    2024年02月16日
    浏览(22)
  • 【YOLOv8-Seg】实战二:LabVIEW+OpenVINO加速YOLOv8-seg实例分割

    【YOLOv8-Seg】实战二:LabVIEW+OpenVINO加速YOLOv8-seg实例分割

    ‍‍🏡博客主页: virobotics的CSDN博客:LabVIEW深度学习、人工智能博主 🎄所属专栏:『LabVIEW深度学习实战』 🍻上期文章: 【YOLOv8-seg】实战一:手把手教你使用YOLOv8实现实例分割 📰如觉得博主文章写的不错或对你有所帮助的话,还望大家多多支持呀! 欢迎大家✌关注、👍

    2024年02月13日
    浏览(10)
  • openvino部署yolov8 检测、分割、分类及姿态模型实例详解

    本文重点参考:https://github.com/openvino-book/yolov8_openvino_cpp/tree/main 文中代码为简便版本,如果要使用请自行修改并封装 openvnio部署模型比较方便和简单,而且不易出错,就是速度慢了点! 下边分别给出 部署源码

    2024年02月16日
    浏览(13)
  • OnnxRuntime TensorRT OpenCV::DNN性能对比(YoloV8)实测

    OnnxRuntime TensorRT OpenCV::DNN性能对比(YoloV8)实测

    之前把ORT的一套推理环境框架搭好了,在项目中也运行得非常愉快,实现了cpu/gpu,fp32/fp16的推理运算,同onnx通用模型在不同推理框架下的性能差异对比贴一下,记录一下自己对各种推理框架的学习状况 YoloV8模型大小 模型名称 参数量 NANO 3.2M ... ... CPU推理框架性能比较 框架 推理耗时

    2024年02月14日
    浏览(12)
  • AI模型部署 | onnxruntime部署YOLOv8分割模型详细教程

    AI模型部署 | onnxruntime部署YOLOv8分割模型详细教程

    本文首发于公众号【DeepDriving】,欢迎关注。 0. 引言 我之前写的文章《基于YOLOv8分割模型实现垃圾识别》介绍了如何使用 YOLOv8 分割模型来实现垃圾识别,主要是介绍如何用自定义的数据集来训练 YOLOv8 分割模型。那么训练好的模型该如何部署呢? YOLOv8 分割模型相比检测模型

    2024年04月24日
    浏览(32)
  • [C#]winform部署yolov8图像分类的openvino格式的模型

    [C#]winform部署yolov8图像分类的openvino格式的模型

    【官方框架地址】 https://github.com/ultralytics/ultralytics 【openvino介绍】 OpenVINO是一个针对Intel硬件优化的开源工具包,用于优化和部署深度学习模型。以下是OpenVINO部署模型的主要优点: 高性能:OpenVINO提供了一系列性能优化工具,如模型量化和剪枝等,可以在Intel硬件平台上实现

    2024年01月21日
    浏览(16)
  • pytorch 42 C#使用onnxruntime部署内置nms的yolov8模型

    pytorch 42 C#使用onnxruntime部署内置nms的yolov8模型

    在进行目标检测部署时,通常需要自行编码实现对模型预测结果的解码及与预测结果的nms操作。所幸现在的各种部署框架对算子的支持更为灵活,可以在模型内实现预测结果的解码,但仍然需要自行编码实现对预测结果的nms操作。其实在onnx opset===11版本以后,其已支持将nms操

    2024年02月12日
    浏览(10)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包