ONNX yolov5导出 convert error --grid

news2024/9/23 17:19:01

使用的版本

  • https://github.com/ultralytics/yolov5/tree/v5.0

安装onnx

torch.onnx.export(model, img, f, verbose=False, opset_version=12, input_names=['images'],
                          output_names=['classes', 'boxes'] if y is None else ['output'],
                          dynamic_axes={'images': {0: 'batch', 2: 'height', 3: 'width'},  # size(1,3,640,640)
                                        'output': {0: 'batch', 2: 'y', 3: 'x'}} if opt.dynamic else None)

opset_version=12,安装对应版本的onnx

:~/Documents/pachong/yolov5$ pip install onnx==1.12.0
Collecting onnx==1.12.0
  Downloading onnx-1.12.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (13.1 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 13.1/13.1 MB 32.9 kB/s eta 0:00:00
Requirement already satisfied: numpy>=1.16.6 in /home/pdd/anaconda3/envs/yolo/lib/python3.7/site-packages (from onnx==1.12.0) (1.21.6)
Requirement already satisfied: typing-extensions>=3.6.2.1 in /home/pdd/anaconda3/envs/yolo/lib/python3.7/site-packages (from onnx==1.12.0) (4.4.0)
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProtocolError('Connection aborted.', ConnectionResetError(104, '连接被对方重设'))': /simple/protobuf/
Collecting protobuf<=3.20.1,>=3.12.2
  Downloading protobuf-3.20.1-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.whl (1.0 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1.0/1.0 MB 26.1 kB/s eta 0:00:00
Installing collected packages: protobuf, onnx
  Attempting uninstall: protobuf
    Found existing installation: protobuf 3.20.3
    Uninstalling protobuf-3.20.3:
      Successfully uninstalled protobuf-3.20.3
  Attempting uninstall: onnx
    Found existing installation: onnx 1.13.0
    Uninstalling onnx-1.13.0:
      Successfully uninstalled onnx-1.13.0
ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
tensorboard 2.10.1 requires protobuf<3.20,>=3.9.2, but you have protobuf 3.20.1 which is incompatible.
Successfully installed onnx-1.12.0 protobuf-3.20.1

export model

  • python ./models/export.py --weights ./weights/yolov5s.pt --img 640 --batch 1

When given a 640x640 input image, the model outputs the following 3 tensors.

// https://medium.com/axinc-ai/yolov5-the-latest-model-for-object-detection-b13320ec516b
(1, 3, 80, 80, 85) # anchor 0
(1, 3, 40, 40, 85) # anchor 1
(1, 3, 20, 20, 85) # anchor 2

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

YOLOv5 输出网格被展平并连接以形成单个输出

  • python ./models/export.py --weights ./weights/yolov5s.pt --img 640 --batch 1 --grid

在这里插入图片描述

gird 起作用的位置

    # Input
    img = torch.zeros(opt.batch_size, 3, *opt.img_size).to(device)  # image size(1,3,320,192) iDetection

    # Update model
    for k, m in model.named_modules():
        m._non_persistent_buffers_set = set()  # pytorch 1.6.0 compatibility
        if isinstance(m, models.common.Conv):  # assign export-friendly activations
            if isinstance(m.act, nn.Hardswish):
                m.act = Hardswish()
            elif isinstance(m.act, nn.SiLU):
                m.act = SiLU()
        # elif isinstance(m, models.yolo.Detect):
        #     m.forward = m.forward_export  # assign forward (optional)
    model.model[-1].export = not opt.grid  # set Detect() layer grid export
    y = model(img)  # dry run

在这里插入图片描述

在这里插入图片描述

detect独有属性export

在这里插入图片描述

在这里插入图片描述

class Detect(nn.Module):
    stride = None  # strides computed during build
    export = **  # onnx export  

    def __init__(self, nc=80, anchors=(), ch=()):  # detection layer
        super(Detect, self).__init__()
        self.nc = nc  # number of classes
        self.no = nc + 5  # number of outputs per anchor
        self.nl = len(anchors)  # number of detection layers
        self.na = len(anchors[0]) // 2  # number of anchors
        self.grid = [torch.zeros(1)] * self.nl  # init grid
        a = torch.tensor(anchors).float().view(self.nl, -1, 2)
        self.register_buffer('anchors', a)  # shape(nl,na,2)
        self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2))  # shape(nl,1,na,1,1,2)
        self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch)  # output conv

其他细节

class Focus(nn.Module):
    # Focus wh information into c-space
    def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True):  # ch_in, ch_out, kernel, stride, padding, groups
        super(Focus, self).__init__()
        self.conv = Conv(c1 * 4, c2, k, s, p, g, act)
        # self.contract = Contract(gain=2)

    # def forward(self, x):  # x(b,c,w,h) -> y(b,4c,w/2,h/2)
    #     return self.conv(torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1))
    #     # return self.conv(self.contract(x))

    def forward(self, x):  # x(b,c,w,h) -> y(b,4c,w/2,h/2)
        if torch.onnx.is_in_onnx_export():# TODO
            a, b = x[..., ::2, :].transpose(-2, -1), x[..., 1::2, :].transpose(-2, -1)
            c = torch.cat([a[..., ::2, :], b[..., ::2, :], a[..., 1::2, :], b[..., 1::2, :]], 1).transpose(-2, -1)
            return self.conv(c)
        else:
            return self.conv(torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1))

simplifier

  • 但我其实没有用这个,因为我安装这个后再次导出onnx出现了问题
  • https://github.com/daquexian/onnx-simplifier
  • pip install onnx-simplifier -i https://pypi.tuna.tsinghua.edu.cn/simple
  • python -m onnxsim ./weights/yolov5s.onnx ./weights/yolov5.onnx

在这里插入图片描述

使用带有 --grid 错误的 ONNX Simplifier 导出 https://github.com/ultralytics/yolov5/issues/2558

python ./models/export.py --weights ./weights/best.pt --img 640 --batch 1 https://www.cnblogs.com/ryzemagic/p/17089528.html

CG

  • python models/export.py --grid --simplify https://github.com/ultralytics/yolov5/issues/1597

  • b[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image) RuntimeError: a view of a leaf Variable that requires grad is being used in an in-place operation. https://blog.csdn.net/zhangxiangweide/article/details/125781044

  • 如何将YOLOV5 训练好的模型部署 输出?

  • 看到很多博客都用了这篇 https://huggingface.co/spaces/darylfunggg/xray-hand-joint-detection/blob/main/yolov5/export.py

  • ultralytics/yolov3: v9.6.0 - YOLOv5 v6.0 发布 YOLOv3 兼容性更新

first of all, onnx-simplifier need to be installed with pip install onnx-simplifier,
then, the simplification codes are:

    # ONNX export
    try:
        import onnx
        from onnxsim import simplify

        print('\nStarting ONNX export with onnx %s...' % onnx.__version__)
        f = opt.weights.replace('.pt', '.onnx')  # filename
        torch.onnx.export(model, img, f, verbose=False, opset_version=12, input_names=['images'],
                          output_names=['output'] if y is None else ['output'])

        # Checks
        onnx_model = onnx.load(f)  # load onnx model
        model_simp, check = simplify(onnx_model)
        assert check, "Simplified ONNX model could not be validated"
        onnx.save(model_simp, f)
        # print(onnx.helper.printable_graph(onnx_model.graph))  # print a human readable model
        print('ONNX export success, saved as %s' % f)
    except Exception as e:
        print('ONNX export failure: %s' % e)
 class Detect(nn.Module): 
     stride = None  # strides computed during build 
     export = False  # onnx export 
  
     def __init__(self, nc=80, anchors=(), ch=()):  # detection layer 
         super(Detect, self).__init__() 
         self.nc = nc  # number of classes 
         self.no = nc + 5  # number of outputs per anchor 
         self.nl = len(anchors)  # number of detection layers 
         self.na = len(anchors[0]) // 2  # number of anchors 
         self.grid = [torch.zeros(1)] * self.nl  # init grid 
         a = torch.tensor(anchors).float().view(self.nl, -1, 2) 
         self.register_buffer('anchors', a)  # shape(nl,na,2) 
         self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2))  # shape(nl,1,na,1,1,2) 
         self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch)  # output conv 
  
     def forward(self, x): 
         # x = x.copy()  # for profiling 
         z = []  # inference output 
         self.training |= self.export 
         for i in range(self.nl): 
             x[i] = self.m[i](x[i])  # conv 
             bs, _, ny, nx = x[i].shape  # x(bs,255,20,20) to x(bs,3,20,20,85) 
             x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous() 
  
             if not self.training:  # inference 
                 if self.grid[i].shape[2:4] != x[i].shape[2:4]: 
                     self.grid[i] = self._make_grid(nx, ny).to(x[i].device) 
  
                 y = x[i].sigmoid() 
                 y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i]  # xy 
                 y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i]  # wh 
                 z.append(y.view(bs, -1, self.no)) 
  
         return x if self.training else (torch.cat(z, 1), x) 

error: (-2:Unspecified error) Can’t create layer “onnx_node!Range_288” of type “Range” in function ‘getLayerInstance’

error: (-2:Unspecified error) Can’t create layer “onnx_node!ScatterND_378” of type “ScatterND” in function ‘getLayerInstance’

what(): Load model from /home/pdd/Documents/yolov5-5.0/weights/yolov5.onnx failed:Node (Mul_918) Op (Mul) [ShapeInferenceError] Incompatible dimensions

what(): Load model from /home/pdd/Documents/yolov5-5.0/weights/yolov5.onnx failed:Node (Mul_918) Op (Mul) [ShapeInferenceError] Incompatible dimensions

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/355489.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

智慧校园:校务助手微信小程序端源码

校园校务助手-智慧校园教师移动端校园校务助手微信小程序端也指智慧校园教师端微信小程序 它包括哪些功能呢&#xff1f;我来介绍一下。 智慧校园教师端微信小程序是基于原生开发 教师端登录界面①.设备管理、通知管理、图片管理、班级考勤 ②.综合素质评价、视频管理、请假…

SQL Server 2008新特性——更改跟踪

在大型的数据库应用中&#xff0c;经常会遇到部分数据的脱机和多个数据库的合并问题。比如现在有一个全省范围使用的应用程序&#xff0c;每个市都部署了单独的相同的应用程序服务器和数据库服务器&#xff0c;每个月需要将全省所有市的数据全部汇总起来用于出全省的报表&#…

微搭使用笔记(三) 数据模型介绍及初步使用

基于数据模型实现表单页面的生成和数据的保存、查看 表单应用是微搭的一个重要的使用场景&#xff0c;我们举下面一个简单的问卷调查的例子: 基于以上问卷&#xff0c;本文我们采取数据模型的方式生成表单页面并完成数据的保存及查看。 数据模型概述 先看下官方文档对于数据…

使用 TypeScript 的 CheckJS 为你的陈旧 JavaScript 项目续命

&#x1f64b; Why CheckJS? 让 JavaScript 项目也能享受到 TS 的类型推导等诸多好处。* 和直迁 TypeScript 相比&#xff0c;大大降低成本和风险&#xff0c;例如&#xff1a;&#x1f6a5; 使用方法 安装依赖、追加配置 # 为你的项目安装 TypeScript npm install typescri…

冰蝎4.0特征分析及流量检测思路

0 1、 冰蝎4.0介绍 冰蝎是一款基于Java开发的动态加密通信流量的新型Webshell客户端。老牌Webshell管理神器——中国菜刀的攻击流量特征明显&#xff0c;容易被各类安全设备检测&#xff0c;实际场景中越来越少使用&#xff0c;加密 Webshell 正变得日趋流行。 由于通信流量被…

JAVA时间类及JAVA8新时间类

文章目录Java旧时间类关系图![在这里插入图片描述](https://img-blog.csdnimg.cn/e2c2c26c841e40bdb9cc85d0fc4bc1df.png)GMT、时间戳、统一标准时间、时区Java时间类创建时间类示例java.text.DateFormat时间格式转换java.util.Calendar总结Java时间类Java8新时间类InstantCloc…

Vulnhub-DC-2实战靶场

Vulnhub-DC-2实战靶场 https://blog.csdn.net/ierciyuan/article/details/127560871 这次试试DC-2&#xff0c;目标是找到官方设置的5个flag。 一. 环境搭建 1. 准备工具 虚拟机Kali&#xff1a; 自备&#xff0c;我的kali的IP为192.168.3.129 靶场机&#xff1a; https…

接口和抽象类

接口(Interface)和抽象类(Abstract Class)是支持抽象类定义的两种机制。 1.抽象类 (1)说明 在Java中被abstract关键字修饰的类称为抽象类&#xff0c;被abstract关键字修饰的方法称为抽象方法&#xff0c;抽象方法只有方法的声明&#xff0c;没有方法体。抽象类是用来捕捉子…

CCNP350-401学习笔记(151-200题)

151、Which two LISP infrastructure elements are needed to support LISP to non-LISP internetworking? (Choose two.)A. PETR B. PITRC. MR D. MS E. ALT 152、In an SD-WAN deployment, which action in the vSmart controller responsible for? A. handle, maintain, …

一文搞懂C/C++内存管理原理与实现

C 语言内存管理指对系统内存的分配、创建、使用这一系列操作。在内存管理中&#xff0c;由于是操作系统内存&#xff0c;使用不当会造成毕竟麻烦的结果。本文将从系统内存的分配、创建出发&#xff0c;并且使用例子来举例说明内存管理不当会出现的情况及解决办法。 一、内存 …

[python入门㊽] - 自定义异常 raise 关键字

目录 ❤ 自定义抛出异常关键字 - raise ❤ 使用raise主动引发异常 ❤ raise 关键字的用法 ❤ 触发异常 ❤ 自定义异常类 在前面我们学过异常三个关键字分别是try、except 以及 finally 在编程过程中合理的使用异常可以使得程序正常的执行。有直接抛出异常的形式&…

【HTML】HTML 表格总结 ★★★ ( 表格标签 | 行标签 | 单元格标签 | 表格标签属性 | 表头单元格标签 | 表格标题标签 | 合并单元格 )

文章目录一、表格标签组成 ( 表格标签 | 行标签 | 单元格标签 )二、table 表格属性 ( border 属性 | align 属性 | width 属性 | height 属性 )三、表头单元格标签四、表格标题标签五、合并单元格1、合并单元格方式2、合并单元格顺序3、合并单元格流程六、合并单元格示例1、原始…

Linux之ping\kill\killall命令

参考视频&#xff1a;linux命令&#xff08;ping&#xff09;linux命令&#xff08;kill、killall&#xff09;Linux ping 命令用于检测主机。执行 ping 指令会使用 ICMP 传输协议&#xff0c;发出要求回应的信息&#xff0c;若远端主机的网络功能没有问题&#xff0c;就会回应…

Redis进阶:布隆过滤器(Bloom Filter)及误判率数学推导

1 缘起 有一次偶然间听到有同事在说某个项目中使用了布隆过滤器&#xff0c; 哎呦&#xff0c;我去&#xff0c;我竟然不知道啥是布隆过滤器&#xff0c; 这我哪能忍&#xff1f;其实&#xff0c;也可以忍&#xff0c;但是&#xff0c;可能有的面试官不能忍&#xff01;&#…

简介JVM

目录 一、内存分区 1、程序计数器 2、栈 3、堆 4、方法区 二、类加载 1、Loading 2、Linking Verification Preparation Resolution 3、Initializing 4、双亲委派模型 三、垃圾回收 1、如何判断为垃圾&#xff1f; 引入引用计数 可达性分析 2、如…

Transformer论文阅读:Swin Transformer算法笔记

标题&#xff1a;Swin Transformer: Hierarchical Vision Transformer using Shifted Windows 会议&#xff1a;ICCV2021 论文地址&#xff1a;https://ieeexplore.ieee.org/document/9710580/ 官方代码&#xff1a;https://github.com/microsoft/Swin-Transformer 作者单位&am…

[安装之2] 台式计算机加固态硬盘,台式机添加固态硬盘教程_台式主机固态硬盘怎么安装

固态硬盘是用固态电子存储芯片阵列制成的硬盘&#xff0c;也是电脑中比较常见的内存硬件&#xff0c;有些用户在使用电脑时候&#xff0c;由于内存不足导致系统运行较卡的情况&#xff0c;往往会选择添加固态硬盘来解决&#xff0c;那么台式主机固态硬盘怎么安装呢&#xff1f;…

shell脚本内调用另外一个shell脚本的几种方法

有时会在一个shell脚本(如test_call_other_shell.sh)中调用另外一个shell脚本(如parameter_usage.sh)&#xff0c;这里总结几种可行的方法&#xff0c;这些方法在linux上和windows上(通过Git Bash)均适用&#xff1a; 1.通过source: 运行在相同的进程&#xff0c;在test_…

CCIE重认证-300-401-拖图题全

拖图 拖图题 编程 snippet&#xff1b;192.168.5.0&#xff0c;mask 255.255.255.0&#xff1b;number是192.168.5.0&#xff1b;mask是255.255.255.0 snippets&#xff1b;edit-config对config&#xff0c;loopback对name 100&#xff0c;address对primary&#xff0c;mask…

广度优先搜索算法 - 迷宫找路

广度优先搜索算法1 思考问题1.1 这个迷宫需不需要指定入口和出口&#xff1f;2 先粗略实现2.1 源码2.2 源码解释3 优化代码3.1 优化读取文件部分3.2 增加错误处理4 再优化-让程序变得更加灵活4.1 用户外部可以循环输入入口和出口5 完整代码这是一个提问者的提出的问题&#xff…