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)  # initializemodelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model'])  # load weightsmodelc.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 oncedef 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/32img /= 255.0  # 0 - 255 to 0.0 - 1.0if img.ndimension() == 3:img = img.unsqueeze(0)# Inferencet1 = time_synchronized()pred = model(img, augment=False)[0]# Apply NMSpred = non_max_suppression(pred, 0.4, 0.5, classes=None, agnostic=False)t2 = time_synchronized()# Apply Classifierif classify:pred = apply_classifier(pred, modelc, img, im0s)# Process detectionsfor i, det in enumerate(pred):  # detections per imagegn = torch.tensor(im0s.shape)[[1, 0, 1, 0]]  # normalization gain whwhif det is not None and len(det):# Rescale boxes from img_size to im0 sizedet[:, :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 resif __name__ == '__main__':path = r'inference\images\0152498D-225A-4126-AEBE-B6D9423E12E7.png's = PoseDect(path=path)print(s)import cv2img = 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()

yolov5测试单张图片相关推荐

  1. GPU测试单张图片时间过长

    为什么在测试GPU和CPU的速度的时候会出现GPU反而比CPU慢的 我之前为了测试resnext101网络在CPU和GPU上的单张图片测试程序 很显然不对啊,后来我发现,GPU在刚启动测试第一张图片, ...

  2. keras笔记(3)-猫狗数据集上的训练以及单张图片多张图片的测试

    之前也写过关于使用tensorflow在猫狗数据集上的训练,想要学习的可以看一下 数据集下载 猫狗数据集:https://pan.baidu.com/s/13hw4LK8ihR6-6-8mpjLKDA ...

  3. 猫狗训练单张图片的测试

    猫狗训练的训练模型的建立,模型在整个预测集上的预测效果的测试的程序代码网上或一些书籍上都可查阅,但是对单张或某些图片的分类测试程序不多,这里通过参考博客:https://blog.csdn.net/b ...

  4. caffe ssd 测试demo,检测单张图片

    原 SSD: Single Shot MultiBox Detector 检测单张图片 2016年10月29日 16:39:05 阅读数:19930 标签: python ssd ssd-detect ...

  5. 仅输入单张图片,就能“看”出物体材质!这篇图形学论文已被SIGGRAPH 2021收录...

     OPPO 日前,计算机图形学顶级国际学术会议ACM SIGGRAPH 2021收录了Highlight-aware Two-stream Network for Single-image SVBRD ...

  6. SIGGRAPH 2021丨OPPO与南大提出双流网络:仅输入单张图片,就能“看”出物体材质...

     OPPO 为了解决双向反射分布函数 (SVBRDF)提取过程中所遇到的纹理.高光.阴影问题,南京大学计算机软件新技术国家重点实验室的过洁博士等多位专家学者和OPPO软工多媒体与智慧开发部高级算法工程 ...

  7. 详细实现yolov5测试丶自己数据集训练测试丶Tensorrt加速优化(完 结 !)+ 跟踪(补充)

    参考文献:[yolov5系列]yolov5 v6.0 环境配置.图片视频测试.模型可视化.v6.0的更新内容   Jeston AGX Orin安装Pytorch1.11.0+torchvision0 ...

  8. yolov3 使用darknet的python接口处理单张图片和视频和摄像头视频流

    目标 使用yoloV3 darknet 自带的 python 接口(即darknet.py 文件)处理图片和视频. 具体的说有三种场景: 1 指定一张图片的位置,进行model预测+画框+另存为新图片 ...

  9. CaNet-master装载图片数据和mask(index对应单张图片序号)

    使用三个txt(15cls)训练,另外1个txt(5cls)用于val. 训练需要support set原图+mask,query set原图,使用query集计算loss更新参数. support ...

  10. YOLOV5测试代码test.py注释与解析

    YOLOv5代码注释版更新啦,注释的是最近的2021.07.14的版本,且注释更全 github: https://github.com/Laughing-q/yolov5_annotations Y ...

最新文章

  1. php7 windows2008,【笔记】Windows Server2008 R2 安装 PHP7 缺少 API-ms-win-crt-runtime-l1-1-0.dll 解决方案...
  2. 欧拉函数的相关应用 noj欧拉函数求和+noj 最大公约数求和
  3. 基于python的FFT频率和振幅处理
  4. nginx 重定向_虚拟机中安装nginx,重定向到resin
  5. ZOJ-2342 Roads 二分图最小权值覆盖
  6. MongoDB更新文档(非常详细,不要错过~)
  7. python调用阿里云表情识别API
  8. 「安妮股份」拉上小米做版权联盟
  9. 如何设计领域特定语言,实现终极业务抽象?
  10. MQL5中的错误处理和日志记录
  11. 米家小相机最新固件_不到1000元的米家小相机 都有哪些缺点
  12. 进制转换模板——短除法
  13. ubuntu登录mysql报错:ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mys
  14. 彻底掌握NodeJS中如何使用Sequelize
  15. 手写jQuery源码
  16. Kindle电子书的资源汇总
  17. php ses 发送邮件,php – 无法使用Amazon SES发送电子邮件
  18. wordpress中Google Map V3 for IDN 插件的使用
  19. Linux Graphics 周刊(第 9 期)
  20. 【深度学习人类语言处理】1 课程介绍、语音辨识1——人类语言处理六种模型、Token、五种Seq2Seq Model(LAS、CTC、RNN-T、Neural Transducer、MoChA)

热门文章

  1. Sklearn实现SVC
  2. 如何将手机里的PDF文件转换成Word文档
  3. linux查网卡物理地址,网卡MAC地址查询方法
  4. 前台请求报:ERR_EMPTY_RESPONSE错误
  5. 变种水仙花数 - Lily Number
  6. HCIA-IoT 个人学习总结 Day2
  7. c语言自评报告怎么写,大学生学生自评报告怎么写
  8. gpg: agent_genkey failed: Operation cancelled Key generation failed: Operation cancelled
  9. 清华梦的粉碎-写给清华大学的退学申请
  10. # cs231n (三)优化问题及方法