将yolo-fastest自训练模型转成rknn,并在rv1126下实现推理

2023-11-07 18:40

本文主要是介绍将yolo-fastest自训练模型转成rknn,并在rv1126下实现推理,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

关于如何用训练自己的yolo-fastest模型,上一篇博文已经说明,现记录先近期的实验。

环境:
系统:ubuntu1804
软件:rknn-toolkit 1.6.0(根据Rockchip_Quick_Start_RKNN_Toolkit_Vx.x.x_CN.pdf文档,部署好其他软件环境,opencv numpy tensorflow…等一系列依赖)
硬件:rv1126开发板(rp pro-rv1126 2+8)

一、模型转换
1、将准备好相应的文件
(1)yolo-fastest.cfg,该文件是自己训练时候修改过的配置文件
(2)yolo-fastest_best.weights, 自训练的权重文件
(3)ai_0006.jpg,需要推理的图片
(4)dataset.txt,该文件的内容是推理图片的路径,如下

./ai_0006.jpg

(5)trans-yolofastest.py,内容如下

from PIL import Image
import numpy as np
from matplotlib import pyplot as plt
import re
import math
import random
from rknn.api import RKNNif __name__ == '__main__':rknn=RKNN()print('load model...')ret = rknn.load_darknet(model='./yolo-fastest.cfg', weight='./yolo-fastest_best.weights')if ret != 0:print('load err...')exit(ret)print('done')rknn.config(reorder_channel='0,1,2', mean_values=[[0,0,0]],std_values=[[255,255,255]],target_platform=['rv1126'])print('building...')ret = rknn.build(do_quantization=True, dataset='./dataset.txt')if ret != 0:print('build fail!')exit(ret)print('done')ret = rknn.export_rknn('./yolo-fastest.rknn')if ret != 0:print('export fail!')exit(ret)exit(0)

2、对模型进行转换
(1)确保已经在文章开头描述的软件环境中
(2)运行模型转换代码

yolo-fast-zyj$ python3 trans-yolofastest.py

运行结果如下图,并查看路径下是否已经生成rknn模型
在这里插入图片描述
二、模型推理
1、准备好推理代码文件run_yolo-fastest_rknn.py,需要修改几个关键的地方
(1)GRID0、GRID1根据yolo算法的grid cell来修改;就是输出单元大小,例如yolov3是13x13,26x26,52x52。
(2)LISTSIZE=NUL_CLS+5,就是识别种类加5,比如yolov4识别80种类,则LISTSIZE=80+5,我这里只识别两个种类,所以填的LISTSIZE=7
(3)CLASSES为识别种类,也就是标注的时候填的类别名称
(4)masks和anchors根据yolo-fastest.cfg文件来填写
(5)配置目标NPU和ID,rknn.init_runtime(target=‘rv1126’,device_id=‘6de927292515e514’)
(6)图像处理outputs在处理时要注意输出的维度,有时候reshape会报异常是因为你前面的GRID0~2配置不对。
具体修改后的代码如下

from PIL import Image
import numpy as np
from matplotlib import pyplot as pltimport re
import math
import random
import cv2from rknn.api import RKNNGRID0 = 10
GRID1 = 20
GRID2 = 52
LISTSIZE = 7
SPAN = 3
NUM_CLS = 2
MAX_BOXES = 500
OBJ_THRESH = 0.5
NMS_THRESH = 0.6'''
CLASSES = ("person", "bicycle", "car","motorbike ","aeroplane ","bus ","train","truck ","boat","traffic light","fire hydrant","stop sign ","parking meter","bench","bird","cat","dog ","horse ","sheep","cow","elephant","bear","zebra ","giraffe","backpack","umbrella","handbag","tie","suitcase","frisbee","skis","snowboard","sports ball","kite","baseball bat","baseball glove","skateboard","surfboard","tennis racket","bottle","wine glass","cup","fork","knife ","spoon","bowl","banana","apple","sandwich","orange","broccoli","carrot","hot dog","pizza ","donut","cake","chair","sofa","pottedplant","bed","diningtable","toilet ","tvmonitor","laptop	","mouse	","remote ","keyboard ","cell phone","microwave ","oven ","toaster","sink","refrigerator ","book","clock","vase","scissors ","teddy bear ","hair drier", "toothbrush ")CLASSES = ("aeroplane","bicycle","bird","boat","bottle","bus","car","cat","chair","cow","diningtable","dog","horse","motorbike","person","pottedplant",
"sheep","sofa","train","tvmonitor")
'''
CLASSES = ("zyj","muzhuang")def sigmoid(x):return 1 / (1 + np.exp(-x))def process(input, mask, anchors):anchors = [anchors[i] for i in mask]grid_h, grid_w = map(int, input.shape[0:2])box_confidence = sigmoid(input[..., 4])box_confidence = np.expand_dims(box_confidence, axis=-1)box_class_probs = sigmoid(input[..., 5:])box_xy = sigmoid(input[..., :2])box_wh = np.exp(input[..., 2:4])box_wh = box_wh * anchorscol = np.tile(np.arange(0, grid_w), grid_w).reshape(-1, grid_w)row = np.tile(np.arange(0, grid_h).reshape(-1, 1), grid_h)col = col.reshape(grid_h, grid_w, 1, 1).repeat(3, axis=-2)row = row.reshape(grid_h, grid_w, 1, 1).repeat(3, axis=-2)grid = np.concatenate((col, row), axis=-1)box_xy += gridbox_xy /= (grid_w, grid_h)box_wh /= (416, 416)box_xy -= (box_wh / 2.)box = np.concatenate((box_xy, box_wh), axis=-1)return box, box_confidence, box_class_probsdef filter_boxes(boxes, box_confidences, box_class_probs):"""Filter boxes with object threshold.# Argumentsboxes: ndarray, boxes of objects.box_confidences: ndarray, confidences of objects.box_class_probs: ndarray, class_probs of objects.# Returnsboxes: ndarray, filtered boxes.classes: ndarray, classes for boxes.scores: ndarray, scores for boxes."""box_scores = box_confidences * box_class_probsbox_classes = np.argmax(box_scores, axis=-1)box_class_scores = np.max(box_scores, axis=-1)pos = np.where(box_class_scores >= OBJ_THRESH)boxes = boxes[pos]classes = box_classes[pos]scores = box_class_scores[pos]return boxes, classes, scoresdef nms_boxes(boxes, scores):"""Suppress non-maximal boxes.# Argumentsboxes: ndarray, boxes of objects.scores: ndarray, scores of objects.# Returnskeep: ndarray, index of effective boxes."""x = boxes[:, 0]y = boxes[:, 1]w = boxes[:, 2]h = boxes[:, 3]areas = w * horder = scores.argsort()[::-1]keep = []while order.size > 0:i = order[0]keep.append(i)xx1 = np.maximum(x[i], x[order[1:]])yy1 = np.maximum(y[i], y[order[1:]])xx2 = np.minimum(x[i] + w[i], x[order[1:]] + w[order[1:]])yy2 = np.minimum(y[i] + h[i], y[order[1:]] + h[order[1:]])w1 = np.maximum(0.0, xx2 - xx1 + 0.00001)h1 = np.maximum(0.0, yy2 - yy1 + 0.00001)inter = w1 * h1ovr = inter / (areas[i] + areas[order[1:]] - inter)inds = np.where(ovr <= NMS_THRESH)[0]order = order[inds + 1]keep = np.array(keep)return keepdef yolov4_post_process(input_data):# yolov3# masks = [[6, 7, 8], [3, 4, 5], [0, 1, 2]]# anchors = [[10, 13], [16, 30], [33, 23], [30, 61], [62, 45],#          [59, 119], [116, 90], [156, 198], [373, 326]]# yolov3-tiny# masks = [[3, 4, 5], [0, 1, 2]]# anchors = [[10, 14], [23, 27], [37, 58], [81, 82], [135, 169], [344, 319]]#yolov4#masks = [[6, 7, 8], [3, 4, 5], [0, 1, 2]]#anchors = [[12, 16], [19, 36], [40, 28], [36, 75], [76, 55], [72, 146], [142, 110], [192, 243], [459, 401]]#yolov4-tiny#masks = [[1, 2, 3], [3, 4, 5]]#anchors = [[10, 14], [23, 27], [37, 58], [81, 82], [135, 169], [344, 319]]#yolo-fastestmasks = [[0, 1, 2], [3, 4, 5]]anchors = [[26, 48], [67, 84], [72, 175], [189, 126], [137, 236], [265, 259]]boxes, classes, scores = [], [], []for input,mask in zip(input_data, masks):b, c, s = process(input, mask, anchors)b, c, s = filter_boxes(b, c, s)boxes.append(b)classes.append(c)scores.append(s)boxes = np.concatenate(boxes)classes = np.concatenate(classes)scores = np.concatenate(scores)nboxes, nclasses, nscores = [], [], []for c in set(classes):inds = np.where(classes == c)b = boxes[inds]c = classes[inds]s = scores[inds]keep = nms_boxes(b, s)nboxes.append(b[keep])nclasses.append(c[keep])nscores.append(s[keep])if not nclasses and not nscores:return None, None, Noneboxes = np.concatenate(nboxes)classes = np.concatenate(nclasses)scores = np.concatenate(nscores)return boxes, classes, scoresdef draw(image, boxes, scores, classes):"""Draw the boxes on the image.# Argument:image: original image.boxes: ndarray, boxes of objects.classes: ndarray, classes of objects.scores: ndarray, scores of objects.all_classes: all classes name."""for box, score, cl in zip(boxes, scores, classes):x, y, w, h = boxprint('class: {}, score: {}'.format(CLASSES[cl], score))print('box coordinate left,top,right,down: [{}, {}, {}, {}]'.format(x, y, x+w, y+h))x *= image.shape[1]y *= image.shape[0]w *= image.shape[1]h *= image.shape[0]top = max(0, np.floor(x + 0.5).astype(int))left = max(0, np.floor(y + 0.5).astype(int))right = min(image.shape[1], np.floor(x + w + 0.5).astype(int))bottom = min(image.shape[0], np.floor(y + h + 0.5).astype(int))# print('class: {}, score: {}'.format(CLASSES[cl], score))# print('box coordinate left,top,right,down: [{}, {}, {}, {}]'.format(top, left, right, bottom))cv2.rectangle(image, (top, left), (right, bottom), (255, 0, 0), 2)cv2.putText(image, '{0} {1:.2f}'.format(CLASSES[cl], score),(top, left - 6),cv2.FONT_HERSHEY_SIMPLEX,0.6, (0, 0, 255), 2)if __name__ == '__main__':# Create RKNN objectrknn = RKNN()# Load tensorflow modelprint('--> Loading model')ret = rknn.load_rknn('./yolo-fastest.rknn')if ret != 0:print('load rknn model failed')exit(ret)print('done')# Set inputsim_file = 'ai_0006.jpg'img = cv2.imread(im_file)orig_img = cv2.resize(img, (320,320))img = cv2.cvtColor(orig_img, cv2.COLOR_BGR2RGB)# init runtime environmentprint('--> Init runtime environment')ret = rknn.init_runtime(target='rv1126',device_id='6de927292515e514')if ret != 0:print('Init runtime environment failed')exit(ret)print('done')# Inferenceprint('--> Running model')outputs = rknn.inference(inputs=[img])rknn.release()#input0_data = np.reshape(outputs[2], (SPAN, LISTSIZE, GRID0, GRID0))input1_data = np.reshape(outputs[1], (SPAN, LISTSIZE, GRID1, GRID1))input2_data = np.reshape(outputs[0], (SPAN, LISTSIZE, GRID0, GRID0))input_data = []#input_data.append(np.transpose(input0_data, (2, 3, 0, 1)))input_data.append(np.transpose(input1_data, (2, 3, 0, 1)))input_data.append(np.transpose(input2_data, (2, 3, 0, 1)))boxes, classes, scores = yolov4_post_process(input_data)if boxes is not None:draw(orig_img, boxes, scores, classes)cv2.imshow("results",orig_img)cv2.waitKeyEx(0)print('done')exit(0)

2、运行代码及结果如下:

yolo-fast-zyj$ pyhton3 run_yolo-fastest_rknn.py

在这里插入图片描述
三、总结
倒腾了好几次,最后终于搞好了。最主要还是要到官方去找下资料,细心点就OK了。

这篇关于将yolo-fastest自训练模型转成rknn,并在rv1126下实现推理的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/365557

相关文章

大模型研发全揭秘:客服工单数据标注的完整攻略

在人工智能(AI)领域,数据标注是模型训练过程中至关重要的一步。无论你是新手还是有经验的从业者,掌握数据标注的技术细节和常见问题的解决方案都能为你的AI项目增添不少价值。在电信运营商的客服系统中,工单数据是客户问题和解决方案的重要记录。通过对这些工单数据进行有效标注,不仅能够帮助提升客服自动化系统的智能化水平,还能优化客户服务流程,提高客户满意度。本文将详细介绍如何在电信运营商客服工单的背景下进行

hdu1043(八数码问题,广搜 + hash(实现状态压缩) )

利用康拓展开将一个排列映射成一个自然数,然后就变成了普通的广搜题。 #include<iostream>#include<algorithm>#include<string>#include<stack>#include<queue>#include<map>#include<stdio.h>#include<stdlib.h>#include<ctype.h>#inclu

Andrej Karpathy最新采访:认知核心模型10亿参数就够了,AI会打破教育不公的僵局

夕小瑶科技说 原创  作者 | 海野 AI圈子的红人,AI大神Andrej Karpathy,曾是OpenAI联合创始人之一,特斯拉AI总监。上一次的动态是官宣创办一家名为 Eureka Labs 的人工智能+教育公司 ,宣布将长期致力于AI原生教育。 近日,Andrej Karpathy接受了No Priors(投资博客)的采访,与硅谷知名投资人 Sara Guo 和 Elad G

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

【Prometheus】PromQL向量匹配实现不同标签的向量数据进行运算

✨✨ 欢迎大家来到景天科技苑✨✨ 🎈🎈 养成好习惯,先赞后看哦~🎈🎈 🏆 作者简介:景天科技苑 🏆《头衔》:大厂架构师,华为云开发者社区专家博主,阿里云开发者社区专家博主,CSDN全栈领域优质创作者,掘金优秀博主,51CTO博客专家等。 🏆《博客》:Python全栈,前后端开发,小程序开发,人工智能,js逆向,App逆向,网络系统安全,数据分析,Django,fastapi

让树莓派智能语音助手实现定时提醒功能

最初的时候是想直接在rasa 的chatbot上实现,因为rasa本身是带有remindschedule模块的。不过经过一番折腾后,忽然发现,chatbot上实现的定时,语音助手不一定会有响应。因为,我目前语音助手的代码设置了长时间无应答会结束对话,这样一来,chatbot定时提醒的触发就不会被语音助手获悉。那怎么让语音助手也具有定时提醒功能呢? 我最后选择的方法是用threading.Time

Android实现任意版本设置默认的锁屏壁纸和桌面壁纸(两张壁纸可不一致)

客户有些需求需要设置默认壁纸和锁屏壁纸  在默认情况下 这两个壁纸是相同的  如果需要默认的锁屏壁纸和桌面壁纸不一样 需要额外修改 Android13实现 替换默认桌面壁纸: 将图片文件替换frameworks/base/core/res/res/drawable-nodpi/default_wallpaper.*  (注意不能是bmp格式) 替换默认锁屏壁纸: 将图片资源放入vendo

C#实战|大乐透选号器[6]:实现实时显示已选择的红蓝球数量

哈喽,你好啊,我是雷工。 关于大乐透选号器在前面已经记录了5篇笔记,这是第6篇; 接下来实现实时显示当前选中红球数量,蓝球数量; 以下为练习笔记。 01 效果演示 当选择和取消选择红球或蓝球时,在对应的位置显示实时已选择的红球、蓝球的数量; 02 标签名称 分别设置Label标签名称为:lblRedCount、lblBlueCount

Retrieval-based-Voice-Conversion-WebUI模型构建指南

一、模型介绍 Retrieval-based-Voice-Conversion-WebUI(简称 RVC)模型是一个基于 VITS(Variational Inference with adversarial learning for end-to-end Text-to-Speech)的简单易用的语音转换框架。 具有以下特点 简单易用:RVC 模型通过简单易用的网页界面,使得用户无需深入了

透彻!驯服大型语言模型(LLMs)的五种方法,及具体方法选择思路

引言 随着时间的发展,大型语言模型不再停留在演示阶段而是逐步面向生产系统的应用,随着人们期望的不断增加,目标也发生了巨大的变化。在短短的几个月的时间里,人们对大模型的认识已经从对其zero-shot能力感到惊讶,转变为考虑改进模型质量、提高模型可用性。 「大语言模型(LLMs)其实就是利用高容量的模型架构(例如Transformer)对海量的、多种多样的数据分布进行建模得到,它包含了大量的先验