DERT(DEtection TRansformer) ONNX直接推理!!

news2024/10/7 8:30:44

目录

1.前言

2. ONNX模型

(1) backbone使用的是resnet50

 (2) Transformer结构

(3)模型输出

3.代码展示(不收费!!!)

4.结果展示

5.源代码地址


1.前言

DETR        DETR的全称是DEtection TRansformer,是Facebook提出的基于Transformer的端到端目标检测网络,发表于ECCV2020,代码已开源:DETR的github源码。

        与之前讲解的VIT ONNX模型不同,VIT是分类模型,同时只用到了transformer的encoder的部分,而DETR是用到了整一个的transformer结构,同时是一个检测模型,具体的可以看下面的图片(本文中大部分图片都来自不灵不灵老师的博文)

 需要看具体的分析请转到不灵不灵老师 的博文,我转出的文档也是基于他的pytorch代码。

2. ONNX模型

(1) backbone使用的是resnet50

 (2) Transformer结构

 

图片太长了,截取不方便,凑活着看吧 

(3)模型输出

"pred_logits":1*100*92,预测的类别

"pred_boxes":1*100*4,预测的box坐标

3.代码展示(不收费!!!)

import numpy as np
import onnxruntime as rt
from PIL import Image
from PIL import ImageDraw, ImageFont
import colorsys


def get_classes(classes_path):
    with open(classes_path, encoding='utf-8') as f:
        class_names = f.readlines()
    class_names = [c.strip() for c in class_names]
    return class_names, len(class_names)


def get_new_img_size(height, width, min_length=600):
    if width <= height:
        f = float(min_length) / width
        resized_height = int(f * height)
        resized_width = int(min_length)
    else:
        f = float(min_length) / height
        resized_width = int(f * width)
        resized_height = int(min_length)

    return resized_height, resized_width


def resize_image(image, min_length):
    iw, ih = image.size
    h, w = get_new_img_size(ih, iw, min_length=min_length)
    new_image = image.resize((w, h), Image.BICUBIC)
    return new_image


def cvtColor(image):
    if len(np.shape(image)) == 3 and np.shape(image)[2] == 3:
        return image
    else:
        image = image.convert('RGB')
        return image


class DecodeBox:
    """ This module converts the model's output into the format expected by the coco api"""

    def box_cxcywh_to_xyxy(self, x):
        x_c, y_c, w, h = x[..., 0], x[..., 1], x[..., 2], x[..., 3]
        b = [(x_c - 0.5 * w), (y_c - 0.5 * h),
             (x_c + 0.5 * w), (y_c + 0.5 * h)]
        return np.stack(b, axis=-1)

    def forward(self, outputs, target_sizes, confidence):
        out_logits, out_bbox = outputs["pred_logits"], outputs["pred_boxes"]

        assert len(out_logits) == len(target_sizes)
        assert target_sizes.shape[1] == 2

        prob = np.exp(out_logits) / np.exp(out_logits).sum(-1, keepdims=True)
        scores = np.max(prob[..., :-1], axis=-1)
        labels = np.argmax(prob[..., :-1], axis=-1)  # 加1来转换为类别标签(背景类别为0)


        # convert to [x0, y0, x1, y1] format
        boxes = self.box_cxcywh_to_xyxy(out_bbox)

        # and from relative [0, 1] to absolute [0, height] coordinates
        img_h, img_w = np.split(target_sizes, target_sizes.shape[1], axis=1)[0], np.split(target_sizes, target_sizes.shape[1], axis=1)[1]
        img_h = img_h.astype(float)
        img_w = img_w.astype(float)
        scale_fct = np.hstack([img_w, img_h, img_w, img_h])
        boxes = boxes * scale_fct[:, None, :]

        outputs = np.concatenate([
            np.expand_dims(boxes[:, :, 1], -1),
            np.expand_dims(boxes[:, :, 0], -1),
            np.expand_dims(boxes[:, :, 3], -1),
            np.expand_dims(boxes[:, :, 2], -1),
            np.expand_dims(scores, -1),
            np.expand_dims(labels.astype(float), -1),
        ], -1)

        results = []
        for output in outputs:
            results.append(output[output[:, 4] > confidence])
        # results = [{'scores': s, 'labels': l, 'boxes': b} for s, l, b in zip(scores, labels, boxes)]
        return results


def preprocess_input(image):
    image /= 255.0
    image -= np.array([0.485, 0.456, 0.406])
    image /= np.array([0.229, 0.224, 0.225])
    return image


if __name__ == "__main__":

    count = True
    confidence = 0.5
    min_length = 512
    image = Image.open('1.jpg')
    image = image.resize((512, 512))
    image_shape = np.array([np.shape(image)[0:2]])
    image = cvtColor(image)
    image_data = resize_image(image, min_length)
    image_data = np.expand_dims(np.transpose(preprocess_input(np.array(image_data, dtype='float32')), (2, 0, 1)), 0)

    # onnx模型前向推理
    sess = rt.InferenceSession('./model_data/models.onnx')

    # 模型的输入和输出节点名,可以通过netron查看
    input_name = 'images'
    outputs_name = ['output', '4556']

    # 模型推理:模型输出节点名,模型输入节点名,输入数据(注意节点名的格式!!!!!)
    net_outs = sess.run(outputs_name, {input_name: image_data})
    # net_outs = {"pred_logits":torch.tensor(net_outs[0]), "pred_boxes":torch.tensor(net_outs[1])}
    net_outs = {"pred_logits": net_outs[0], "pred_boxes": net_outs[1]}
    bbox_util = DecodeBox()
    results = bbox_util.forward(net_outs, image_shape, confidence)

    if results[0] is None:
        print('NO OBJECT')
    else:
        _results = results[0]
        top_label = np.array(_results[:, 5], dtype='int32')
        top_conf = _results[:, 4]
        top_boxes = _results[:, :4]
        font = ImageFont.truetype(font='model_data/simhei.ttf', size=np.floor(3e-2 * image.size[1] + 0.5).astype('int32'))
        thickness = int(max((image.size[0] + image.size[1]) // min_length, 1))
        classes_path = 'model_data/coco_classes.txt'
        class_names, num_classes = get_classes(classes_path)
        hsv_tuples = [(x / num_classes, 1., 1.) for x in range(num_classes)]
        colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))
        colors = list(map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)), colors))

        for i, c in list(enumerate(top_label)):
            predicted_class = class_names[int(c)]
            box = top_boxes[i]
            score = top_conf[i]
            top, left, bottom, right = box
            top = max(0, np.floor(top).astype('int32'))
            left = max(0, np.floor(left).astype('int32'))
            bottom = min(image.size[1], np.floor(bottom).astype('int32'))
            right = min(image.size[0], np.floor(right).astype('int32'))

            label = '{} {:.2f}'.format(predicted_class, score)
            draw = ImageDraw.Draw(image)
            label_size = draw.textsize(label, font)
            label = label.encode('utf-8')
            print(label, top, left, bottom, right)

            if top - label_size[1] >= 0:
                text_origin = np.array([left, top - label_size[1]])
            else:
                text_origin = np.array([left, top + 1])

            for i in range(thickness):
                draw.rectangle([left + i, top + i, right - i, bottom - i], outline=colors[c])
            draw.rectangle([tuple(text_origin), tuple(text_origin + label_size)], fill=colors[c])
            draw.text(text_origin, str(label, 'UTF-8'), fill=(0, 0, 0), font=font)
            del draw
        image.save('output.png')

4.结果展示

5.源代码地址

链接: https://pan.baidu.com/s/1Rkh8GI-EZdaS6h7uG4IuFg 提取码: xfen 

 

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

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

相关文章

c++实现【典型的旅行商问题(TSP)】实现配送中心最多可以用2辆车对8个客户进行运输配送

假定配送中心最多可以用2辆车对8个客户进行运输配送。每个车辆载重均 为8吨,车辆每次配送的最大行驶距离为50km,配送中心(编号0)与8个客 户之间及8个客户相互之间的距离d; (i, j= 1, 2, ... 8)、8个客户的货物需 求r;(j= 1, 2... 8)如表1所示。要求寻找一条路径, 使得配送总…

Codeforces Div.2 1798B Three Sevens题解

题目&#xff1a; 传送门 B. Three Sevens time limit per test 2 seconds memory limit per test 256 megabytes input standard input output standard output Lottery "Three Sevens" was held for m days. On day i, ni people with the numbers ai,1…

生态系统NPP及碳源、碳汇模拟——土地利用变化、未来气候变化、空间动态模拟

由于全球变暖、大气中温室气体浓度逐年增加等问题的出现&#xff0c;“双碳”行动特别是碳中和已经在世界范围形成广泛影响。碳中和可以从碳排放&#xff08;碳源&#xff09;和碳固定&#xff08;碳汇&#xff09;这两个侧面来理解。陆地生态系统在全球碳循环过程中有着重要作…

手动计算校正年龄、性别后的标准化死亡率 (SMR)

分析队列人群有无死亡人数超额&#xff0c;通常应用标准人群死亡率来校正&#xff0c;即刻观察到中的实际死亡数&#xff08;D&#xff09;与定一个标准的死亡人数&#xff08;E&#xff09;&#xff0c;D与E之比称为死亡比&#xff08;standarized Mortality ratio&#xff0c…

运筹学-单纯形法

一、单纯形法的求解思路 单纯形法求解线性规划的思路&#xff1a;在高斯消去法的基础上&#xff0c;发展为求解变量数大于方程数&#xff0c;并且使目标函数值优化的方法。从线性方程中找到一个个的单纯形&#xff0c;每个单纯形&#xff08;图形的顶点&#xff09;可以得到一组…

支付宝 小程序 抽奖组件 大转盘

介绍 使用支付宝原有的大转盘营销组件进行改造的&#xff0c;由于背景使用的图片&#xff0c;目前只支持 6 个奖品&#xff0c;一般情况下的大转盘都是这个规格。 转盘停止&#xff1a;之前使用的是计算角度来完成的&#xff0c;没有那种缓慢停止的动画。现在加了一个缓慢停止…

Android实现皮肤主题修改

最近在做App内皮肤切换功能&#xff0c;想了很久方案&#xff0c;写了个皮肤更换工具类&#xff0c;适配N皮肤种类。 话不多说&#xff0c;直接捋一下我的设计思路&#xff0c;因为我的App默认为黑色主题&#xff0c;因此在做其他皮肤主题时&#xff0c;我的图片命名方式是直接…

Fastjson核心解析器DefaultJSONParser,解析算法递归下降算法,实例解析json的步骤

先恭喜热火没有在3-0的情况下被凯尔特人翻盘&#xff0c;抢七获胜成功晋级总决赛~ 最近的项目用到了fastjson&#xff0c;因为源码比较容易搞到&#xff0c;所以就拿来简单的了解了一下&#xff0c;json的主要功能就是解析json和生成json字符串&#xff0c;今天主要是从解析jso…

基于vue3.0简单的页面使用

基于vue3.0简单的页面使用 项目效果图项目文件图package.jsonmain.jsApp.vueviews/Tutorial.vueviews/TS.vueviews/Docs.vueviews/Community.vueviews/Blog.vueviews/About.vueutils/create.jsxutils/defineCom.jsutils/DragIcon.jsutils/someName.tsutils/TS.tsstores/client.…

win11任务栏时间改成12时制

需求&#xff1a;默认24小时值&#xff0c;想改成12小时3:49 方法&#xff1a;设置-时间和语言-语言和区域-管理语言设置-格式 将时间格式改成带tt的

2022年长三角高校数学建模竞赛C题隧道的升级改造与设计解题全过程文档及程序

2022年长三角高校数学建模竞赛 C题 隧道的升级改造与设计 原题再现&#xff1a; 某地现存一旧式双洞隧道&#xff0c;现计划将该隧道在旧貌基础上升级改造。在升级改造前&#xff0c;需进行定标与设计。考虑到该隧道洞壁附着特殊涂料&#xff0c;无人机在洞内通信信号较差&am…

网络面试题:什么是 TCP/IP?

目录标题 什么是 TCP/IP?1) 网络接口层:2) 网络层:3) 传输层:4) 应用层: 2.数据包3.网络接口层4.网络层1) IP:2)地址解析协议 ARP3)子网 5 传输层1&#xff09;UDP&#xff1a;2&#xff09;TCP&#xff1a; 6 应用层运行在TCP协议上的协议&#xff1a;运行在UDP协议上的协议&…

Netty 实现百万级连接服务的难点和优点分析总结

推送服务 还记得一年半前&#xff0c;做的一个项目需要用到 Android 推送服务。和 iOS 不同&#xff0c;Android 生态中没有统一的推送服务。Google 虽然有 Google Cloud Messaging &#xff0c;但是连国外都没统一&#xff0c;更别说国内了&#xff0c;直接被墙。 所以之前在…

Lua学习笔记:C/C++和Lua的相互调用

前言 本篇在讲什么 C/C和Lua的相互调用 本篇适合什么 适合初学Lua的小白 适合需要C/C和lua结合开发的人 本篇需要什么 对Lua语法有简单认知 对C/C语法有简单认知 依赖Lua5.1的环境 依赖VS 2017编辑器 本篇的特色 具有全流程的图文教学 重实践&#xff0c;轻理论&…

云南智慧档案库综合管理系统建设解决方案

一、智慧档案管理系统建设背景 档案作为一种特殊的文献&#xff0c;是人类社会活动的产物&#xff0c;具有特殊的价值&#xff0c;其价值可以概括为现实价值和历史价值。档案是人类留给国家和社会的宝贵财富&#xff0c;它在经济与社会建设中起着重要的作用。档案是反映一个单…

多重共线性的处理方法

回归分析需要考虑多重共线性问题。多重共线性是指自变量之间存在高度相关性&#xff0c;导致回归模型的系数估计不稳定和假设检验不可靠。在实际应用中&#xff0c;许多自变量之间都可能存在一定程度的相关性&#xff0c;如果没有进行控制&#xff0c;就会导致多重共线性问题的…

设计模式之美-实战二:如何对接口鉴权这样一个功能开发做面向对象分析?

面向对象的三个环节&#xff1a;面向对象分析&#xff08;OOA&#xff09;、面向对象设计&#xff08;OOD&#xff09;、面向对象编程&#xff08;OOP&#xff09;。只知道OOA、OOD、OOP只能说有一个宏观了解&#xff0c;我们更重要的还是要知道“如何做”&#xff0c;也就是&a…

【快应用】多语言适配案例

【关键词】 多语言&#xff0c;$t 【问题背景】 快应用平台的能力会覆盖多个国家地区&#xff0c;平台支持多语言的能力后&#xff0c;可以让一个快应同时支持多个语言版本的切换&#xff0c;开发者无需开发多个不同语言的源码项目&#xff0c;避免给项目维护带来困难。使用系…

子串分值--子串分值和 模拟,找规律

子串分值和 n有十万&#xff0c;需要找规律&#xff0c;O(n^2)不满足要求 分析样例&#xff1a; Ababc 01234 长度是n5 索引下标-对应字符 0A贡献 112 a;ab;---22*1 next a 2&#xff1b; pre a -1 1b贡献 112 b;ba;---42*2 next b 3&#xff1b; pre b -1 2a贡献 1113…

2023年测试前景?测试开发工程师养成记,开发企业级测试平台...

目录&#xff1a;导读 前言一、Python编程入门到精通二、接口自动化项目实战三、Web自动化项目实战四、App自动化项目实战五、一线大厂简历六、测试开发DevOps体系七、常用自动化测试工具八、JMeter性能测试九、总结&#xff08;尾部小惊喜&#xff09; 前言 测试开发&#xff…