yolov5测试代码

一般源码的测试代码涉及很多文件,因项目需要写一个独立测试的代码。传入的是字典

import time
import cv2
import os
import numpy as np
import torch
from modules.detec.models.common import DetectMultiBackend
from modules.detec.utils.dataloaders import LoadImages
from modules.detec.utils.general import (LOGGER, Profile, check_file, check_img_size, check_imshow, check_requirements, colorstr,increment_path, non_max_suppression, print_args, scale_boxes, strip_optimizer, xyxy2xywh)
from modules.detec.utils.augmentations import letterbox
from modules.detec.utils.plots import Annotator, colorsclass DetectionEstimation:def __init__(self, model_path, conf_threshold=0.9, iou_threshold=0.45, img_size=(384,640)):self.device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')self.model = DetectMultiBackend(model_path).to(self.device)self.conf_threshold = conf_thresholdself.iou_threshold = iou_thresholdself.img_size = img_sizedef _preprocess_image(self, img_dict):img_tensor_list = []original_sizes = {}for serial, img in img_dict.items():original_size = img.shape[:2]img_resized = letterbox(img, self.img_size, stride=32, auto=True)[0]img_resized = img_resized.transpose((2, 0, 1))[::-1]img_resized = np.ascontiguousarray(img_resized)img_tensor = torch.from_numpy(img_resized).float().to(self.device)img_normalized = img_tensor / 255if len(img_normalized.shape) == 3:img_normalized = img_normalized[None]img_tensor_list.append(img_normalized)original_sizes[serial] = original_sizeimage_input = torch.cat(img_tensor_list)return image_input, original_sizesdef _postprocess_predictions(self, predictions, original_sizes):results = {}for i, (det, (serial, img)) in enumerate(zip(predictions, original_sizes.items())):if det is not None and len(det):det[:, :4] = scale_boxes(self.img_size, det[:, :4], img).round()labels = []coordinates = []for *xyxy, conf, cls in reversed(det):label = self.model.names[int(cls)]labels.append((label, conf.item()))coordinates.append([xyxy[0].item(), xyxy[1].item(), xyxy[2].item(), xyxy[3].item()])results[serial] = {'labels': labels,'coordinates': coordinates}return resultsdef predict(self, img_dict):start_total = time.time()start_preprocess = time.time()img_tensor, original_sizes = self._preprocess_image(img_dict)preprocess_time = time.time() - start_preprocessprint(f"Preprocess Time: {preprocess_time * 1000:.2f}ms")start_inference = time.time()with torch.no_grad():predictions = self.model(img_tensor)inference_time = time.time() - start_inferenceprint(f"Inference Time:{inference_time * 1000:.2f}ms")start_non_max_suppression = time.time()predictions = non_max_suppression(predictions, self.conf_threshold, self.iou_threshold)non_max_suppression_time = time.time() - start_non_max_suppressionprint(f"Non-Max Suppression Time: {non_max_suppression_time * 1000:.2f}ms")start_postprocess = time.time()results = self._postprocess_predictions(predictions, original_sizes)postprocess_time = time.time() - start_postprocessprint(f"Postprocess Time: {postprocess_time * 1000:.2f}ms")total_time = time.time() - start_totalprint(f"Total Processing Time: {total_time * 1000:.2f}ms")print("res:",results)return resultsdef draw_results(self, img_dict, results):annotated_images = {}for serial, img in img_dict.items():if serial in results:det = results[serial]['coordinates']  # 从 results 中提取处理后的坐标labels = results[serial]['labels']  # 提取标签和置信度annotator = Annotator(img, line_width=3, example=self.model.names)for i, (xyxy, (label, conf)) in enumerate(zip(det, labels)):# 生成标签信息label_str = f'{label} {conf:.2f}'# 绘制检测框和标签annotator.box_label(xyxy, label_str, color=colors(i, True))annotated_images[serial] = annotator.result()return annotated_imagesdef _save_labels(self, results, output_folder, batch_size=3):os.makedirs(output_folder, exist_ok=True)img_serials = list(results.keys())for i in range(0, len(img_serials), batch_size):batch = img_serials[i:i + batch_size]combined_filename = '_'.join(batch) + '_labels.txt'labels_path = os.path.join(output_folder, combined_filename)with open(labels_path, 'w') as file:for serial in batch:if serial in results:result = results[serial]file.write("{\n")file.write(f"  'serial': '{result['serial']}',\n")file.write(f"  'labels': {result['labels']},\n")file.write(f"  'coordinates': {result['coordinates']},\n")file.write("}\n\n")if __name__ == "__main__":model_path = 'data/pt/best.pt'detector = DetectionEstimation(model_path)img_folder = './data/images/'img_dict = {}img_filenames = []for img_filename in os.listdir(img_folder):img_path = os.path.join(img_folder, img_filename)if img_path.lower().endswith(('.png', '.jpg', '.jpeg')):img_data = cv2.imread(img_path)serial = os.path.splitext(img_filename)[0]img_dict[serial] = img_dataimg_filenames.append(img_filename)batch_size = 2img_keys = list(img_dict.keys())for i in range(0, len(img_keys), batch_size):batch_dict = {k: img_dict[k] for k in img_keys[i:i + batch_size]}results = detector.predict(batch_dict)annotated_images = detector.draw_results(batch_dict, results)os.makedirs('results', exist_ok=True)for serial, img in annotated_images.items():output_path = f'results/{serial}.jpg'success = cv2.imwrite(output_path, img)if not success:print(f'Error saving image {output_path}')else:print(f'Successfully saved image {output_path}')detector._save_labels(results, 'results/labels', batch_size=batch_size)

在该代码同级目录下放models、results、utils文件夹和export.py

运行该代码得到的txt文件是字典:

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

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

相关文章

工业交换机如何保证数据的访问安全

在现代工业自动化环境中,工业交换机作为关键的网络设备,扮演着数据传输和信息交互的重要角色。为了确保数据的访问安全,工业交换机不仅具备高效的转发性能,还集成了多层次的安全防护机制,以抵御各种潜在的网络威胁。 首…

输电线螺栓销钉缺失检测数据集

输电线螺栓销钉缺失检测数据集共1209张。标注文件为YOLO适用的txt格式以及VOC格式。可以直接用于模型训练。 类别:缺失和不缺失 包含yolov7tiny训练验证结果以及权重文件和数据集。 数据集亮点: 丰富的图像资源: 本数据集包含1209张高质量…

PHP及Java等其他语言转Go时选择GoFly快速快速开发框架指南

概要 经过一年多的发展GoFly快速开发框架已被一千多家科技企业或开发者用于项目开发,他的简单易学得到其他语言转Go首选框架。且企业版的发展为GoFly社区提供资金,这使得GoFly快速框架得到良好的发展,GoFly技术团队加大投入反哺科技企业和开…

268页PPT大型集团智慧工厂信息化顶层架构设计(2024版)

智能制造装备是高端制造业的关键,通过整合智能传感、控制、AI等技术,具备了信息感知、分析规划等智能化功能,能显著提升加工质量、效率和降低成本。该装备是先进制造、信息、智能技术的深度融合。其原理主要包括物联网集成、大数据分析与人工…

Windows Server2016多用户登录破解

使用场景 很多时候,公司开发和测试运维会同时登录同一台windows服务器进行查询、更新、维护等操作,本文就来介绍一下Windows2016配置多人远程桌面登录实现,感兴趣的可以了解一下。 操作流程 (1)首先桌面需要安装远程…

详解x86汇编指令:test edx, edx

前言 有不少新手在学习汇编指令的时候可能会被网上一些人误导(很显然我就被误导了),认为test与cmp指令相同,都是在比较两个值是否相同的,那么来看这两个指令: test edx,edx jne 0040BCA3jne 指令为不等于0…

18.DHT11编程案例

温湿度传感器 产品概述 DHT11数字温湿度传感器是一款含有已校准数字信号输出的温湿度复合传感器,应用领域:暖通 空调;汽车;消费品;气象站;湿度调节器;除湿器;家电;医疗…

技术美术百人计划 | 《4.1 Bloom算法》笔记

1. Bloom算法介绍 1.1. Bloom效果 实际拍摄照片与游戏画面Bloom效果对比,Bloom模拟了真实世界图片的效果 Bloom流程图 1.2. 前置知识:HDR和LDR,高斯模糊 1.2.1. HDR和LDR LDR颜色范围太少,精度不够,往往会存在颜色精…

Prometheus 上手指南

文章目录 Prometheus 相关概念Prometheus 的特点Prometheus 架构数据模型 Datemode使用场景 指标类型 Metric type适用场景 作业和实例 Jobs and instances使用场景 Prometheus 安装Prometheus 配置prometheusalertmanager Grafana 可视化Grafana 安装Grafana 配置选项Grafana …

微信小程序开发第五课

一 vant-app # https://vant-contrib.gitee.io/vant-weapp/#/home1.1 集成步骤 # 0 必须使用专门为小程序提供的npm包,通常好多包用不了,比如第三方包用了dom,小程序没有 https://developers.weixin.qq.com/miniprogram/dev/devtools/npm.h…

MATLAB画图,曲线图如何绘制美观,曲线图10种美化方法

曲线图是比较常用的图形,本文以二维曲线图为例,展示曲线的图的不同美化方法,如图1所示,是一个标准的曲线图,横坐标为x,纵坐标为y, 图1 标准曲线图 调整方法1 首先可以通过改变线的颜色,不同…

使用API有效率地管理Dynadot域名,为域名进行隐私保护设置

前言 Dynadot是通过ICANN认证的域名注册商,自2002年成立以来,服务于全球108个国家和地区的客户,为数以万计的客户提供简洁,优惠,安全的域名注册以及管理服务。 Dynadot平台操作教程索引(包括域名邮箱&…

js中的 赋值 浅拷贝 和 深拷贝 详细解读

js数据类型主要分基本数据类型和引用数据类型。前者包括Number,String等,后者主要是Object,因此以下会针对不同的数据类型来分析,需要的朋友可以参考一下 基本数据类型(Primary Data Types): String(字符串) Number&…

【4】AT32F437 OpenHarmony轻量系统移植教程(1)

开源地址:https://gitee.com/AT32437_OpenHarmony 1.学习本文档的意义 1.学习移植OpenHarmony轻量系统到AT32全系列mcu上,本文档移植的具体型号为AT32F437ZMT7 2.学习OpenHarmony轻量系统开发 2.移植前的准备工作 1.移植之前必须要先熟悉AT-START-F…

C:字符串函数(完)-学习笔记

目录 前言: 1、strstr 1.1 strstr的使用 4.2 strstr的模拟实现 5、strtok 5.1 strtok函数的介绍 5.2 strtok函数的使用 6、strerror 前言: 这篇文章将介绍strstr函数,strtok函数,strerror函数 1、strstr 1.1 strstr的使用…

Android JetPack系列之——Navigation

[转] 由于Android的开源性,在开始的几年呈现出了百家齐放的盛况,层出不穷的API和以及官方的API各自大放异彩,在丰富了android生态的同时也带来了一个很严重的问题,即android 的碎片化和规范化的问题。碎片化主要集中于国内的各大…

MYSQL解说

MySQL是一个流行的开源关系型数据库管理系统(RDBMS),广泛用于网站和应用程序的后端数据存储。 MySQL的基础知识: 1. 数据库和表 数据库(Database):存储数据的逻辑容器。表(Table&…

MT8370|MTK8370(Genio 510 )安卓核心板参数介绍

MTK Genio 510 (MT8370)安卓核心板是一款极为先进的高性能平台,专为满足边缘处理、先进多媒体功能及全面的连接需求而设计,适用于多种人工智能(AI)和物联网(IoT)应用场景。它具备多个高分辨率摄像头支持和可联网触摸屏显示,适用于使用多任务高…

使用PyTorch检测和验证多GPU环境的Python脚本

使用PyTorch检测和验证多GPU环境的Python脚本 在深度学习和机器学习中,GPU的计算能力对模型训练和推理的速度有着极大的影响。随着多GPU系统的普及,如何确保多GPU能被正确识别并使用,是一个非常关键的问题。本文将为大家介绍一段简洁的Pytho…

怎么理解机器学习与数据融合的集成?

在科技进步的浪潮中,数据的重要性日益成为共识。但数据本身,若不经过有效的整合与分析,其价值便难以充分发挥。本文将探讨如何通过集成数据融合与机器学习,提升预测和决策的准确性。将海量数据转化为富含洞察力的信息,…