YOLOv10环境搭建、模型预测和ONNX推理

news2024/9/22 13:46:37

目录

1、开源代码、模型下载

2、环境配置

3、模型预测

4、onnxruntime测试


1、开源代码、模型下载

代码下载链接:https://github.com/THU-MIG/yolov10

模型下载:

YOLOv10-N:https://github.com/THU-MIG/yolov10/releases/download/v1.1/yolov10n.pt

YOLOv10-S:https://github.com/THU-MIG/yolov10/releases/download/v1.1/yolov10s.pt

YOLOv10-M:https://github.com/THU-MIG/yolov10/releases/download/v1.1/yolov10m.pt

YOLOv10-B:https://github.com/THU-MIG/yolov10/releases/download/v1.1/yolov10b.pt

YOLOv10-L:https://github.com/THU-MIG/yolov10/releases/download/v1.1/yolov10l.pt

YOLOv10-X:https://github.com/THU-MIG/yolov10/releases/download/v1.1/yolov10x.pt

2、环境配置

打开Anaconda3终端,进入base环境,创建新环境

conda create -n yolov10 python=3.9
conda activate yolov10
#cd到yolov10的目录下
pip install -r requirements.txt -i  https://pypi.tuna.tsinghua.edu.cn/simple/
pip install -e . 

3、模型预测

安装完成之后,我们简单执行下推理命令测试下效果,默认读取yolov10-main/ultralytics/assets文件夹下的所有图像:

yolo predict model=yolov10s.pt

或者使用脚本



from ultralytics import YOLOv10
import glob
import os
import numpy as np
import cv2

classes = {
    0: 'person', 1: 'bicycle', 2: 'car', 3: 'motorcycle', 4: 'airplane', 5: 'bus',
    6: 'train', 7: 'truck', 8: 'boat', 9: 'traffic light', 10: 'fire hydrant',
    11: 'stop sign', 12: 'parking meter', 13: 'bench', 14: 'bird', 15: 'cat',
    16: 'dog', 17: 'horse', 18: 'sheep', 19: 'cow', 20: 'elephant', 21: 'bear',
    22: 'zebra', 23: 'giraffe', 24: 'backpack', 25: 'umbrella', 26: 'handbag',
    27: 'tie', 28: 'suitcase', 29: 'frisbee', 30: 'skis', 31: 'snowboard',
    32: 'sports ball', 33: 'kite', 34: 'baseball bat', 35: 'baseball glove',
    36: 'skateboard', 37: 'surfboard', 38: 'tennis racket', 39: 'bottle',
    40: 'wine glass', 41: 'cup', 42: 'fork', 43: 'knife', 44: 'spoon', 45: 'bowl',
    46: 'banana', 47: 'apple', 48: 'sandwich', 49: 'orange', 50: 'broccoli',
    51: 'carrot', 52: 'hot dog', 53: 'pizza', 54: 'donut', 55: 'cake',
    56: 'chair', 57: 'couch', 58: 'potted plant', 59: 'bed', 60: 'dining table',
    61: 'toilet', 62: 'tv', 63: 'laptop', 64: 'mouse', 65: 'remote', 66: 'keyboard',
    67: 'cell phone', 68: 'microwave', 69: 'oven', 70: 'toaster', 71: 'sink',
    72: 'refrigerator', 73: 'book', 74: 'clock', 75: 'vase', 76: 'scissors',
    77: 'teddy bear', 78: 'hair drier', 79: 'toothbrush'
}
class Colors:
    """Ultralytics color palette https://ultralytics.com/."""

    def __init__(self):
        """Initialize colors as hex = matplotlib.colors.TABLEAU_COLORS.values()."""
        hexs = ('FF3838', 'FF9D97', 'FF701F', 'FFB21D', 'CFD231', '48F90A', '92CC17', '3DDB86', '1A9334', '00D4BB',
                '2C99A8', '00C2FF', '344593', '6473FF', '0018EC', '8438FF', '520085', 'CB38FF', 'FF95C8', 'FF37C7')
        self.palette = [self.hex2rgb(f'#{c}') for c in hexs]
        # print(self.palette)
        self.n = len(self.palette)

    def __call__(self, i, bgr=False):
        """Converts hex color codes to rgb values."""
        c = self.palette[int(i) % self.n]
        return (c[2], c[1], c[0]) if bgr else c

    @staticmethod
    def hex2rgb(h):  # rgb order (PIL)
        return tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4))


colors = Colors()  # create instance for 'from utils.plots import colors'

imgpath = r'D:\Yolov10\yolov10-main\yolov10-detect\test2'
modelpath = r'D:\Yolov10\yolov10-main\yolov10-detect\yolov10s.pt'
save_dir = imgpath + '_Rst'
os.makedirs(save_dir,exist_ok=True)
model = YOLOv10(modelpath)

imgs = glob.glob(os.path.join(imgpath,'*.jpg'))
for img in imgs:
    imgname = img.split('\\')[-1]
    frame = cv2.imread(img)
    results = model.predict(img)[0]
    # results = model(img)

    for box in results.boxes:
        # print(box)
        xyxy = box.xyxy.squeeze().tolist()
        x1, y1, x2, y2 = int(xyxy[0]), int(xyxy[1]), int(xyxy[2]), int(xyxy[3])
        c, conf = int(box.cls), float(box.conf)
        name = classes[c]
        color = colors(c, True)
        cv2.rectangle(frame, (int(xyxy[0]), int(xyxy[1])), (int(xyxy[2]), int(xyxy[3])), color, thickness=2, lineType=cv2.LINE_AA)
        cv2.putText(frame, f"{name}: {conf:.2f}", (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 1, color,
                    2)
    # cv2.imshow('image', frame)
    # cv2.waitKey(0)
    cv2.imwrite(save_dir+'\\'+imgname,frame)

运行结果如下:

4、onnxruntime测试

(1)onnx模型转换

yolo export model=yolov10s.pt format=onnx opset=13 simplify

 运行后会在文件yolov10s.pt存放路径下生成一个的yolov10s.onnxONNX模型文件

可以通过这个网站Netron查看导出的节点信息:

(2)模型推理

通过 Ultralytics 框架测试下能否正常推理:

yolo predict model=yolov10s.onnx

或者使用推理脚本

import glob
import os
import cv2
import numpy as np
import onnxruntime as ort


classes = {
    0: 'person', 1: 'bicycle', 2: 'car', 3: 'motorcycle', 4: 'airplane', 5: 'bus',
    6: 'train', 7: 'truck', 8: 'boat', 9: 'traffic light', 10: 'fire hydrant',
    11: 'stop sign', 12: 'parking meter', 13: 'bench', 14: 'bird', 15: 'cat',
    16: 'dog', 17: 'horse', 18: 'sheep', 19: 'cow', 20: 'elephant', 21: 'bear',
    22: 'zebra', 23: 'giraffe', 24: 'backpack', 25: 'umbrella', 26: 'handbag',
    27: 'tie', 28: 'suitcase', 29: 'frisbee', 30: 'skis', 31: 'snowboard',
    32: 'sports ball', 33: 'kite', 34: 'baseball bat', 35: 'baseball glove',
    36: 'skateboard', 37: 'surfboard', 38: 'tennis racket', 39: 'bottle',
    40: 'wine glass', 41: 'cup', 42: 'fork', 43: 'knife', 44: 'spoon', 45: 'bowl',
    46: 'banana', 47: 'apple', 48: 'sandwich', 49: 'orange', 50: 'broccoli',
    51: 'carrot', 52: 'hot dog', 53: 'pizza', 54: 'donut', 55: 'cake',
    56: 'chair', 57: 'couch', 58: 'potted plant', 59: 'bed', 60: 'dining table',
    61: 'toilet', 62: 'tv', 63: 'laptop', 64: 'mouse', 65: 'remote', 66: 'keyboard',
    67: 'cell phone', 68: 'microwave', 69: 'oven', 70: 'toaster', 71: 'sink',
    72: 'refrigerator', 73: 'book', 74: 'clock', 75: 'vase', 76: 'scissors',
    77: 'teddy bear', 78: 'hair drier', 79: 'toothbrush'
}
class Colors:
    """Ultralytics color palette https://ultralytics.com/."""

    def __init__(self):
        """Initialize colors as hex = matplotlib.colors.TABLEAU_COLORS.values()."""
        hexs = ('FF3838', 'FF9D97', 'FF701F', 'FFB21D', 'CFD231', '48F90A', '92CC17', '3DDB86', '1A9334', '00D4BB',
                '2C99A8', '00C2FF', '344593', '6473FF', '0018EC', '8438FF', '520085', 'CB38FF', 'FF95C8', 'FF37C7')
        self.palette = [self.hex2rgb(f'#{c}') for c in hexs]
        # print(self.palette)
        self.n = len(self.palette)

    def __call__(self, i, bgr=False):
        """Converts hex color codes to rgb values."""
        c = self.palette[int(i) % self.n]
        return (c[2], c[1], c[0]) if bgr else c

    @staticmethod
    def hex2rgb(h):  # rgb order (PIL)
        return tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4))


colors = Colors()  # create instance for 'from utils.plots import colors'


def letterbox(
        im,
        new_shape,
        color=(114, 114, 114),
        auto=False,
        scaleFill=False,
        scaleup=True,
        stride=32,
):
    """
    Resize and pad image while meeting stride-multiple constraints
    Returns:
        im (array): (height, width, 3)
        ratio (array): [w_ratio, h_ratio]
        (dw, dh) (array): [w_padding h_padding]
    """
    shape = im.shape[:2]  # current shape [height, width]
    if isinstance(new_shape, int):  # [h_rect, w_rect]
        new_shape = (new_shape, new_shape)

    # Scale ratio (new / old)
    r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
    if not scaleup:  # only scale down, do not scale up (for better val mAP)
        r = min(r, 1.0)

    # Compute padding
    ratio = r, r  # wh ratios
    new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))  # w h
    dw, dh = (
        new_shape[1] - new_unpad[0],
        new_shape[0] - new_unpad[1],
    )  # wh padding

    if auto:  # minimum rectangle
        dw, dh = np.mod(dw, stride), np.mod(dh, stride)  # wh padding
    elif scaleFill:  # stretch
        dw, dh = 0.0, 0.0
        new_unpad = (new_shape[1], new_shape[0])  # [w h]
        ratio = (
            new_shape[1] / shape[1],
            new_shape[0] / shape[0],
        )  # [w_ratio, h_ratio]

    dw /= 2  # divide padding into 2 sides
    dh /= 2
    if shape[::-1] != new_unpad:  # resize
        im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR)
    top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
    left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
    im = cv2.copyMakeBorder(
        im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color
    )
    return im, ratio, (dw, dh)


def rescale_coords(boxes, image_shape, input_shape):
    image_height, image_width = image_shape
    input_height, input_width = input_shape

    scale = min(input_width / image_width, input_height / image_height)

    pad_w = (input_width - image_width * scale) / 2
    pad_h = (input_height - image_height * scale) / 2

    boxes[:, [0, 2]] = (boxes[:, [0, 2]] - pad_w) / scale
    boxes[:, [1, 3]] = (boxes[:, [1, 3]] - pad_h) / scale

    boxes[:, [0, 2]] = np.clip(boxes[:, [0, 2]], 0, image_width)
    boxes[:, [1, 3]] = np.clip(boxes[:, [1, 3]], 0, image_height)

    return boxes.astype(int)


def preprocess(image, input_shape):
    # Resize
    input_img = letterbox(image, input_shape)[0]
    # Transpose
    input_img = input_img[..., ::-1].transpose(2, 0, 1)
    # Expand
    input_img = input_img[np.newaxis, :, :, :].astype(np.float32)
    # Contiguous
    input_img = np.ascontiguousarray(input_img)
    # Norm
    blob = input_img / 255.0
    return blob


def postprocess(outs, conf_thres, image_shape, input_shape):
    # Filtered by conf
    outs = outs[outs[:, 4] >= conf_thres]

    # Extract
    boxes = outs[:, :4]
    scores = outs[:, -2]
    labels = outs[:, -1].astype(int)

    # Rescale
    boxes = rescale_coords(boxes, image_shape, input_shape)

    return boxes, scores, labels


def main():
    conf_thres = 0.25
    input_shape = (640, 640)
    image_path = r'D:\Yolov10\yolov10-main\ultralytics\assets'
    save_path = image_path + '_Rst'
    os.makedirs(save_path,exist_ok=True)
    model_path = r'D:\Yolov10\yolov10-main\yolov10-detect\yolov10s.onnx'

    ort_model = ort.InferenceSession(model_path)
    imgs = glob.glob(os.path.join(image_path,'*.jpg'))
    imgs.sort()
    for img in imgs:
        imgname = img.split('\\')[-1]
        # Preprocess
        im0 = cv2.imread(img)
        image_shape = im0.shape[:2]
        blob = preprocess(im0, input_shape)

        # Inference
        outs = ort_model.run(None, {'images': blob})[0][0]

        # Postprocess
        boxes, scores, labels = postprocess(outs, conf_thres, image_shape, input_shape)

        # 保存结果
        for label, score, box in zip(labels, scores, boxes):
            label_text = f'{classes[label]}: {score:.2f}'
            color = colors(label,True)
            cv2.rectangle(im0, (box[0], box[1]), (box[2], box[3]), color, thickness=2, lineType=cv2.LINE_AA)
            cv2.putText(im0, label_text, (box[0], box[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)

        # cv2.imshow('image', im0)
        # cv2.waitKey(0)
        cv2.imwrite(save_path+'\\'+imgname, im0)


if __name__ == '__main__':
    main()

参考:YOLOv10 正式发布!原理、部署、应用一站式齐全-CSDN博客

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

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

相关文章

Linux系统安装AMH服务器管理面板并实现远程访问管理维护

目录 前言 1. Linux 安装AMH 面板 2. 本地访问AMH 面板 3. Linux安装Cpolar 4. 配置AMH面板公网地址 5. 远程访问AMH面板 6. 固定AMH面板公网地址 1. 部署Docker Registry 2. 本地测试推送镜像 3. Linux 安装cpolar 4. 配置Docker Registry公网访问地址 5. 公网远程…

【NumPy】关于numpy.divide()函数,看这一篇文章就够了

🧑 博主简介:阿里巴巴嵌入式技术专家,深耕嵌入式人工智能领域,具备多年的嵌入式硬件产品研发管理经验。 📒 博客介绍:分享嵌入式开发领域的相关知识、经验、思考和感悟,欢迎关注。提供嵌入式方向…

Kubernetes可视化界面之DashBoard

1.1 DashBoard Kubernetes Dashboard 是 Kubernetes 集群的一个开箱即用的 Web UI,提供了一种图形化的方式来管理和监视 Kubernetes 集群中的资源。它允许用户直接在浏览器中执行许多常见的 Kubernetes 管理任务,如部署应用、监控应用状态、执行故障排查…

AI整体架构设计6:vLLM

训练大型语言模型以及微调的教程比比皆是,但关于在生产环境中部署它们并监控其活动的资料相对稀缺。上个章节提到了未来云原生的AI是趋势,然而涉及到云原生会比较偏技术。而在此之前为了解决大模型部署量产的问题,社区也一直在探索&#xff0…

数据链路层 + NAT技术

数据链路层:负责设备之间的数据帧的传送和识别。 一、以太网 以太网的帧格式 如何分离报头和有效数据? 报头是固定长度的 如何将数据交给上层协议? 通过类型,如果是0800,则交给IP协议,如果是0806&#xf…

华火硬核专利库丨登创新科技之巅,探创新未至之境

十年的艰苦卓越,“灶”就了华火科技之巅;电生明火的应用,不仅是一次颠覆性的创新,更是对未来厨房的无尽遐想与探索。在当今日新月异的科技时代,创新已成为推动社会进步的重要动力。 华火烹饪科技,以其深厚的…

【空号检测】手机号码状态识别背后的神秘力量:信令检测技术揭秘!

在当今数字化时代,了解一个手机号码的真实状态——是空号、停机还是活跃使用,对于企业运营、客户服务乃至个人通讯管理都至关重要。这一切高效而精准的查询能力,很大程度上归功于一项核心技术——信令检测技术。 免费测试地址:号…

【Django】中间件实现钩子函数预处理和后处理,局部装饰视图函数

在app文件夹里新建middleware.py继承MiddlewareMixin, 编写中间件类,重写process_request、process_response钩子函数 from django.http import HttpRequest, HttpResponse from django.utils.decorators import decorator_from_middleware from django…

使用MyBatis进行批量新增更新操作 ON CONFLICT

1.数据库增加uniques 2.mybatis <?xml version"1.0" encoding"UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace"co…

蓝桥杯2023(十四届)省赛——接龙数列(DP)

接龙数列&#xff08;DP&#xff09; 1.接龙数列 - 蓝桥云课 (lanqiao.cn) 琢磨半天&#xff0c;本来是开一个三维的&#xff0c;dp[i][j][k] 表示 前i个&#xff0c;以j为首项&#xff0c;k为尾项的最大子集个数&#xff0c;但是实际上用二维即可。想求的是删除个数&#xf…

【SpringCloud】负载均衡

目录 负载均衡什么是负载均衡生活场景为什么需要负载均衡负载均衡手段负载均衡总的来说有两种实现手段负载均衡具体可以通过多种手段来实现 SpringCloud中的负载均衡组件Ribbon VS Nginx负载均衡区别集中式LB进程内LB RibbonRibbon的工作原理Ribbon在工作时分成两步 使用1.提供…

二叉树经典OJ题分析

目录 一、单值二叉树 1.1 题目 1.2 思路 1.3 C语言题解 二、相同的树 2.1 题目 2.2 思路 2.3 C语言题解 三、对称二叉树 3.1 题目 3.2 思路 3.3 C语言题解 四、另一颗树的子树 4.1 题目 4.2 思路 4.3 C语言题解 五、翻转二叉树 5.1 题目 5.2 思路 5.3 C语言…

Elasticsearch之文本分析

文本分析基本概念 官网&#xff1a;Text analysis | Elasticsearch Guide [7.17] | Elastic 官网称为文本分析&#xff0c;这是对文本进行一直分析处理的方式&#xff0c;基本处理逻辑是为按照预先制定的分词规则&#xff0c;把原本的文档进行分割成多个小颗粒度的词项&#x…

800HZ电源-高频电源行业的明星

一、800Hz电源的简介&#xff1a; 800Hz电源&#xff0c;顾名思义&#xff0c;是一种专为满足通信系统中特定频率要求而设计的电源。通常&#xff0c;800Hz电源具有极高的稳定性和精确度&#xff0c;能提供稳定的电压输出&#xff0c;确保通信设备如交换机、基站、无线路由器等…

动手学操作系统(一、搭建实验环境)

动手学操作系统&#xff08;一、搭建实验环境&#xff09; 文章目录 动手学操作系统&#xff08;一、搭建实验环境&#xff09;1. 在VMware虚拟机中安装ubuntu20.042. 安装Bochs3. 启动计算机Reference &#x1f680; 环境配置 &#x1f680; 笔者的环境使用的是 ubuntu 20.04…

计算机图形学入门Games101笔记01:Overview of Computer Graphics

第一章讲述了计算机图形学是什么和GAMES101会讲什么 1.What is Computer Graphics? The use of computers to synthesize and manipulate visual information. 图形学是合成和操纵视觉信息的计算机应用。 百度百科&#xff1a;计算机图形学(Computer Graphics&#xff0c;简…

从零开始:如何集成美颜SDK和优化美颜接口

今天&#xff0c;小编将从零开始&#xff0c;详细讲解如何集成SDK并优化美颜接口。 一、选择合适的美颜SDK 评估SDK的功能 在评估过程中&#xff0c;可以通过阅读官方文档、查看示例代码以及实际测试来确定SDK是否符合需求。 兼容性和性能 确保其支持你开发的应用平台&…

开发多个工具包的黑产团伙GXC正在积极拥抱AI技术

研究人员发现一个名为 GXC Team 的犯罪团伙&#xff0c;该团伙专门开发用于网上银行盗窃、电子商务欺诈与互联网诈骗的工具。2023 年 11 月 11 日&#xff0c;该组织以别名 googleXcoder 在暗网上发布多项公告。开始售卖新开发的结合人工智能的工具&#xff0c;用于创建用于电汇…

【必备工具】gitee上传-保姆级教程

目录 1.gitee是什么 2.gitee怎么注册 ​编辑 3.gitee怎么提交代码 4.gitee的三板斧 Clone仓库 Q&A 1. Gitee 只有三板斧吗&#xff1f; 2. Git 教了&#xff0c;Gitee 上没有绿点怎么办&#xff1f; 3. 用户名和密码输入错误怎么办&#xff1f; 4. 操作时不小心…

0成本的副业兼职,咸鱼监督打卡,新手小白也能一天100+

这两天在咸鱼上闲逛&#xff0c;看到有个项目很有意思&#xff0c;监督别人打卡赚服务费&#xff0c;每天轻松收入100。 周周近财&#xff1a;让网络小白少花冤枉钱&#xff0c;赚取第一桶金 这种监督打卡服务并非新颖的商业模式&#xff0c;实际上在很久以前&#xff0c;许多…