旭日x3派部署自己训练的模型(安全帽识别、视频流推理、yolov5-6.2)

旭日x3派部署自己训练的模型(安全帽识别、视频流推理、yolov5-6.2)windows,框架pytorch,python3.7

    • 效果
    • 模型训练
    • 模型转换
      • 1、pt模型文件转onnx
      • 2、检查onnx模型
      • 3、准备校准数据
      • 4、onnx转bin
    • 上板视频流推理
      • 1、图片推理
      • 2、视频流推理

效果

模型训练

进官网可克隆yolov5:https://github.com/ultralytics/yolov5/tree/v6.2,这里选择6.2。数据集直接使用现成的:安全帽识别。
整个训练过程参考:炮哥带你学
需要注意的是这里是6.2,参考博客是5.0,过程会有一些不同,训练时报错直接百度即可。
最终需要的pt文件位于:runs/train/exp/weights下:在这里插入图片描述

模型转换

docker环境搭建及启动、挂载文件参考上一篇博客:https://blog.csdn.net/m0_71523511/article/details/136546588

1、pt模型文件转onnx

①修改export.py文件:
在这里插入图片描述
②导出onnx:
运行export.py文件:
在这里插入图片描述

2、检查onnx模型

在挂载目录中的BPUCodes文件夹中新建文件夹yolov5-6.2_hat_2,将上一步得到的onnx模型复制一份进来。
在这里插入图片描述

打开docker桌面版,按下win+R进行命令符,在命令符中进入docker并将一些文件挂载进去,这里的命令是上一篇一样的:

docker run -it --rm -v "G:\bushu_xiangguan\horizon_xj3_open_explorer_v2.2.3a_20220701":/open_explorer -v "G:\bushu_xiangguan\Codes\dateset":/data/horizon_x3/data -v "G:\bushu_xiangguan\BPUCodes":/data/horizon_x3/codes openexplorer/ai_toolchain_centos_7:v1.13.6

在这里插入图片描述
输入以下指令进行检查:

hb_mapper checker --model-type onnx --march bernoulli2 --model best.onnx

在这里插入图片描述

3、准备校准数据

在yolov5-6.2_hat_2文件夹下新建prepare_calibration存放待校准数据,新建一个prepare_calibration_data.py文件,执行之后就可以在calibration_data下生成校准数据。

# prepare_calibration_data.py
import os
import cv2
import numpy as npsrc_root = '/data/horizon_x3/codes/yolov5-6.2_hat_2/prepare_calibration'    #存放待校准图片的文件夹
cal_img_num = 100  
dst_root = '/data/horizon_x3/codes/yolov5-6.2_hat_2/calibration_data'     #存放输出校准数据的文件夹num_count = 0
img_names = []
for src_name in sorted(os.listdir(src_root)):if num_count > cal_img_num:breakimg_names.append(src_name)num_count += 1if not os.path.exists(dst_root):os.system('mkdir {0}'.format(dst_root))def imequalresize(img, target_size, pad_value=127.):target_w, target_h = target_sizeimage_h, image_w = img.shape[:2]img_channel = 3 if len(img.shape) > 2 else 1scale = min(target_w * 1.0 / image_w, target_h * 1.0 / image_h)new_h, new_w = int(scale * image_h), int(scale * image_w)resize_image = cv2.resize(img, (new_w, new_h))pad_image = np.full(shape=[target_h, target_w, img_channel], fill_value=pad_value)dw, dh = (target_w - new_w) // 2, (target_h - new_h) // 2pad_image[dh:new_h + dh, dw:new_w + dw, :] = resize_imagereturn pad_imagefor each_imgname in img_names:img_path = os.path.join(src_root, each_imgname)img = cv2.imread(img_path)  # BRG, HWCimg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)  # RGB, HWCimg = imequalresize(img, (640, 640))      #训练时是多少就写多少img = np.transpose(img, (2, 0, 1))  # RGB, CHWdst_path = os.path.join(dst_root, each_imgname + '.rgbchw')print("write:%s" % dst_path)img.astype(np.uint8).tofile(dst_path) print('finish')

执行python3 prepare_calibration_data.py即可:
在这里插入图片描述
此时目录结构如下:
在这里插入图片描述

4、onnx转bin

转换模型需要yaml参数文件,具体含义参考https://blog.csdn.net/Zhaoxi_Li/article/details/125516265
在yolov5-6.2_hat_2文件夹下新建model_convert.yaml文件:

model_parameters:onnx_model: './best.onnx' output_model_file_prefix: 'hat_yolov5_6.2' march: 'bernoulli2'
input_parameters:input_type_train: 'rgb'input_layout_train: 'NCHW'input_type_rt: 'nv12'norm_type: 'data_scale'scale_value: 0.003921568627451input_layout_rt: 'NHWC'
calibration_parameters:cal_data_dir: './calibration_data' calibration_type: 'max'max_percentile: 0.9999
compiler_parameters:compile_mode: 'latency'optimize_level: 'O3'debug: Falsecore_num: 2 

然后执行:hb_mapper makertbin --config model_convert.yaml --model-type onnx:
在这里插入图片描述
此时自动生成model_output文件夹,里面包含了bin模型:
在这里插入图片描述

上板视频流推理

1、图片推理

在这里插入图片描述
https://developer.horizon.cc/forumDetail/112555549341653639,这篇帖子介绍了cython,将上图有的文件全部拷到板端中,包括前面转成的bin文件。如下进行推理:在这里插入图片描述
推理结果:
在这里插入图片描述
我的这个模型只训练了五轮,对图片的识别率不错,后续的视频流推理容易出错,轮次多点应该就好了。

2、视频流推理

自己新建一个py文件,代码如下:

import numpy as np
import cv2
import os
from hobot_dnn import pyeasy_dnn as dnn
from bputools.format_convert import imequalresize, bgr2nv12_opencvimport lib.pyyolotools as yolotoolsdef get_hw(pro):if pro.layout == "NCHW":return pro.shape[2], pro.shape[3]else:return pro.shape[1], pro.shape[2]def format_yolov5(frame):row, col, _ = frame.shape_max = max(col, row)result = np.zeros((_max, _max, 3), np.uint8)result[0:row, 0:col] = framereturn result# 加载模型和设置参数
model_path = 'hat_yolov5_6.2.bin'
classes_name_path = 'coco_classes.names'
models = dnn.load(model_path)
model_h, model_w = get_hw(models[0].inputs[0].properties)
print("Model Height:", model_h, "Model Width:", model_w)thre_confidence = 0.4
thre_score = 0.25
thre_nms = 0.45
colors = [(255, 255, 0), (0, 255, 0), (0, 255, 255), (255, 0, 0)]# 打开摄像头
cap = cv2.VideoCapture(8)  # 使用第一个摄像头(如果有多个摄像头,可能需要更改参数)# 主循环:读取帧,进行目标检测,显示结果
while True:ret, frame = cap.read()  # 读取一帧图像if not ret:print("Error: Couldn't capture frame")breakinputImage = format_yolov5(frame)img = imequalresize(inputImage, (model_w, model_h))nv12 = bgr2nv12_opencv(img)t1 = cv2.getTickCount()outputs = models[0].forward(nv12)t2 = cv2.getTickCount()outputs = outputs[0].bufferprint('Inference time: {0} ms'.format((t2 - t1) * 1000 / cv2.getTickFrequency()))image_width, image_height, _ = inputImage.shapefx, fy = image_width / model_w, image_height / model_ht1 = cv2.getTickCount()class_ids, confidences, boxes = yolotools.pypostprocess_yolov5(outputs[0][:, :, 0], fx, fy,thre_confidence, thre_score, thre_nms)t2 = cv2.getTickCount()print('Post-processing time: {0} ms'.format((t2 - t1) * 1000 / cv2.getTickFrequency()))with open(classes_name_path, "r") as f:class_list = [cname.strip() for cname in f.readlines()]for (classid, confidence, box) in zip(class_ids, confidences, boxes):color = colors[int(classid) % len(colors)]cv2.rectangle(frame, box, color, 2)cv2.rectangle(frame, (box[0], box[1] - 20), (box[0] + box[2], box[1]), color, -1)#cv2.putText(frame, str(classid), (box[0], box[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, .5, (0, 0, 0))cv2.putText(frame, class_list[classid], (box[0], box[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, .5, (0,0,0))cv2.imshow('frame', frame)  # 显示帧if cv2.waitKey(1) & 0xFF == ord('q'):  # 按下 'q' 键退出循环break# 释放资源并关闭窗口
cap.release()
cv2.destroyAllWindows()

这个需要通过hdmi将开发板与显示屏连接,才能看到实时画面,大概10帧左右,模型还可以简化,15帧应该很轻松。
最终效果如本文开头所示。

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

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

构建部署_Docker常用命令

构建部署_Docker常见命令 启动命令镜像命令容器命令 启动命令 启动docker:systemctl start docker 停止docker:systemctl stop docker 重启docker:systemctl restart docker 查看docker状态:systemctl status docker 开机启动&…

计算机网络——物理层(奈氏准则和香农定理)

计算机网络——物理层(奈氏准则和香农定理) 失真码间串扰奈氏准则(奈奎斯特定理)极限数据率 噪声信噪比香农定理奈氏准则和香农定理的区别 前面我们已经了解一些数据通信的基本知识,没有看过上一篇得小伙伴可以点击这里…

【刷题训练】LeetCode:557. 反转字符串中的单词 III

557. 反转字符串中的单词 III 题目要求 示例 1: 输入:s “Let’s take LeetCode contest” 输出:“s’teL ekat edoCteeL tsetnoc” 示例 2: 输入: s “Mr Ding” 输出:“rM gniD” 思路: 第一步&am…

git stash clear/drop 后如何恢复

git stash clear/drop 后代码如何恢复 事故经过 切换分支前有修改未提交的代码,使用 git stash 存储了当前的代码切换分支再返回自己开发的分支本来要进行 git stash pop 操作,然后 git stash list 发现有好几个 stash记录于是想清除没用的 stash 记录…

Ps:图层样式 - 渐变叠加

渐变叠加 Gradient Overly主要用于在图层上添加颜色渐变效果。 可为同一图层添加多达 10 个渐变叠加。 渐变 Gradient 混合模式 Blend Mode 设置渐变叠加效果与图层的混合模式。 默认为“正常”,表示不混合。 仿色 Dither 默认勾选,可使渐变过渡更加平滑…

SpringCloud Sleuth 分布式请求链路跟踪

一、前言 接下来是开展一系列的 SpringCloud 的学习之旅,从传统的模块之间调用,一步步的升级为 SpringCloud 模块之间的调用,此篇文章为第十篇,即介绍 Sleuth 分布式请求链路跟踪。 二、概述 2.1 出现的原因 在微服务框架中&…

git 安装、创建仓库、常用命令、克隆下载、上传项目、删除分支 -- 一篇文章总结

一、git安装 1、git安装地址:https://git-scm.com/downloads 2、选择操作系统 3、安装自己系统对应的操作位数 4、等待下载完,一路next安装就可以了 5、安装完成后,在任意文件夹点击右键,看到下图说明安装成功 二、创建仓库 1…

服务器数据恢复—服务器硬盘灯显示红色的数据恢复案例

服务器数据恢复环境&故障: 一台服务器中有一组由多块硬盘组建的raid阵列,在运行过程中服务器突然崩溃,管理员检查服务器发现该服务器raid阵列中有两块硬盘的指示灯显示红色。于是,管理员重启服务器,服务器重启后&a…

对OceanBase进行 sysbench 压测前,如何用 obdiag巡检

有一些用户想对 OceanBase 进行 sysbench 压测,并向我询问是否需要对数据库的各种参数进行调整。我想起有一个工具 obdiag ,具备对集群进行巡检的功能。因此,我正好借此机会试用一下这个工具。 obdiag 功能的比较丰富,详细情况可参…

【兆易创新GD32H759I-EVAL开发板】图像处理加速器(IPA)的应用

GD32H7系列的IPA(Image Pixel Accelerator)是一个高效的图像处理硬件加速器,专门设计用于加速图像处理操作,如像素格式转换、图像旋转、缩放等。它的优势在于能够利用硬件加速来实现这些操作,相比于软件实现&#xff0…

如何搭建“Docker Registry私有仓库,在CentOS7”?

1、下载镜像Docker Registry docker pull registry:2.7.1 2、运行私有库Registry docker run -d -p 5000:5000 -v ${PWD}/registry:/var/lib/registry --restartalways --name registry registry:2.7.1 3、拉取镜像 docker pull busybox 4、打标签,修改IP&#x…

【兔子机器人】实现从初始状态到站立

一、遥想星空up主的方法 由于我有卡位结构,无法做到劈腿,而且底盘也不一样,无法使用此方法 但是其代码思想是可以借鉴的。 参考视频: 【【开源啦!】无刷轮腿平衡机器人】 【精准空降到 01:16】 https://www.bilibili…