瑞芯微RKNN开发·yolov5

官方预训练模型转换

  1. 下载yolov5-v6.0分支源码解压到本地,并配置基础运行环境。
  2. 下载官方预训练模型
  1. 进入yolov5-6.0目录下,新建文件夹weights,并将步骤2中下载的权重文件放进去。

  2. 修改models/yolo.py文件

     def forward(self, x):
         z = []  # inference output
         for i in range(self.nl):
             x[i] = self.m[i](x[i]).sigmoid()  # 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] or self.onnx_dynamic:
         #             self.grid[i], self.anchor_grid[i] = self._make_grid(nx, ny, i)
    
         #         y = x[i].sigmoid()
         #         if self.inplace:
         #             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
         #         else:  # for YOLOv5 on AWS Inferentia https://github.com/ultralytics/yolov5/pull/2953
         #             xy = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i]  # xy
         #             wh = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i]  # wh
         #             y = torch.cat((xy, wh, y[..., 4:]), -1)
         #         z.append(y.view(bs, -1, self.no))
    
         # return x if self.training else (torch.cat(z, 1), x)
         return x[0], x[1], x[2]
    
  3. 新建export_rknn.py文件

    import os
    import torch
    import onnx
    from onnxsim import simplify
    import onnxoptimizer
    import argparse
    from models.yolo import Detect, Model

    if name == 'main':
    parser = argparse.ArgumentParser()
    parser.add_argument('--weights', type=str, default='./weights/yolov5n.pt', help='initial weights path')

     #================================================================
     opt = parser.parse_args()
     print(opt)
    
     #Save Only weights
     ckpt = torch.load(opt.weights, map_location=torch.device('cpu'))
     torch.save(ckpt['model'].state_dict(), opt.weights.replace(".pt", "-model.pt"))
    
     #Load model without postprocessing
     new_model = Model("./models/{}.yaml".format(os.path.basename(opt.weights).strip(".pt")))
     new_model.load_state_dict(torch.load(opt.weights.replace(".pt", "-model.pt"), map_location=torch.device('cpu')), False)
     new_model.eval()
    
     #save to JIT script
     example = torch.rand(1, 3, 640, 640)
     traced_script_module = torch.jit.trace(new_model, example)
     traced_script_module.save(opt.weights.replace(".pt", "-jit.pt"))
    
     #save to onnx
     f = opt.weights.replace(".pt", ".onnx")
     torch.onnx.export(new_model, example, f, verbose=False, opset_version=12,
                             training=torch.onnx.TrainingMode.EVAL,
                             do_constant_folding=True,
                             input_names=['data'],
                             output_names=['out0','out1','out2'])
    
     #onnxsim
     model_simp, check = simplify(f)
     assert check, "Simplified ONNX model could not be validated"
     onnx.save(model_simp, opt.weights.replace(".pt", "-sim.onnx"))
    
     #optimize onnx
     passes = ["extract_constant_to_initializer", "eliminate_unused_initializer"]
     optimized_model = onnxoptimizer.optimize(model_simp, passes)
     onnx.checker.check_model(optimized_model)
     onnx.save(optimized_model, opt.weights.replace(".pt", "-op.onnx"))
     print('finished exporting onnx')
    
  4. 命令行执行python3 export_rknn.py脚本(默认为yolov5n.pt, 加--weights参数可指定权重),转换成功会输出一下信息, 转换后的模型存于权重同级目录(*-op.onnx后缀模型)

    Namespace(weights='./weights/yolov5n.pt')
    finished exporting onnx

RKNN开发板植入-模型转换篇

前期准备
  • RKNN开发环境(python)
  • rknn-toolkits2
详细流程
  1. 进入rknn-toolkits2/examples/onnx/yolov5示例目录下

  2. 修改test.py内容(按需修改ONNX_MODEL、RKNN_MODEL、IMG_PATH、DATASET等等超参数)

    def sigmoid(x):
    # return 1 / (1 + np.exp(-x))
    return x

  3. 命令行执行python3 test.py即可获取推理结果

RKNN开发板植入-NPU加载推理篇(C++)

后续放出代码

相关推荐
红色的山茶花9 小时前
YOLOv11-ultralytics-8.3.67部分代码阅读笔记-conv.py
笔记·深度学习·yolo
呆呆珝1 天前
RKNN_C++版本-YOLOV5
c++·人工智能·嵌入式硬件·yolo
FL16238631291 天前
汽车表面划痕刮伤检测数据集VOC+YOLO格式1221张1类别
深度学习·yolo·汽车
红色的山茶花2 天前
YOLOv10-1.1部分代码阅读笔记-train.py
笔记·深度学习·yolo
winxp-pic2 天前
自动化标注平台开源,基于 yolov8标注平台可本地部署
yolo·自动化
~啥也不会~3 天前
YOLOV11改进1-检测头篇
人工智能·深度学习·神经网络·yolo·目标检测
海里的鱼20223 天前
yolov11配置环境,实现OBB带方向目标检测
人工智能·yolo·目标检测·计算机视觉
Kacey Huang3 天前
YOLOv1、YOLOv2、YOLOv3目标检测算法原理与实战第十三天|YOLOv3实战、安装Typora
人工智能·算法·yolo·目标检测·计算机视觉
日日行不惧千万里4 天前
如何用YOLOv8训练一个识别安全帽的模型?
python·yolo
Coovally AI模型快速验证4 天前
MMYOLO:打破单一模式限制,多模态目标检测的革命性突破!
人工智能·算法·yolo·目标检测·机器学习·计算机视觉·目标跟踪