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

RealBasicVSR模型转成ONNX以及用c++推理

文章目录

    • 安装RealBasicVSR的环境
      • 1. 新建一个conda环境
      • 2. 安装pytorch(官网上选择合适的版本)版本太低会有问题
      • 3. 安装 mim 和 mmcv-full
      • 4. 安装 mmedit
    • 下载RealBasicVSR源码
    • 下载模型文件
    • 写一个模型转换的脚步
    • 测试生成的模型

安装RealBasicVSR的环境

1. 新建一个conda环境

conda create -n RealBasicVSR_to_ONNX  python=3.8 -y
conda activate RealBasicVSR_to_ONNX

2. 安装pytorch(官网上选择合适的版本)版本太低会有问题

conda install pytorch==1.12.1 torchvision==0.13.1 torchaudio==0.12.1 cudatoolkit=11.6 -c pytorch -c conda-forge

3. 安装 mim 和 mmcv-full

pip install openmim
mim install mmcv-full

4. 安装 mmedit

pip install mmedit

下载RealBasicVSR源码

git clone https://github.com/ckkelvinchan/RealBasicVSR.git

下载模型文件

模型文件下载 (Dropbox / Google Drive / OneDrive) ,随便选一个渠道下载就行

cd RealBasicVSR
#然后新建文件夹model
将模型文件放在model文件夹下

写一个模型转换的脚步

import cv2
import mmcv
import numpy as np
import torch
from mmcv.runner import load_checkpoint
from mmedit.core import tensor2imgfrom realbasicvsr.models.builder import build_modeldef init_model(config, checkpoint=None):if isinstance(config, str):config = mmcv.Config.fromfile(config)elif not isinstance(config, mmcv.Config):raise TypeError('config must be a filename or Config object, 'f'but got {type(config)}')config.model.pretrained = Noneconfig.test_cfg.metrics = Nonemodel = build_model(config.model, test_cfg=config.test_cfg)if checkpoint is not None:checkpoint = load_checkpoint(model, checkpoint)model.cfg = config  # save the config in the model for conveniencemodel.eval()return modeldef main():model = init_model("./configs/realbasicvsr_x4.py","./model/RealBasicVSR_x4.pth")src = cv2.imread("./data/img/test1.png")src = torch.from_numpy(src / 255.).permute(2, 0, 1).float()src = src.unsqueeze(0)input_arg = torch.stack([src], dim=1)torch.onnx.export(model,input_arg,'realbasicvsr.onnx',training= True,input_names= ['input'],output_names=['output'],opset_version=11,dynamic_axes={'input' : {0 : 'batch_size', 3 : 'w', 4 : 'h'}, 'output' : {0 : 'batch_size', 3 : 'dstw', 4 : 'dsth'}})if __name__ == '__main__':main()

这里报错:

ValueError: SRGAN model does not support `forward_train` function.

直接将这个test_mode默认值改为Ture,让程序能走下去就行了。
在这里插入图片描述

测试生成的模型

这里已经得到了 realbasicvsr.onnx 模型文件了.

import onnxruntime as ort
import numpy as np
import onnx
import cv2def main():onnx_model = onnx.load_model("./realbasicvsr.onnx")onnxstrongmodel = onnx_model.SerializeToString()sess = ort.InferenceSession(onnxstrongmodel)providers = ['CPUExecutionProvider']options = [{}]is_cuda_available = ort.get_device() == 'GPU'if is_cuda_available:providers.insert(0, 'CUDAExecutionProvider')options.insert(0, {'device_id': 0})sess.set_providers(providers, options)input_name = sess.get_inputs()[0].nameoutput_name = sess.get_outputs()[1].nameprint(sess.get_inputs()[0])print(sess.get_outputs()[0])print(sess.get_outputs()[0].shape)print(sess.get_inputs()[0].shape)img = cv2.imread("./data/img/test1.png")img = np.expand_dims((img/255.0).astype(np.float32).transpose(2,0,1), axis=0)imgs = np.array([img])print(imgs.shape)print(imgs)output = sess.run([output_name], {input_name : imgs})print(output)print(output[0].shape)output = np.clip(output, 0, 1)res = output[0][0][0].transpose(1, 2, 0)cv2.imwrite("./testout.png", (res * 255).astype(np.uint8))if __name__ == '__main__':main()

至此模型转换部分就成功完成了

http://www.lryc.cn/news/26136.html

相关文章:

  • C语言作用域(变量生存的空间)学习
  • Spark性能优化一 概念篇
  • [数据结构]:09-二分查找(顺序表指针实现形式)(C语言实现)
  • 3.基于Label studio的训练数据标注指南:文本分类任务
  • Python进阶-----面向对象3.0(面对对象三大特征之---封装)
  • 软考中级软件设计师备考建议
  • 【机器学习】决策树(理论)
  • VSCode下载与安装使用教程【超详细讲解】
  • 2023年3月北京/上海/广州/深圳DAMA数据管理认证CDGA/CDGP
  • 进程和线程理论知识
  • 华为OD机试用Python实现 -【广播服务器】
  • Solon2 的应用生命周期
  • 学习笔记-架构的演进之服务容错策略设计模式-3月day02
  • 【WEB前端进阶之路】 HTML 全路线学习知识点梳理(上)
  • mes系统核心业务流程及应用场景介绍
  • 应用统计部分常用公式总结
  • 阿赵的MaxScript学习笔记分享八《文件操作》
  • 将项目封装进docker进行迁移或使用
  • matlab - 特殊矩阵、矩阵求值、稀疏矩阵
  • Flume使用入门
  • 【Servlet篇2】Servlet的工作过程,Servlet的api——HttpServletRequest
  • 【JAVASE】注解
  • 【408之计算机组成原理】计算机系统概述
  • 1.Spring Cloud (Hoxton.SR10) 学习笔记—基础知识
  • 嵌入式开发工具箱【持续更新中】【VMware、Ubuntutftp、nfs、SecureCRT、XShell、Source Insight 4.0】
  • 深究Java Hibernate框架下的Deserialization
  • 微服务一 实用篇 - Docker安装
  • JavaSE22-集合2-map
  • 【项目精选】病历管理系统设计与实现(源码+视频)
  • 如何用Python把篮球和鸡联系起来