YOLOv9-Openvino和ONNXRuntime推理【CPU】
1 环境:
CPU:i5-12500
Python:3.8.18
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 YOLOv9介绍
YOLOv9速读
文章地址:https://arxiv.org/pdf/2402.13616.pdf
Github:https://github.com/WongKinYiu/yolov9
4 基于Openvino和ONNXRuntime推理
下面代码整个处理过程主要包括:预处理—>推理—>后处理—>画图。
假设图像resize为640×640,
前处理输出结果维度:(1, 3, 640, 640);
推理输出结果维度:(1, 84, 8400),其中84表示4个box坐标信息+80个类别概率,8400表示80×80+40×40+20×20;
后处理输出结果维度:(5, 6),其中第一个5表示图bus.jpg检出5个目标,第二个维度6表示(x1, y1, x2, y2, conf, cls)。
注:与YOLOv8输出维度一致,可通用!!!
4.1 全部代码
import argparse
import time
import cv2
import numpy as np
from openvino.runtime import Core # pip install openvino -i https://pypi.tuna.tsinghua.edu.cn/simple
import onnxruntime as ort # 使用onnxruntime推理用上,pip install onnxruntime,默认安装CPU# COCO默认的80类
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']class OpenvinoInference(object):def __init__(self, onnx_path):self.onnx_path = onnx_pathie = 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_dataclass YOLOv9:"""YOLOv9 object detection model class for handling inference and visualization."""def __init__(self, onnx_model, imgsz=(640, 640), infer_tool='openvino'):"""Initialization.Args:onnx_model (str): Path to the ONNX model."""self.infer_tool = infer_toolif self.infer_tool == 'openvino':# 构建openvino推理引擎self.openvino = OpenvinoInference(onnx_model)self.ndtype = np.singleelse:# 构建onnxruntime推理引擎self.ort_session = ort.InferenceSession(onnx_model,providers=['CUDAExecutionProvider', 'CPUExecutionProvider']if ort.get_device() == 'GPU' else ['CPUExecutionProvider'])# Numpy dtype: support both FP32 and FP16 onnx modelself.ndtype = np.half if self.ort_session.get_inputs()[0].type == 'tensor(float16)' else np.singleself.classes = CLASSES # 加载模型类别self.model_height, self.model_width = imgsz[0], imgsz[1] # 图像resize大小self.color_palette = np.random.uniform(0, 255, size=(len(self.classes), 3)) # 为每个类别生成调色板def __call__(self, im0, conf_threshold=0.4, iou_threshold=0.45):"""The whole pipeline: pre-process -> inference -> post-process.Args:im0 (Numpy.ndarray): original input image.conf_threshold (float): confidence threshold for filtering predictions.iou_threshold (float): iou threshold for NMS.Returns:boxes (List): list of bounding boxes."""# 前处理Pre-processt1 = time.time()im, ratio, (pad_w, pad_h) = self.preprocess(im0)print('预处理时间:{:.3f}s'.format(time.time() - t1))# 推理 inferencet2 = time.time()if self.infer_tool == 'openvino':preds = self.openvino.predirts(im)else:preds = self.ort_session.run(None, {self.ort_session.get_inputs()[0].name: im})[0]print('推理时间:{:.2f}s'.format(time.time() - t2))# 后处理Post-processt3 = time.time()boxes = self.postprocess(preds,im0=im0,ratio=ratio,pad_w=pad_w,pad_h=pad_h,conf_threshold=conf_threshold,iou_threshold=iou_threshold,)print('后处理时间:{:.3f}s'.format(time.time() - t3))return boxes# 前处理,包括:resize, pad, HWC to CHW,BGR to RGB,归一化,增加维度CHW -> BCHWdef preprocess(self, img):"""Pre-processes the input image.Args:img (Numpy.ndarray): image about to be processed.Returns:img_process (Numpy.ndarray): image preprocessed for inference.ratio (tuple): width, height ratios in letterbox.pad_w (float): width padding in letterbox.pad_h (float): height padding in letterbox."""# Resize and pad input image using letterbox() (Borrowed from Ultralytics)shape = img.shape[:2] # original image shapenew_shape = (self.model_height, self.model_width)r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])ratio = r, rnew_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))pad_w, pad_h = (new_shape[1] - new_unpad[0]) / 2, (new_shape[0] - new_unpad[1]) / 2 # wh paddingif shape[::-1] != new_unpad: # resizeimg = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR)top, bottom = int(round(pad_h - 0.1)), int(round(pad_h + 0.1))left, right = int(round(pad_w - 0.1)), int(round(pad_w + 0.1))img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=(114, 114, 114)) # 填充# Transforms: HWC to CHW -> BGR to RGB -> div(255) -> contiguous -> add axis(optional)img = np.ascontiguousarray(np.einsum('HWC->CHW', img)[::-1], dtype=self.ndtype) / 255.0img_process = img[None] if len(img.shape) == 3 else imgreturn img_process, ratio, (pad_w, pad_h)# 后处理,包括:阈值过滤与NMSdef postprocess(self, preds, im0, ratio, pad_w, pad_h, conf_threshold, iou_threshold):"""Post-process the prediction.Args:preds (Numpy.ndarray): predictions come from ort.session.run().im0 (Numpy.ndarray): [h, w, c] original input image.ratio (tuple): width, height ratios in letterbox.pad_w (float): width padding in letterbox.pad_h (float): height padding in letterbox.conf_threshold (float): conf threshold.iou_threshold (float): iou threshold.Returns:boxes (List): list of bounding boxes."""x = preds # outputs: predictions (1, 84, 8400)# Transpose the first output: (Batch_size, xywh_conf_cls, Num_anchors) -> (Batch_size, Num_anchors, xywh_conf_cls)x = np.einsum('bcn->bnc', x) # (1, 8400, 84)# Predictions filtering by conf-thresholdx = x[np.amax(x[..., 4:], axis=-1) > conf_threshold]# Create a new matrix which merge these(box, score, cls) into one# For more details about `numpy.c_()`: https://numpy.org/doc/1.26/reference/generated/numpy.c_.htmlx = np.c_[x[..., :4], np.amax(x[..., 4:], axis=-1), np.argmax(x[..., 4:], axis=-1)]# NMS filtering# 经过NMS后的值, np.array([[x, y, w, h, conf, cls], ...]), shape=(-1, 4 + 1 + 1)x = x[cv2.dnn.NMSBoxes(x[:, :4], x[:, 4], conf_threshold, iou_threshold)]# 重新缩放边界框,为画图做准备if len(x) > 0:# Bounding boxes format change: cxcywh -> xyxyx[..., [0, 1]] -= x[..., [2, 3]] / 2x[..., [2, 3]] += x[..., [0, 1]]# Rescales bounding boxes from model shape(model_height, model_width) to the shape of original imagex[..., :4] -= [pad_w, pad_h, pad_w, pad_h]x[..., :4] /= min(ratio)# Bounding boxes boundary clampx[..., [0, 2]] = x[:, [0, 2]].clip(0, im0.shape[1])x[..., [1, 3]] = x[:, [1, 3]].clip(0, im0.shape[0])return x[..., :6] # boxeselse:return []# 绘框def draw_and_visualize(self, im, bboxes, vis=False, save=True):"""Draw and visualize results.Args:im (np.ndarray): original image, shape [h, w, c].bboxes (numpy.ndarray): [n, 4], n is number of bboxes.vis (bool): imshow using OpenCV.save (bool): save image annotated.Returns:None"""# Draw rectangles for (*box, conf, cls_) in bboxes:# draw bbox rectanglecv2.rectangle(im, (int(box[0]), int(box[1])), (int(box[2]), int(box[3])),self.color_palette[int(cls_)], 1, cv2.LINE_AA)cv2.putText(im, f'{self.classes[int(cls_)]}: {conf:.3f}', (int(box[0]), int(box[1] - 9)),cv2.FONT_HERSHEY_SIMPLEX, 0.7, self.color_palette[int(cls_)], 2, cv2.LINE_AA)# Show imageif vis:cv2.imshow('demo', im)cv2.waitKey(0)cv2.destroyAllWindows()# Save imageif save:cv2.imwrite('demo.jpg', im)if __name__ == '__main__':# Create an argument parser to handle command-line argumentsparser = argparse.ArgumentParser()parser.add_argument('--model', type=str, default='yolov9c.onnx', help='Path to ONNX model')parser.add_argument('--source', type=str, default=str('bus.jpg'), help='Path to input image')parser.add_argument('--imgsz', type=tuple, default=(640, 640), help='Image input size')parser.add_argument('--conf', type=float, default=0.25, help='Confidence threshold')parser.add_argument('--iou', type=float, default=0.45, help='NMS IoU threshold')parser.add_argument('--infer_tool', type=str, default='openvino', choices=("openvino", "onnxruntime"), help='选择推理引擎')args = parser.parse_args()# Build modelmodel = YOLOv9(args.model, args.imgsz, args.infer_tool)# Read image by OpenCVimg = cv2.imread(args.source)# Inferenceboxes = model(img, conf_threshold=args.conf, iou_threshold=args.iou)# Visualizeif len(boxes) > 0:model.draw_and_visualize(img, boxes, vis=False, save=True)
4.2 结果

具体时间消耗:
预处理时间:0.005s(包含Pad)
推理时间:0.19~0.20s(Openvino)
推理时间:0.36~0.40s(ONNXRuntime)
后处理时间:0.001s
注:640×640下。
YOLOv9c.onnx下载链接
相关文章:
YOLOv9-Openvino和ONNXRuntime推理【CPU】
1 环境: CPU:i5-12500 Python:3.8.18 2 安装Openvino和ONNXRuntime 2.1 Openvino简介 Openvino是由Intel开发的专门用于优化和部署人工智能推理的半开源的工具包,主要用于对深度推理做优化。 Openvino内部集成了Opencv、Tens…...
AIGC 架构:RAG (retrieval augumented generation) 应用可以使用 PostgreSQL 作为向量数据库组件吗?
是的,RAG(检索增强生成)应用程序可以绝对地使用 PostgreSQL 作为向量数据库!事实上,它是一个流行的选择,因为有以下几个优点: 使用 PostgreSQL 和 pgvector 的优点: 集成解决方案&…...
leetcode:134.加油站
解题思路:需要注意开始时的编号,有的可以走一圈,有的走不了 模拟过程:for循环主要是用来模拟线性的过程,而在这里它是环状的; 可以用暴力解法,但是在这里我用贪心来解决。 常见疑惑࿱…...
uniapp的微信小程序授权头像昵称(最新版)
前面我出过两期博客关于小程序授权登录,利用php实现一个简单的小程序授权登录并存储授权用户信息到数据库的完整流程。无奈,小程序官方又整幺蛾子了。wx.getUserInfo接口收回,wx.getUserProfile接口也不让用。导致我的个人小程序:梦缘 的授权…...
Spring Boot到底是如何进行自动配置的?
【1】从 spring.factories 配置文件中加载 EnableAutoConfiguration 自动配置类),获取的自动配 置类如图所示。 【2】若 EnableAutoConfiguration 等注解标有要 exclude 的自动配置类,那么再将这个自动配置类 排除掉; 【3】排除掉要 exclude …...
【王道数据结构】【chapter7查找】【P285t5】
线性表中各节点的检索概率不等时,可用如下策略提高顺序检索的效率;若找到指定的结点,则将该结点和其前驱结点(若存在)交换,使得经常被访问的结点尽量位于表的前端。试设计在顺序结构和链式结构的线性表盘上…...
个人玩航拍,如何申请无人机空域?
我们在《年会不能停》一文中,有分享我们在西岭雪山用无人机拍摄的照片和视频,有兴趣可以去回顾。 春节的时候,趁着回老家一趟,又将无人机带了回去,计划拍一下老家的风景。 原本以为穷乡僻壤的地方可以随便飞…...
ChatGPT带火的HBM是什么?
“ChatGPT是人工智能领域的iPhone时刻,也是计算领域有史以来最伟大的技术之一。” 英伟达创始人兼CEO黄仁勋此前这样盛赞ChatGPT。 ChatGPT突然爆火,对大算力芯片提出了更高更多的要求。近日,据韩国经济日报报道,受惠于ChatGPT&am…...
10 款数据恢复软件功能和有效性对比(2024 年更新)
数据丢失可能是一种痛苦的经历,无论是由于意外删除、硬件故障还是软件损坏。值得庆幸的是,数字时代带来了强大的数据恢复解决方案。 随着我们进入 2024 年,市场上充斥着旨在有效检索丢失数据的先进软件。在本文中,我们将探讨 2024…...
Python 与 pdfplumber:高效自动读取 PDF 的解决方案
在许多数据处理和信息提取任务中,处理 PDF 文件可能是一个具有挑战性的过程。幸运的是,Python 提供了许多库来简化这个任务,其中 pdfplumber 是一个功能强大且易于使用的库。在本文中,我们将探讨如何使用 Python 和 pdfplumber 库…...
Flutter 启动流程解析
任何应用程序都是从main()开始的,Flutter也不例外。Flutter 的启动入口在 lib/main.dart 里的 main() 函数中,代码如下。 void main() => runApp(MyApp());void runApp(Widget app) {final WidgetsBinding binding = WidgetsFlutterBinding.ensureInitialized();assert(b…...
全量知识系统问题及SmartChat给出的答复 之4
Q11. 现在,我们进一步完善前端--知识表征。首先前端需要基于一个全面的GUI库,和前面说到的 混沌工程:基于流形 的分形混沌 与自相似性的计算机图像与程序。请考虑 1)这两部分的实现用什么 ?2) 如何封装它们…...
Java架构师之路七、大数据:Hadoop、Spark、Hive、HBase、Kafka等
目录 Hadoop: Spark: Hive: HBase: Kafka: Java架构师之路六、高并发与性能优化:高并发编程、性能调优、线程池、NIO、Netty、高性能数据库等。-CSDN博客Java架构师之路八、安全技术:Web安…...
图论基础(一)
一、图论 图论是数学的一个分支,它以图为研究对象。图论中的图是若干给定的点(顶点)以及连接两点的线(边)构成的图像,这种图形通常用来描述某些事物之间的某种特定关系,用点代表事物,…...
使用 React 和 MUI 创建多选 Checkbox 树组件
在本篇博客中,我们将使用 React 和 MUI(Material-UI)库来创建一个多选 Checkbox 树组件。该组件可以用于展示树形结构的数据,并允许用户选择多个节点。 前提 在开始之前,确保你已经安装了以下依赖: Reac…...
vue3里面使用el-image-vie出现图片预览导致页面卡顿停止加载问题
需求:我们在使用element-plus组件里面的图片预览时候,通过点击按钮来实现图片预览的效果。在开发过程中我们会遇到图片预览的时候出现卡顿出不来,导致当前的页面停止加载了。 具体思路如下: 我们需要添加:preview-teleported“t…...
Leetcoder Day26| 回溯part06:总结+三道hard题
332.重新安排行程 给定一个机票的字符串二维数组 [from, to],子数组中的两个成员分别表示飞机出发和降落的机场地点,对该行程进行重新规划排序。所有这些机票都属于一个从 JFK(肯尼迪国际机场)出发的先生,所以该行程必…...
浅谈 Linux 网络编程 - 网络字节序
文章目录 前言核心知识关于 小端法关于 大端法网络字节序的转换 函数 前言 在进行 socket 网络编程时,会用到字节流的转换函数、例如 inet_pton、htons 等,那么为什么要用到这些函数呢,本篇主要就是对这部分进行介绍。 核心知识 重点需要记…...
Nginx网络服务六-----IP透传、调度算法和负载均衡
1.实现反向代理客户端 IP 透传 就是在日志里面加上一个变量 Module ngx_http_proxy_module [rootcentos8 ~]# cat /apps/nginx/conf/conf.d/pc.conf server { listen 80; server_name www.kgc.org; location / { index index.html index.php; root /data/nginx/html/p…...
【Linux进程】进程状态---进程僵尸与孤儿
📙 作者简介 :RO-BERRY 📗 学习方向:致力于C、C、数据结构、TCP/IP、数据库等等一系列知识 📒 日后方向 : 偏向于CPP开发以及大数据方向,欢迎各位关注,谢谢各位的支持 目录 1.进程排队2.进程状态…...
RK3588 Camera调试:APK打开无画面,从数据链路到HAL的深度排查指南
1. 问题现象与初步分析 最近在调试RK3588平台的Camera功能时,遇到一个典型问题:驱动已经注册成功,I2C通信也正常,但上层APK打开后就是没有画面输出。这种情况在实际开发中很常见,很多工程师都会卡在这里。今天我就来分…...
理解「响应式编程」在Spring WebFlux中的应用
响应式编程在现代高并发系统中扮演着重要角色,而Spring WebFlux作为Spring生态中的响应式框架,为开发者提供了处理异步非阻塞请求的强大工具。理解响应式编程在WebFlux中的应用,不仅能提升系统性能,还能优化资源利用率。本文将围绕…...
SQL窗口函数性能瓶颈排查_执行计划中的关键点
WindowAgg节点cost高或width异常(>1000字节)是性能问题首要信号,因窗口函数需缓存整分区数据,width大加重内存与磁盘压力,cost高常反映排序或物化代价被低估。看懂执行计划里 WindowAgg 节点的 cost 和 widthPostgr…...
【网络基础科普】交换机 MAC 地址全解析:查询方法、System MAC 与 Bridge MAC 的区别,以及“为什么只差 1”
一、背景:为什么要搞懂交换机 MAC? 在很多网络运维场景中,查询交换机 MAC 地址是刚性要求: 从资产台账、合规审计,到故障排查与网络设计,MAC 地址都是基础且关键的数据。 本文从真实运维背景出发…...
当n和L大到1e18时,别再暴力模拟了!详解‘3437 melon’吃瓜问题的O(1)公式推导与边界条件处理
极端数据规模下的算法优化:从暴力模拟到O(1)公式推导 在算法竞赛和高性能编程中,我们常常会遇到数据规模极其庞大的问题。当输入参数达到1e18量级时,传统的暴力模拟或动态规划方法往往无法在合理时间内完成计算。本文将以经典的"3437 me…...
PHP怎么实现SAML单点登录_PHP企业级SSO解决方案【指南】
onelogin/php-saml 是 PHP 中最稳的 SAML 库,必须用 Auth 类全流程处理签名验签、时间校验等;SP ID 需与 IDP 完全一致;私钥须为 PEM 格式;SAMLResponse 必须由 processResponse() 全链路验证;属性为数组结构需安全取值…...
西门子S7-300与Intouch通讯实战:DASSIDirect驱动配置全流程(附避坑指南)
西门子S7-300与Intouch高效通讯:DASSIDirect驱动配置实战手册 在工业自动化领域,SCADA系统与PLC的稳定通讯是确保生产数据实时监控的关键环节。作为业内广泛采用的组合,西门子S7-300系列PLC与Wonderware Intouch的集成方案,通过DA…...
格子玻尔兹曼双分布函数液汽相变传热模拟代码功能说明
格子玻尔兹曼 LBM 多孔介质沸腾 Gongchen双分布函数模型,matlab代码,有参考文献一、代码整体概述 本代码基于格子玻尔兹曼方法(Lattice Boltzmann Method, LBM),实现了液汽相变传热过程的数值模拟,核心聚焦…...
别再死磕理论了!用PCL+KinectFusion手把手教你从照片到3D模型(保姆级避坑指南)
从零实现3D建模:基于PCL与KinectFusion的实战避坑手册 当我在研究生实验室第一次尝试用Kinect扫描物体生成3D模型时,连续三天的环境配置失败几乎让我放弃。直到发现那个被埋没在GitHub issue里的OpenCL驱动解决方案,才明白三维重建的入门门槛…...
CMake实战:在Qt Creator中优雅集成第三方库的完整指南
1. 为什么需要优雅集成第三方库? 最近在做一个图像处理项目时,我遇到了一个典型问题:在本机调试一切正常,但把程序发给同事后却报错"找不到opencv_world450.dll"。这种问题在Windows平台开发中太常见了,根本…...
