首页 > 编程语言 >yolov5 onnx部署模型代码,python版本

yolov5 onnx部署模型代码,python版本

时间:2024-08-10 20:50:10浏览次数:8  
标签:box yolov5 name img python onnx input path cls

`

import os
import cv2
import numpy as np
import onnxruntime
import time
from tqdm import tqdm
from matplotlib import pyplot as plt
import math
CLASSES = ['jump_cap2', 'jump_cap4']

class YOLOV5():
def init(self, onnxpath):
self.onnx_session = onnxruntime.InferenceSession(onnxpath, providers=['CPUExecutionProvider'])
self.input_name = self.get_input_name()
self.output_name = self.get_output_name()

def get_input_name(self):
    input_name = []
    for node in self.onnx_session.get_inputs():
        input_name.append(node.name)
    return input_name

def get_output_name(self):
    output_name = []
    for node in self.onnx_session.get_outputs():
        output_name.append(node.name)
    return output_name


def get_input_feed(self, img_tensor):
    input_feed = {}
    for name in self.input_name:
        input_feed[name] = img_tensor
    return input_feed


def inference(self, img_path):
    img = cv2.imread(img_path)
    img_o=img.copy()
    or_img = cv2.resize(img, (640, 640))        # 640x640
    img = or_img[:, :, ::-1].transpose(2, 0, 1)  # BGR2RGB��HWC2CHW
    img = img.astype(dtype=np.float32)
    img /= 255.0
    img = np.expand_dims(img, axis=0)
    input_feed = self.get_input_feed(img)
    pred = self.onnx_session.run(None, input_feed)[0]
    return pred, img_o

def nms(dets, thresh):
x1 = dets[:, 0]
y1 = dets[:, 1]
x2 = dets[:, 2]
y2 = dets[:, 3]

areas = (y2 - y1 + 1) * (x2 - x1 + 1)
scores = dets[:, 4]
keep = []
index = scores.argsort()[::-1]

while index.size > 0:
    i = index[0]
    keep.append(i)

    x11 = np.maximum(x1[i], x1[index[1:]])
    y11 = np.maximum(y1[i], y1[index[1:]])
    x22 = np.minimum(x2[i], x2[index[1:]])
    y22 = np.minimum(y2[i], y2[index[1:]])

    w = np.maximum(0, x22 - x11 + 1)
    h = np.maximum(0, y22 - y11 + 1)

    overlaps = w * h

    ious = overlaps / (areas[i] + areas[index[1:]] - overlaps)
    idx = np.where(ious <= thresh)[0]
    index = index[idx + 1]
return keep

def xywh2xyxy(x):
# [x, y, w, h] to [x1, y1, x2, y2]
y = np.copy(x)
y[:, 0] = x[:, 0] - x[:, 2] / 2
y[:, 1] = x[:, 1] - x[:, 3] / 2
y[:, 2] = x[:, 0] + x[:, 2] / 2
y[:, 3] = x[:, 1] + x[:, 3] / 2
return y

def filter_box(org_box, conf_thres, iou_thres):

org_box = np.squeeze(org_box)
conf = org_box[..., 4] > conf_thres
box = org_box[conf == True]

cls_cinf = box[..., 5:]
cls = []
for i in range(len(cls_cinf)):
    cls.append(int(np.argmax(cls_cinf[i])))
all_cls = list(set(cls))
output = []


for i in range(len(all_cls)):
    curr_cls = all_cls[i]
    curr_cls_box = []
    curr_out_box = []
    for j in range(len(cls)):
        if cls[j] == curr_cls:
            box[j][5] = curr_cls
            curr_cls_box.append(box[j][:6])
    curr_cls_box = np.array(curr_cls_box)

    curr_cls_box = xywh2xyxy(curr_cls_box)
    curr_out_box = nms(curr_cls_box, iou_thres)
    for k in curr_out_box:
        output.append(curr_cls_box[k])
output = np.array(output)
return output

def draw(image, box_data):

boxes = box_data[..., :4].astype(np.int32)
scores = box_data[..., 4]
classes = box_data[..., 5].astype(np.int32)

print("132:boxes",boxes)
img_height_o=image.shape[0]
img_width_o=image.shape[1]
x_ratio=img_width_o/640
y_ratio=img_height_o/640

max_area = 0
best_rec = None
best_cls = None
for box, score, cl in zip(boxes, scores, classes):

    top, left, right, bottom = box

    top=int(top*x_ratio)
    right=int(right*x_ratio)
    left=int(left*y_ratio)
    bottom=int(bottom*y_ratio)

    print("149:top",top)
    print("149:right",right)
    print("149:left",left)
    print("149:bottom",bottom)

    w = top-right
    h = left -bottom
    area = w*h
    if area > max_area:
        max_area = area
        best_rec = [top, left, right, bottom]
        best_cls = cl
top, left, right, bottom = best_rec
cv2.rectangle(image, (top, left), (right, bottom), (255, 0, 0), 1)

print("164:best_rec",best_rec)
# print("166:best_cls",best_cls)

# plt.imshow(image)
# plt.show()

return best_rec, best_cls

def onnx_infer(input, output, onnx_path, pin_rec_list, single_inference=False, conf_thres=0.1, iou_thres=0.1):

if single_inference:
    model = YOLOV5(onnx_path)
    outbox, or_img = model.inference(input)
    outbox = filter_box(outbox, conf_thres, iou_thres)

    best_rec, best_cls = draw(or_img, outbox)
    file_name = input.split('/')[-1]
    output = os.path.join(output, file_name)
    cv2.imwrite(output, or_img)


else:
    img_list = os.listdir(input)
    for img in tqdm(img_list):
        img_path = os.path.join(input, img)
        model = YOLOV5(onnx_path)
        outbox, or_img = model.inference(img_path)
        outbox = filter_box(outbox, conf_thres, iou_thres)
        best_rec = []
        try:
            best_rec, best_cls = draw(or_img, outbox)
        except Exception as e:
            continue
        file_name = img.split('/')[-1]
        save_path = os.path.join(output, file_name)
        cv2.imwrite(save_path, or_img)

if name == "main":

start_time = time.time()
onnx_path = 'model/best.onnx'
model = YOLOV5(onnx_path)
img_dir_path = 'testpicture'
# img_dir_path = 'testpic'
img_list = os.listdir(img_dir_path)
save_dir_path = 'detimg/'

if not os.path.exists(save_dir_path):
    os.makedirs(save_dir_path)
for img_name in tqdm(img_list):
    img_path = os.path.join(img_dir_path, img_name)
    output, or_img = model.inference(img_path)
    outbox = filter_box(output, 0.25, 0.7)
    try:
        draw(or_img, outbox)


    except Exception as e:
        print(img_name)
        continue
    save_img_path = os.path.join(save_dir_path, img_name)
    cv2.imwrite(save_img_path, or_img)

end_time = time.time()
print('inference time: {:.2f}'.format(end_time - start_time))

pass`

标签:box,yolov5,name,img,python,onnx,input,path,cls
From: https://www.cnblogs.com/littlecute555/p/18352766

相关文章

  • Python中yaml模块的使用教程
    一、yaml文件介绍yaml是一个专门用来写配置文件的语言。1.yaml文件规则区分大小写;使用缩进表示层级关系;使用空格键缩进,而非Tab键缩进缩进的空格数目不固定,只需要相同层级的元素左侧对齐;文件中的字符串不需要使用引号标注,但若字符串包含有特殊字符则需用引号标注;注释标识......
  • python装饰器的集中使用姿势
    在Python中,装饰器是一种十分强大并且好用的语法,一些重复的代码使用装饰器语法的话能够使代码更容易理解及阅读。因此在这里简单总结了一下Python中装饰器的几种用法以及需要注意的事情。一、在装饰器中获取被装饰函数的参数假设我们在开发web的时候,需要做反爬。要判断接口的访......
  • Python类中__del__()、__call__()、__repr__()、__new__()、__hash__()方法
    1.__del__()销毁魔术方法触发时机:当一个对象在内存中被销毁的时候自动执行参数:至少有一个self,接收对象返回值:无作用:在对象销毁的时候做一些操作注意:程序自动调用此方法,不需要我们手动调用。classCat:def__init__(self,name):print("--init--")s......
  • Python字典的高级用法
    一、collections中defaultdict的使用1.字典的键映射多个值将下面的列表转成字典l=[('a',2),('b',3),('a',1),('b',4),('a',3),('a',1),('b',3)]一个字典就是一个键对应一个单值的映射,而上面的列表中有相同键。如果你想要一个键映射多个值,那么就需要将这多个值放到另外......
  • 2024最新版PyCharm下载安装详细教程,Python环境配置和使用指南,零基础保姆级教程
    一、简介PyCharm是一款PythonIDE,其带有一整套可以帮助用户在使用Python语言开发时提高其效率的工具,比如,调试、语法高亮、Project管理、代码跳转、智能提示、自动完成、单元测试、版本控制等等。此外,该IDE提供了一些高级功能,以用于支持Django框架下的专业Web开发。Pytho......
  • python3使用pyVmomi获取vCenter中告警信息语音告警
    原创文档编写不易,未经许可请勿转载,目前仅发布于博客园,其他平台均为非法转载。文档中有疑问的可以邮件联系我文章。邮箱:[email protected]一、说明文章分享在pyVmomi获取vCenter中的告警信息,对red级别的告警信息进行本地语音告警,记录告警信息到本地txt文件后清空当前vCenter上的......
  • [附开题]flask框架重庆美食网站的设计与实现kt945(源码+论文+python)
    本系统(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。系统程序文件列表开题报告内容研究背景重庆,作为中国的美食之都,以其独特的地理环境和悠久的历史文化孕育了众多令人垂涎欲滴的特色美食。从麻辣鲜香的火锅到酥脆可口的重庆小面,每......
  • [附开题]flask框架助农特色农产品销售系统i7957(源码+论文+python)
    本系统(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。系统程序文件列表开题报告内容研究背景在乡村振兴战略的大背景下,特色农产品的销售成为促进农村经济发展、农民增收的重要途径。然而,传统农产品销售模式受限于信息不对称、渠道单......
  • Python爬虫常用库的安装及环境配置(widows系统)
    Python常用库的安装urllib、re这两个库是Python的内置库,直接使用方法import导入即可。requests这个库是请求的库。我们需要使用执行文件pip3来进行安装。文件处于C:\Python36\Scripts下,我们可以先将此路径设为环境变量。在命令行中输入pip3installrequests进行安装......
  • Python 潮流周刊#64:Python 的函数调用还很慢么?(摘要)
    本周刊由Python猫出品,精心筛选国内外的250+信息源,为你挑选最值得分享的文章、教程、开源项目、软件工具、播客和视频、热门话题等内容。愿景:帮助所有读者精进Python技术,并增长职业和副业的收入。分享了11篇文章,13个开源项目,1则音视频,全文2000字。以下是本期摘要:......