当前位置: 首页 > news >正文

ONNX runtime本地终端部署

1、class_index.csv文件:

ID,English,Chinese
0,A,你
1,B,我
2,C,他
3,D,她

2、classification.onnx
3、单张图像处理代码如下:

import onnxruntime
import torch
import torch.nn.functional as F
import pandas as pd
from PIL import Image
from torchvision import transforms
import matplotlib.pyplot as pltdef predict_class(model_path, image_path, class_index_path, top_n=1):# Load the ONNX model and create an ONNX Runtime inference sessionort_session = onnxruntime.InferenceSession(model_path, providers=['CUDAExecutionProvider'])# Load the test image and apply transformationsimg_pil = Image.open(image_path).convert('RGB')test_transform = transforms.Compose([transforms.Resize(256),transforms.CenterCrop(224),transforms.ToTensor(),transforms.Normalize([0.485, 0.456, 0.406],[0.229, 0.224, 0.225])])input_img = test_transform(img_pil)input_tensor = input_img.unsqueeze(0).numpy()# Perform inferenceort_inputs = {'input': input_tensor}pred_logits = ort_session.run(['output'], ort_inputs)[0]pred_logits = torch.tensor(pred_logits)# Apply softmax to get class probabilitiespred_softmax = F.softmax(pred_logits, dim=1)# Load the class index mappingdf = pd.read_csv(class_index_path)idx_to_labels = {row['ID']: row['English'] for idx, row in df.iterrows()}# idx_to_labels = {row['ID']: row['Chinese'] for idx, row in df.iterrows()}# Get the top predicted classes and their confidence scorestop_n_results = torch.topk(pred_softmax, top_n)pred_ids = top_n_results.indices.numpy()[0]confs = top_n_results.values.numpy()[0]# Translate class IDs to class namespredicted_classes = [idx_to_labels[class_id] for class_id in pred_ids]# Create a list of class names and their corresponding confidence scoresresults = []for i in range(top_n):class_name = predicted_classes[i]confidence = confs[i] * 100results.append((class_name, confidence))return results,img_pilif __name__ == '__main__':model_path = 'classification.onnx'image_path = 'E:/Python_Project/classification/21t1Gdxsagittal0143.png'class_index_path = 'class_index.csv'top_n = 1  # Adjust the number of top predictions you wantpredictions,img = predict_class(model_path, image_path, class_index_path, top_n)for class_name, confidence in predictions:text = class_name + ': {:.3f}%'.format(confidence)print(text)# Display the image inputplt.rcParams['font.sans-serif'] = 'SimHei'  # 黑体plt.figure(figsize=(6,6))plt.imshow(img)plt.axis('off')# add the predicted class and confidence as a titleclass_name, confidence = predictions[0]title_text = f'Predicted Class: {class_name}\nAccuracy: {confidence:.3f}%'plt.title(title_text)plt.show()

4、批量图像处理代码如下:

import onnxruntime
import pandas
import torch
from PIL import Image
import os
from torchvision import transforms
import torch.nn.functional as F
import matplotlib.pyplot as pltdef batch_prediction(model_path,class_index_path,top_n,input_folder,output_folder):# 列出输出文件夹所有图片input_files=os.listdir(input_folder)# print(input_files)# 针对每个文件进行处理for input_file in input_files:# 构建一个完整的路径input_file_path=os.path.join(input_folder,input_file)# 打开图像并转换成RGB格式img_pil=Image.open(input_file_path).convert('RGB')# print(image)# 图像预处理test_transform = transforms.Compose([transforms.Resize(256),transforms.CenterCrop(224),transforms.ToTensor(),transforms.Normalize([0.485, 0.456, 0.406],[0.229, 0.224, 0.225])])input_img=test_transform(img_pil)# 增加维度input_tensor=input_img.unsqueeze(0).numpy()# print(input_tensor.shape)# 加载ONNX模型并创建onnx_runtime推理ort_session = onnxruntime.InferenceSession(model_path, providers=['CUDAExecutionProvider'])# print(ort_session)# 平台推理ort_inputs={'input':input_tensor}pre_logits=ort_session.run(['output'],ort_inputs)[0]pre_logits=torch.Tensor(pre_logits)# print(pre_logits)# 应用softmax去做类别预测pred_softmax=F.softmax(pre_logits,dim=1)# dim=1 按行进行归一化# print(pred_softmax)# 加载类别索引df=pandas.read_csv(class_index_path)# print(df)idx_to_labels={row['ID'] : row['English'] for idx, row in df.iterrows()}# 去得到准确率和得分top_n_results=torch.topk(pred_softmax,top_n)# print(top_n_results)pred_ids=top_n_results.indices.numpy()[0]# 得到id# print(pred_ids)confs=top_n_results.values.numpy()[0]# 得到分数 numpy格式# print(type(confs))# 预测类别predicted_class=[idx_to_labels[class_id] for class_id in pred_ids]#列表格式# print(predicted_class)# 输出类别和相应的得分# print(predicted_class,confs)for i in range(top_n):class_name=predicted_class[i]confidence=confs[i]*100plt.rcParams['font.sans-serif'] = 'SimHei'  # 黑体中文字体plt.imshow(img_pil)#plt.axis('off')#title_text = f'Predicted Class: {class_name}\nAccuracy: {confidence:.3f}%'plt.title(title_text)print(title_text)# 确保输出文件夹存在,如果不存在则创建if not os.path.exists(output_folder):os.makedirs(output_folder)# 构建输出文件夹的完整路径并保存绘制的图像plot_output_file = os.path.join(output_folder,input_file)plt.savefig(plot_output_file, bbox_inches='tight', pad_inches=0.1)  # 保存绘制的图像plt.close()  # 关闭当前绘图以便处理下一个图像if __name__ == '__main__':model_path='classification.onnx'class_index_path='class_index.csv'top_n=1input_folder="C:/Users/XUB/Desktop/A"output_folder="C:/Users/XUB/Desktop/B"batch_prediction(model_path,class_index_path,top_n,input_folder,output_folder)

相关文章:

ONNX runtime本地终端部署

1、class_index.csv文件: ID,English,Chinese 0,A,你 1,B,我 2,C,他 3,D,她2、classification.onnx 3、单张图像处理代码如下: import onnxruntime import torch import torch.nn.functional as F import pandas as pd from PIL import Image from tor…...

Linux性能优化--性能工具:特定进程CPU

4.0 概述 在用系统级性能工具找出是哪个进程降低了系统速度之后,你需要用特定进程性能工具来发现这个进程的行为。对此,Linux提供了丰富的工具用于追踪一个进程和应用程序性能的重要统计信息。 阅读本章后,你将能够: 确定应用程…...

技术人员转岗产品经理,有优势吗?

产品经理是一个非技术型的岗位,但是懂一些技术相关的知识会更好的和技术部门沟通,能更好的从技术部门的角度理解需求的可行性。所以这么说来,技术转产品经理相对来说更加有优势。 任何事情不可能都是只有好处没有坏处的,同样的&a…...

使用IDEA2022.1创建Maven工程出现卡死问题

使用IDEA创建Maven工程出现卡死问题,这个是一个bug 这里是别人和官方提供这个bug,大家可以参考一下 话不多说,上教程 解决方案: 方案1:更新idea版本 方案2:关闭工程,再新建,看图...

Nuttx Syscall

在Nuttx系统中,mksyscall工具用于根据syscall/syscall.csv文件生成供用户调用的接口和内核中对应的接口。具体来说,mksyscall -p system.csv生成供用户调用的接口,而mksyscall -s system.csv生成内核中调用的接口。 在syscall/syscall.csv文…...

HTTP协议中GET请求和POST请求的区别

1. 形式上: GET请求:参数包含在URL中,意味着参数的长度是有限的,并且参数只能是ASCII码的形式。 POST请求:参数包含在请求体中,参数的长度是不受限,并且参数支持多种数据类型。 2.安全性 GET请…...

【广州华锐互动】利用VR开展施工现场安全培训,提高员工安全意识水平

随着科技的不断发展,虚拟现实(VR)技术已经逐渐渗透到各个领域,为我们带来了前所未有的沉浸式体验。在建筑施工行业,VR技术的应用也日益广泛,从设计、施工到管理,都可以看到VR技术的身影。而在这…...

Cornerstone for Mac:高效SVN管理的黄金标准

在当今的软件开发领域,版本控制系统是不可或缺的一部分。其中,Subversion(SVN)是一个广泛使用的版本控制系统,有助于团队协同工作,实现代码的版本管理和追踪。对于Mac用户来说,Cornerstone是一款…...

数据结构之顺序表的模拟实现

💕"世事犹如书籍,一页页被翻过去。人要向前看,少翻历史旧账。"💕 作者:Mylvzi 文章主要内容:数据结构之顺序表的模拟实现 /*** Created with IntelliJ IDEA.* Description:* User: 绿字* Date:…...

R6G azide, 5-isomer具有良好的水溶性,2135330-71-9

试剂 | 基础知识概述(部分): 英文名称:R6G azide, 5-isomer CAS:2135330-71-9 分子式:C30H32N6O4 分子量:540.61 规格标准:10mg,25mg,50mg,可提供mg级以…...

Canvas系列绘制图片学习:绘制图片和渐变效果

我们现在已经可以绘制好多东西了,不过在实际开发中,绘制最多的当然是图片了,这章我们就讲讲图片的绘制。 绘制图片 绘制图片的API是drawImage,它的参数有三种情况: // 将图片绘制在canvas的(dX, dY)坐标处 context.…...

AJAX为什么叫AJAX

AJAX(Asynchronous JavaScript and XML)这个名字是由美国程序员Jesse James Garrett在2005年提出的,用来描述一种用于创建交互式Web应用程序的技术组合。它之所以被称为"AJAX",有以下原因: Asynchronous&…...

自动化测试中如何编写配置文件 ? 该使用什么工具 ? 一文详解使用ConfigParser读写配置文件

1. 配置文件说明 只要是用编写项目,你就肯定离不开配置文件 。就以测试人员编写的自动化测试项目为例 ,如果你做连接数据库 、访问一些第三方接口、或者访问登录接口的用户名和密码。这些输入的信息最大特点就是都可能是变量,比如访问数据库…...

文件批量管理:轻松复制备份并删除原文件

在日常生活和工作中,我们经常需要处理大量的文件。为了确保文件的安全性和完整性,您需要一种高效的文件批量管理方法。本文将向您介绍如何一一复制备份并删除原文件里的文件,让您的文件管理变得轻松便捷。 首先,我们要进入文件批…...

Linux高性能服务器编程 学习笔记 第十七章 系统监测工具

tcpdump是一款经典的抓包工具,即使今天我们已经有了像Wireshark这样更易于使用和掌握的抓包工具,tcpdump仍是网络程序员的必备利器。 tcpdump提供了一些选项用以过滤数据包或定制输出格式,常见的选项如下: 1.-n:使用I…...

rabbitmq 消费者报错 ListenerExecutionFailedException NullPointerException

报错信息: org.springframework.amqp.rabbit.support.ListenerExecutionFailedException: Listener method private void com.xxx.service.impl.xxxServiceImpl.xxx(com.xxx.dto.XXX) threw exception at org.springframework.amqp.rabbit.listener.adapter.Mes…...

Java面试题:链表-合并两个排序的链表

描述 输入两个递增的链表,单个链表的长度为n,合并这两个链表并使新链表中的节点仍然是递增排序的。 示例 输入: {1,3,5}, {2,4,6}返回值: {1,2,3,4,5,6}原题地址:https://www.nowcoder.com/practice/d8b6b4358f7742…...

Springboot结合Mockito写单元测试实践和原理

文章目录 前言一、使用最佳实践使用场景SpyBean失效场景解决Mock失效的问题避免FactoryBean的实现方式使用MockBean,但是要指定name 个人推荐 二、原理1. MockBean2.SpyBean方法调用 总结 前言 相信看我博客的都是javaer,工作中一般都是使用Springboot框…...

操作系统之微内核架构

宏内核相反,微内核架构提倡功能尽可能少,只提供进程调度、处理中断、内存映射、进程间通信等功能。微内核架构是不能够提供什么实际功能的,而内存管理、进程管理、设备管理和文件管理服务等,都被做成一个个服务进程,它…...

24---WPF缓存

一、什么是缓存: 1.缓存指的是将需要频繁访问的网络内容存放在离用户较近、访问速度更快的系统中,以提高内容访问速度的一种技术。缓存服务器就是存放频繁访问内容的服务器。 2.缓存就是一个临时存放区域--离用户比较近 二、作用--意义---如果系统出现故…...

C++初阶-list的底层

目录 1.std::list实现的所有代码 2.list的简单介绍 2.1实现list的类 2.2_list_iterator的实现 2.2.1_list_iterator实现的原因和好处 2.2.2_list_iterator实现 2.3_list_node的实现 2.3.1. 避免递归的模板依赖 2.3.2. 内存布局一致性 2.3.3. 类型安全的替代方案 2.3.…...

iPhone密码忘记了办?iPhoneUnlocker,iPhone解锁工具Aiseesoft iPhone Unlocker 高级注册版​分享

平时用 iPhone 的时候,难免会碰到解锁的麻烦事。比如密码忘了、人脸识别 / 指纹识别突然不灵,或者买了二手 iPhone 却被原来的 iCloud 账号锁住,这时候就需要靠谱的解锁工具来帮忙了。Aiseesoft iPhone Unlocker 就是专门解决这些问题的软件&…...

系统设计 --- MongoDB亿级数据查询优化策略

系统设计 --- MongoDB亿级数据查询分表策略 背景Solution --- 分表 背景 使用audit log实现Audi Trail功能 Audit Trail范围: 六个月数据量: 每秒5-7条audi log,共计7千万 – 1亿条数据需要实现全文检索按照时间倒序因为license问题,不能使用ELK只能使用…...

376. Wiggle Subsequence

376. Wiggle Subsequence 代码 class Solution { public:int wiggleMaxLength(vector<int>& nums) {int n nums.size();int res 1;int prediff 0;int curdiff 0;for(int i 0;i < n-1;i){curdiff nums[i1] - nums[i];if( (prediff > 0 && curdif…...

Vue2 第一节_Vue2上手_插值表达式{{}}_访问数据和修改数据_Vue开发者工具

文章目录 1.Vue2上手-如何创建一个Vue实例,进行初始化渲染2. 插值表达式{{}}3. 访问数据和修改数据4. vue响应式5. Vue开发者工具--方便调试 1.Vue2上手-如何创建一个Vue实例,进行初始化渲染 准备容器引包创建Vue实例 new Vue()指定配置项 ->渲染数据 准备一个容器,例如: …...

自然语言处理——循环神经网络

自然语言处理——循环神经网络 循环神经网络应用到基于机器学习的自然语言处理任务序列到类别同步的序列到序列模式异步的序列到序列模式 参数学习和长程依赖问题基于门控的循环神经网络门控循环单元&#xff08;GRU&#xff09;长短期记忆神经网络&#xff08;LSTM&#xff09…...

根据万维钢·精英日课6的内容,使用AI(2025)可以参考以下方法:

根据万维钢精英日课6的内容&#xff0c;使用AI&#xff08;2025&#xff09;可以参考以下方法&#xff1a; 四个洞见 模型已经比人聪明&#xff1a;以ChatGPT o3为代表的AI非常强大&#xff0c;能运用高级理论解释道理、引用最新学术论文&#xff0c;生成对顶尖科学家都有用的…...

以光量子为例,详解量子获取方式

光量子技术获取量子比特可在室温下进行。该方式有望通过与名为硅光子学&#xff08;silicon photonics&#xff09;的光波导&#xff08;optical waveguide&#xff09;芯片制造技术和光纤等光通信技术相结合来实现量子计算机。量子力学中&#xff0c;光既是波又是粒子。光子本…...

Python 高效图像帧提取与视频编码:实战指南

Python 高效图像帧提取与视频编码:实战指南 在音视频处理领域,图像帧提取与视频编码是基础但极具挑战性的任务。Python 结合强大的第三方库(如 OpenCV、FFmpeg、PyAV),可以高效处理视频流,实现快速帧提取、压缩编码等关键功能。本文将深入介绍如何优化这些流程,提高处理…...

Python网页自动化Selenium中文文档

1. 安装 1.1. 安装 Selenium Python bindings 提供了一个简单的API&#xff0c;让你使用Selenium WebDriver来编写功能/校验测试。 通过Selenium Python的API&#xff0c;你可以非常直观的使用Selenium WebDriver的所有功能。 Selenium Python bindings 使用非常简洁方便的A…...