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

智能推荐

当前顶点状态和顶点数组——OpenGL ES Common/Common-Lite 规范(版本 1.1.12)_查看当前顶点在哪个顶点组-程序员宅基地

文章浏览阅读1.4k次。当前顶点状态当一个顶点数组被定义,但是数据还不可用时,当前值常用于联合顶点辅助的数据。当前值可能在任何时候被独占命令改变。使用以下的命令可设置当前的RGBA颜色值。void Color4{xf}(T red, T green, T blue, T alpha);void Color4ub(ubyte red, ubyte green, ubyte blue, uby_查看当前顶点在哪个顶点组

用JAVAFX做一个简单的桌面宠物(四)-程序员宅基地

文章浏览阅读603次。(完结篇)实现自动行走的功能(Move类)类成员与构造函数private long time;private ImageView imageView;private int direID; double x; double maxx; double width; Rectangle2D screenBounds = Screen.getPrimary().getVisualBounds(); Stage stage;private EventListener lis

Anaconda详细安装及环境变量配置(图文)_anaconda环境变量-程序员宅基地

文章浏览阅读3.9w次,点赞39次,收藏182次。AnacondaAnaconda指的是一个开源的Python发行版本,其包含了conda、Python等180多个科学包及其依赖项。因为包含了大量的科学包,Anaconda的下载文件比较大(约531 MB),如果只需要某些包,或者需要节省带宽或存储空间,也可以使用Miniconda这个较小的发行版(仅包含conda和Python)。Conda是一个开源的包、环境管理器,可以用于在同一个机器上安装不同版本的软件包及其依赖,并能够在不同的环境之间切换。Anaconda包括Conda、Pyth..._anaconda环境变量

Python 之 Pandas (一)介绍_s = pd.series(['湖北', '浙江', '广东'])-程序员宅基地

文章浏览阅读601次。代码:import pandas as pdimport numpy as npprint("生成序列")s = pd.Series([1, 3, 6, np.nan, 44, 1])print(s)dates = pd.date_range('20160101', periods=6)print(dates)运行结果:生成序列0 1.01 3.02 6..._s = pd.series(['湖北', '浙江', '广东'])

java icon动态变换_Android实现APP安装后动态更换Icon和名称-程序员宅基地

文章浏览阅读200次。最近看到手机自带的时钟App可以实时的修改图标样式,就觉得很神奇。考虑到我自己要做的日记App可能也需要这样的功能,于是研究了一下,目前初步实现了修改图标及点击后进入不同Activity的功能,代码比较简单,点击这里download ZIP。简单效果图:原来调用修改方法:代码很简单,就2个部分:1.修改manifest文件:package="sxkeji.net.aliasdemo" >an..._android app 更换电子门牌 demo

Pytorch中的register_buffer()-程序员宅基地

文章浏览阅读2.4w次,点赞185次,收藏333次。Pytorch中的register_buffer1.register_buffer( )的使用随着例子边看边讲例子1:使用类成员变量(类成员变量并不会在我们的model.state_dict(),即无法保存)例子2:使用类成员变量(类成员变量并不会随着model.cuda()复制到gpu上)例子3:使用register_buffer()总结2.与pa1.register_buffer( )的使用回顾模型保存:torch.save(model.state_dict()),model.state_dict(_register_buffer

随便推点

mysql 8.0 创建新的数据库、用户并授权,以及相关查看并删除操作_mysql8.0 添加创建数据库权限-程序员宅基地

文章浏览阅读1.6k次。一、创建数据库mysql> create database news character set utf8;Query OK, 0 rows affected (0.09 sec)二、创建用户mysql> create user ‘news’@‘39.15.16.14’ identified by ‘123news’;Query OK, 0 rows affected (0.09 sec)三、授权用户mysql> grant all privileges on news.* _mysql8.0 添加创建数据库权限

SonarQube学习笔记二:Sonar插件安装和API调用示例_sonar-pdf-plugin-程序员宅基地

文章浏览阅读1.9k次。本文主要内容是sonarqube安装插件实现功能扩展,也对sonarqube的API功能进行了可用性确认。_sonar-pdf-plugin

vue使用fullCalendar插件(类似日程表)_vue 行程插件-程序员宅基地

文章浏览阅读6.4w次,点赞6次,收藏44次。基本操作传送门显示效果图添加效果图代码:<template> <div style="width:90%;margin: 20px auto;"> <!-- ref 用来拿到这个日历对象 defaultView 默认以月份方式显示 locale 语言 header 头部的按钮 buttonText 头部按钮的文字 plugins 插件 wee......_vue 行程插件

关于layout_centerHorizontal、layout_gravity、gravity的区别-程序员宅基地

文章浏览阅读1.2w次,点赞5次,收藏8次。layout_centerHorizontal是相对于RelativeLayout的布局属性如果设置为true,就将该控价设置在相对于父控件水平居中的位置layout_gravity针对LinearLayout的一种控件对齐方式,可以把值设置成下列值:center_vertical、center_horizontal、center等等gravity控制控件内文字的对齐方式举个栗子:在写一个简单的

python循环嵌套_python循环j和i每循环9个一分行-程序员宅基地

文章浏览阅读1.9k次。#一,循环嵌套##1,双for循环嵌套"""外层循环每循环一次,内层循环循环所有次,内层循环体执行就是内外层循环次数的乘积for i in "范围": #循环9次 for j in "范围":# 循环9次 "循环体""""for x in range(3): for y in range(3): print("%d %d" % (x, y))#例2打印99 乘法表for i in range(1, 10):# 循环打印数字0到9 for_python循环j和i每循环9个一分行

ubuntu16.04成功安装 百度网盘 by deepin-wine-for-ubuntu_ubuntu kylin16.04 网盘-程序员宅基地

文章浏览阅读9.6k次,点赞2次,收藏6次。ubuntu笔记本 安装百度网盘 ,帮助完成安装 百度网盘 的资料来源,请点击此处hairui@hadoop:~$ git clone https://gitee.com/wszqkzqk/deepin-wine-for-ubuntu.git正克隆到 'deepin-wine-for-ubuntu'...remote: Enumerating objects: 2777, done.remo..._ubuntu kylin16.04 网盘

推荐文章

热门文章

相关标签