当前位置: 首页 > 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.缓存就是一个临时存放区域--离用户比较近 二、作用--意义---如果系统出现故…...

MongoDB学习和应用(高效的非关系型数据库)

一丶 MongoDB简介 对于社交类软件的功能,我们需要对它的功能特点进行分析: 数据量会随着用户数增大而增大读多写少价值较低非好友看不到其动态信息地理位置的查询… 针对以上特点进行分析各大存储工具: mysql:关系型数据库&am…...

uni-app学习笔记二十二---使用vite.config.js全局导入常用依赖

在前面的练习中,每个页面需要使用ref,onShow等生命周期钩子函数时都需要像下面这样导入 import {onMounted, ref} from "vue" 如果不想每个页面都导入,需要使用node.js命令npm安装unplugin-auto-import npm install unplugin-au…...

聊聊 Pulsar:Producer 源码解析

一、前言 Apache Pulsar 是一个企业级的开源分布式消息传递平台,以其高性能、可扩展性和存储计算分离架构在消息队列和流处理领域独树一帜。在 Pulsar 的核心架构中,Producer(生产者) 是连接客户端应用与消息队列的第一步。生产者…...

Keil 中设置 STM32 Flash 和 RAM 地址详解

文章目录 Keil 中设置 STM32 Flash 和 RAM 地址详解一、Flash 和 RAM 配置界面(Target 选项卡)1. IROM1(用于配置 Flash)2. IRAM1(用于配置 RAM)二、链接器设置界面(Linker 选项卡)1. 勾选“Use Memory Layout from Target Dialog”2. 查看链接器参数(如果没有勾选上面…...

python如何将word的doc另存为docx

将 DOCX 文件另存为 DOCX 格式(Python 实现) 在 Python 中,你可以使用 python-docx 库来操作 Word 文档。不过需要注意的是,.doc 是旧的 Word 格式,而 .docx 是新的基于 XML 的格式。python-docx 只能处理 .docx 格式…...

Web 架构之 CDN 加速原理与落地实践

文章目录 一、思维导图二、正文内容(一)CDN 基础概念1. 定义2. 组成部分 (二)CDN 加速原理1. 请求路由2. 内容缓存3. 内容更新 (三)CDN 落地实践1. 选择 CDN 服务商2. 配置 CDN3. 集成到 Web 架构 &#xf…...

Netty从入门到进阶(二)

二、Netty入门 1. 概述 1.1 Netty是什么 Netty is an asynchronous event-driven network application framework for rapid development of maintainable high performance protocol servers & clients. Netty是一个异步的、基于事件驱动的网络应用框架,用于…...

力扣热题100 k个一组反转链表题解

题目: 代码: func reverseKGroup(head *ListNode, k int) *ListNode {cur : headfor i : 0; i < k; i {if cur nil {return head}cur cur.Next}newHead : reverse(head, cur)head.Next reverseKGroup(cur, k)return newHead }func reverse(start, end *ListNode) *ListN…...

【p2p、分布式,区块链笔记 MESH】Bluetooth蓝牙通信 BLE Mesh协议的拓扑结构 定向转发机制

目录 节点的功能承载层&#xff08;GATT/Adv&#xff09;局限性&#xff1a; 拓扑关系定向转发机制定向转发意义 CG 节点的功能 节点的功能由节点支持的特性和功能决定。所有节点都能够发送和接收网格消息。节点还可以选择支持一个或多个附加功能&#xff0c;如 Configuration …...

android RelativeLayout布局

<?xml version"1.0" encoding"utf-8"?> <RelativeLayout xmlns:android"http://schemas.android.com/apk/res/android"android:layout_width"match_parent"android:layout_height"match_parent"android:gravity&…...