yolov5测试单张图片-程序员宅基地

技术标签: # QD  python  

yolov5测试单张图片,返回一个列表[类别,置信度,x,y,w,h]

from numpy import random
import torch
from models.experimental import attempt_load
from utils.datasets import LoadStreams, LoadImages
from utils.general import (
    check_img_size, non_max_suppression, apply_classifier, scale_coords,
    xyxy2xywh, plot_one_box, strip_optimizer, set_logging)
from utils.torch_utils import select_device, load_classifier, time_synchronized
import os
import shutil

# Initialize
out = r'inference\output'
set_logging()
device = select_device('')
if os.path.exists(out):
    shutil.rmtree(out)  # delete output folder
os.makedirs(out)  # make new output folder
half = device.type != 'cpu'  # half precision only supported on CUDA

# Load model
model = attempt_load('weights/yolov5s.pt', map_location=device)  # load FP32 model
imgsz = check_img_size(512, s=model.stride.max())  # check img_size
if half:
    model.half()  # to FP16

# Second-stage classifier
classify = False
if classify:
    modelc = load_classifier(name='resnet101', n=2)  # initialize
    modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model'])  # load weights
    modelc.to(device).eval()

# Set Dataloader


# Get names and colors
names = model.module.names if hasattr(model, 'module') else model.names
colors = [[random.randint(0, 255) for _ in range(3)] for _ in range(len(names))]
img = torch.zeros((1, 3, imgsz, imgsz), device=device)  # init img
_ = model(img.half() if half else img) if device.type != 'cpu' else None  # run once


def PoseDect(path, imgsz=512):
    res = []
    dataset = LoadImages(path, img_size=imgsz)

    for path, img, im0s, vid_cap in dataset:
        img = torch.from_numpy(img).to(device)
        img = img.half() if half else img.float()  # uint8 to fp16/32
        img /= 255.0  # 0 - 255 to 0.0 - 1.0
        if img.ndimension() == 3:
            img = img.unsqueeze(0)

        # Inference
        t1 = time_synchronized()
        pred = model(img, augment=False)[0]

        # Apply NMS
        pred = non_max_suppression(pred, 0.4, 0.5, classes=None, agnostic=False)
        t2 = time_synchronized()

        # Apply Classifier
        if classify:
            pred = apply_classifier(pred, modelc, img, im0s)

        # Process detections
        for i, det in enumerate(pred):  # detections per image
            gn = torch.tensor(im0s.shape)[[1, 0, 1, 0]]  # normalization gain whwh
            if det is not None and len(det):
                # Rescale boxes from img_size to im0 size
                det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0s.shape).round()

                for *xyxy, conf, cls in reversed(det):
                    x, y, w, h = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()
                    res.append([names[int(cls)], float(conf), x, y, w, h])

    return res

    # for _, img, im0s, _ in dataset:
    #
    #     img = torch.from_numpy(img).to(device)
    #     img = img.half() if half else img.float()  # uint8 to fp16/32
    #     img /= 255.0  # 0 - 255 to 0.0 - 1.0
    #     if img.ndimension() == 3:
    #         img = img.unsqueeze(0)
    #
    #     pred = model(img, augment=False)[0]
    #     # Apply NMS
    #     pred = non_max_suppression(pred, 0.4, .05, classes=None, agnostic=None)
    #
    #     for i, det in enumerate(pred):  # detections per image
    #         p, s, im0 = path[i], '%g: ' % i, im0s[i].copy()
    #
    #         gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]  # normalization gain whwh
    #         if det is not None and len(det):
    #             # Rescale boxes from img_size to im0 size
    #             det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
    #
    #             # Write results
    #             for *xyxy, conf, cls in reversed(det):
    #                 xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()  # normalized xywh
    #                 x, y, w, h = xywh
    #                 if(int(cls)==0):
    #                     res.append([names[int(cls)], float(conf), x, y, w, h])
    #                 #res.append([int(cls), float(conf), x, y, w, h])
    #
    #                 # draw
    #                 # label = '%s %.2f' % (names[int(cls)], conf)
    #                 #plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3)
    #
    # return res


if __name__ == '__main__':

    path = r'inference\images\0152498D-225A-4126-AEBE-B6D9423E12E7.png'
    s = PoseDect(path=path)
    print(s)
    import cv2

    img = cv2.imread(r'inference\images\0152498D-225A-4126-AEBE-B6D9423E12E7.png')
    for box in s:
        x1, y1, x2, y2 = box[2:]
        # 映射原图尺寸
        x = int(x1 * img.shape[1])
        y = int(y1 * img.shape[0])
        w = int(x2 * img.shape[1])
        h = int(y2 * img.shape[0])
        # 计算出左上角和右下角:原x,y是矩形框的中心点
        a = int(x - w / 2)
        b = int(y - h / 2)
        c = int(x + w / 2)
        d = int(y + h / 2)

        print(x1, y1, x1 + x2, y1 + y2)
        print(x, y, x + w, y + h)
        print(a, b, c, d)
        
        cv2.rectangle(img, (a, b), (c, d), (255, 0, 0), 2)
    cv2.imshow('dst', img)
    cv2.waitKey()
    cv2.destroyAllWindows()

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_38582851/article/details/109165440

智能推荐

Android 应用程序组件_android清单文件包含了组成应用程序模块所需要的组件-程序员宅基地

文章浏览阅读168次。应用程序组件是一个Android应用程序的基本构建块。这些组件由应用清单文件松耦合的组织。AndroidManifest.xml描述了应用程序的每个组件,以及他们如何交互。以下是可以在Android应用程序中使用的四个主要组件。组件 描述 Activities 描述UI,并且处理用户与机器屏幕的交互。 Services 处理与应用程序关联的后台操作。 Broadcast Receivers 处理Android操作系统和应用程序之间的通信。 Content Prov_android清单文件包含了组成应用程序模块所需要的组件

22.8.29 C语言作业5道_a.c: in function ‘main’:-程序员宅基地

文章浏览阅读387次。1.字符转换输出递归按位输出_a.c: in function ‘main’:

【pygame游戏】用Python实现一个蔡徐坤大战篮球的小游戏,可还行?【附源码】_python蔡徐坤代码复制-程序员宅基地

文章浏览阅读6.9w次,点赞137次,收藏246次。表弟大周末的跑来我家,没事干天天骚扰我,搞得我都不能跟小姐姐好好聊天了,于是为了打发表弟,我决定用Python做一个小游戏来消耗一下他的精力..._python蔡徐坤代码复制

系统分析、设计_信息系统开发中分析与设计的重要性。-程序员宅基地

文章浏览阅读1.9k次。blueski推荐 [2007-1-31]出处:Java夜无眠作者:蔡学镛 1、系统分析是什么?   系统分析工作是解决一个问题的工作,目标是将一个对计算机应用系统的需求转化成实际的物理实现,其中复杂就复杂在实际的面太多.在系统分析过程之中注意问以下的问题,可能会所进行的系统分析设计工作有帮助。    1)您所完成的系统目的是什么?注意不是功能要求,而是目的.也就是为什么要建设、为什么要现_信息系统开发中分析与设计的重要性。

nginx 学习+案例练习_nginx 使用pipe:rollback-程序员宅基地

文章浏览阅读659次。nginx软件学习nginx是个web服务器,常用作静态文件服务器,反向代理服务器,邮件代理服务器,负载均衡服务器1.安装淘宝nginx,编代码编译安装,先解决模块依赖 yum install gcc patch libffi-devel python-devel zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel..._nginx 使用pipe:rollback

python_one893.app-程序员宅基地

文章浏览阅读6.7k次。pycharm安装库包失败:比如安装matplotlib失败下载库文件:https://www.lfd.uci.edu/~gohlke/pythonlibs/#matplotlib根据python版本等来选择适合的文件,比如python3.8选择cp38,python3.10选择cp310,这里我选择的是matplotlib‑3.4.3‑cp310‑cp310‑win_amd64.whl将下载好的文件放入python安装包的Scripts中,运行cmd命令行,执行pip install .\_one893.app

随便推点

idea 注释插件_开发效率不高?墙裂推荐这十款精选IntelliJ Idea插件-程序员宅基地

文章浏览阅读3.3k次。(给程序员零距离加星标,了解项目开发.)作者|雷架来源 |爱笑的架构师(ID:DancingOnYourCode)俗话说:"工欲善其事必先利其器",小主从项目实战的角度在众多的idea插件中挑选了10款开发必备的神器,帮助大家在日常编码中提升开发效率。1Key Promoter X实用指数:★★★★★装逼指数:★你还在为记不住快捷键烦恼吗,Key Promoter X可以帮助你快..._idea@value寻找注释插件

mybatis看这一篇就够了,简单全面一发入魂_mybatis一发入魂-程序员宅基地

文章浏览阅读10w+次,点赞1.9k次,收藏1.3w次。文章目录Mybatis概述快速入门原生开发示例基于Mapper代理的示例基于注解的示例应用场景主键返回批量查询动态SQL缓存关联查询延迟加载逆向工程PageHelper分页插件Mybatis PlusMybatis概述mybatis是什么?有什么特点?它是一款半自动的ORM持久层框架,具有较高的SQL灵活性,支持高级映射(一对一,一对多),动态SQL,延迟加载和缓存等特性,但它的数据库无关性较低什么是ORM?Object Relation Mapping,对象关系映射。对象指的是Java_mybatis一发入魂

回溯算法(leetcode 306 python)-程序员宅基地

文章浏览阅读295次。回溯算法:回溯算法实际上一个类似枚举的搜索尝试过程,主要是在搜索尝试过程中寻找问题的解,当发现已不满足求解条件时,就“回溯”返回,尝试别的路径。回溯法是一种选优搜索法,按选优条件向前搜索,以达到目标。但当探索到某一步时,发现原先选择并不优或达不到目标,就退回一步重新选择,这种走不通就退回再走的技术为回溯法,而满足回溯条件的某个状态的点称为“回溯点”。许多复杂的,规模较大的问题都可以使用回..._leetcode 306、python

redis的使用总结_redis.redis(host='127.0.0.1', port=6379)-程序员宅基地

文章浏览阅读352次。数据库redis使用优点使用方法redis的简单类型String字符串注意一个键最大能存储512MB哈希list列表set集合注意redis安全可以通过以下命令查看是否设置了密码验证用python实现链接数据库redis-connectredis密码破解redis使用设置数据添加数据redis查看服务器配置插入值追加数据setget数据导出dumprdb 这个即为_redis.redis(host='127.0.0.1', port=6379)

华为ICT解决方案助力全球190多家电力公司数字化转型-程序员宅基地

文章浏览阅读1k次。华为以“比特驱动瓦特,共建全联接智能电网”为主题,举办第七届华为全球电力峰会(线上),邀请来自全球各地的客户、伙伴、行业精英和思想领袖共同探讨。面对2020年的全球疫情、政治、经济等不确..._ict数字化解决方案资金分配

将图片资源文件整合到DLL文件中 _易语言dll加入资源-程序员宅基地

文章浏览阅读733次。 1、新建一个类库,例如库名为 ResourcesLibrary;2、添加引用 System.Drawing;3、添加资源文件(添加--新建项--资源文件),例如文件名为 Resource1.resx;4、添加图片(打开Resource1.resx,单击“添加资源”后的小三角,选择添加现有文件,选择需要作为资源的图片),例如添加了图片 Sunset.jpg5、添加类,例如名为 GetImage_易语言dll加入资源

推荐文章

热门文章

相关标签