当前位置: 首页 > news >正文

可视化脚本用于使用MMDetection库进行图像的目标检测

# Copyright (c) OpenMMLab. All rights reserved.
import asyncio
from argparse import ArgumentParserfrom mmdet.apis import (async_inference_detector, inference_detector,init_detector, show_result_pyplot)
import denseclip# 解析命令行参数
def parse_args():parser = ArgumentParser()parser.add_argument('img', help='Image file')  # 图像文件路径parser.add_argument('config', help='Config file')  # 配置文件路径parser.add_argument('checkpoint', help='Checkpoint file')  # 检查点文件路径parser.add_argument('--out-file', default=None, help='Path to output file')  # 输出结果文件路径parser.add_argument('--device', default='cuda:0', help='Device used for inference')  # 使用进行推理的设备parser.add_argument('--palette',default='coco',choices=['coco', 'voc', 'citys', 'random'],help='Color palette used for visualization')  # 可视化使用的颜色调色板parser.add_argument('--score-thr', type=float, default=0.3, help='bbox score threshold')  # 框得分阈值parser.add_argument('--async-test',action='store_true',help='whether to set async options for async inference.')  # 是否进行异步推理args = parser.parse_args()return args# 主函数
def main(args):# 从配置文件和检查点文件构建模型model = init_detector(args.config, args.checkpoint, device=args.device)# 对单张图像进行测试result = inference_detector(model, args.img)# 显示结果show_result_pyplot(model,args.img,result,palette=args.palette,score_thr=args.score_thr,out_file=args.out_file)# 异步主函数
async def async_main(args):# 从配置文件和检查点文件构建模型model = init_detector(args.config, args.checkpoint, device=args.device)# 对单张图像进行异步测试tasks = asyncio.create_task(async_inference_detector(model, args.img))result = await asyncio.gather(tasks)# 显示结果show_result_pyplot(model,args.img,result[0],palette=args.palette,score_thr=args.score_thr,out_file=args.out_file)# 主程序入口
if __name__ == '__main__':args = parse_args()if args.async_test:asyncio.run(async_main(args))  # 如果设置了异步选项,则运行异步主函数else:main(args)  # 否则运行同步主函数

用命令行指定具体文件

基本示例

python your_script.py path/to/image.jpg path/to/config.py path/to/checkpoint.pth

指定输出文件

python your_script.py path/to/image.jpg path/to/config.py path/to/checkpoint.pth --out-file path/to/output.jpg

设置边界框得分阈值

python your_script.py path/to/image.jpg path/to/config.py path/to/checkpoint.pth --score-thr 0.5

或者用下面的分布式测试

import argparse
import os
import warningsimport mmcv
import torch
from mmcv import Config, DictAction
from mmcv.cnn import fuse_conv_bn
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv.runner import (get_dist_info, init_dist, load_checkpoint,wrap_fp16_model)from mmdet.apis import multi_gpu_test, single_gpu_test
from mmdet.datasets import (build_dataloader, build_dataset,replace_ImageToTensor)
from mmdet.models import build_detector
import denseclipdef parse_args():parser = argparse.ArgumentParser(description='MMDet test (and eval) a model')parser.add_argument('config', help='test config file path')parser.add_argument('checkpoint', help='checkpoint file')parser.add_argument('--out', help='output result file in pickle format')parser.add_argument('--fuse-conv-bn',action='store_true',help='Whether to fuse conv and bn, this will slightly increase''the inference speed')parser.add_argument('--format-only',action='store_true',help='Format the output results without perform evaluation. It is''useful when you want to format the result to a specific format and ''submit it to the test server')parser.add_argument('--eval',type=str,nargs='+',help='evaluation metrics, which depends on the dataset, e.g., "bbox",'' "segm", "proposal" for COCO, and "mAP", "recall" for PASCAL VOC')parser.add_argument('--show', action='store_true', help='show results')parser.add_argument('--show-dir', help='directory where painted images will be saved')parser.add_argument('--show-score-thr',type=float,default=0.3,help='score threshold (default: 0.3)')parser.add_argument('--gpu-collect',action='store_true',help='whether to use gpu to collect results.')parser.add_argument('--tmpdir',help='tmp directory used for collecting results from multiple ''workers, available when gpu-collect is not specified')parser.add_argument('--cfg-options',nargs='+',action=DictAction,help='override some settings in the used config, the key-value pair ''in xxx=yyy format will be merged into config file. If the value to ''be overwritten is a list, it should be like key="[a,b]" or key=a,b ''It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" ''Note that the quotation marks are necessary and that no white space ''is allowed.')parser.add_argument('--options',nargs='+',action=DictAction,help='custom options for evaluation, the key-value pair in xxx=yyy ''format will be kwargs for dataset.evaluate() function (deprecate), ''change to --eval-options instead.')parser.add_argument('--eval-options',nargs='+',action=DictAction,help='custom options for evaluation, the key-value pair in xxx=yyy ''format will be kwargs for dataset.evaluate() function')parser.add_argument('--launcher',choices=['none', 'pytorch', 'slurm', 'mpi'],default='none',help='job launcher')parser.add_argument('--local_rank', type=int, default=0)args = parser.parse_args()if 'LOCAL_RANK' not in os.environ:os.environ['LOCAL_RANK'] = str(args.local_rank)if args.options and args.eval_options:raise ValueError('--options and --eval-options cannot be both ''specified, --options is deprecated in favor of --eval-options')if args.options:warnings.warn('--options is deprecated in favor of --eval-options')args.eval_options = args.optionsreturn argsdef main():args = parse_args()assert args.out or args.eval or args.format_only or args.show \or args.show_dir, \('Please specify at least one operation (save/eval/format/show the ''results / save the results) with the argument "--out", "--eval"'', "--format-only", "--show" or "--show-dir"')if args.eval and args.format_only:raise ValueError('--eval and --format_only cannot be both specified')if args.out is not None and not args.out.endswith(('.pkl', '.pickle')):raise ValueError('The output file must be a pkl file.')cfg = Config.fromfile(args.config)if args.cfg_options is not None:cfg.merge_from_dict(args.cfg_options)# import modules from string list.if cfg.get('custom_imports', None):from mmcv.utils import import_modules_from_stringsimport_modules_from_strings(**cfg['custom_imports'])# set cudnn_benchmarkif cfg.get('cudnn_benchmark', False):torch.backends.cudnn.benchmark = Truecfg.model.pretrained = Noneif cfg.model.get('neck'):if isinstance(cfg.model.neck, list):for neck_cfg in cfg.model.neck:if neck_cfg.get('rfp_backbone'):if neck_cfg.rfp_backbone.get('pretrained'):neck_cfg.rfp_backbone.pretrained = Noneelif cfg.model.neck.get('rfp_backbone'):if cfg.model.neck.rfp_backbone.get('pretrained'):cfg.model.neck.rfp_backbone.pretrained = None# in case the test dataset is concatenatedif isinstance(cfg.data.test, dict):cfg.data.test.test_mode = Trueelif isinstance(cfg.data.test, list):for ds_cfg in cfg.data.test:ds_cfg.test_mode = True# init distributed env first, since logger depends on the dist info.if args.launcher == 'none':distributed = Falseelse:distributed = Trueinit_dist(args.launcher, **cfg.dist_params)# build the dataloadersamples_per_gpu = cfg.data.test.pop('samples_per_gpu', 1)if samples_per_gpu > 1:# Replace 'ImageToTensor' to 'DefaultFormatBundle'cfg.data.test.pipeline = replace_ImageToTensor(cfg.data.test.pipeline)dataset = build_dataset(cfg.data.test)data_loader = build_dataloader(dataset,samples_per_gpu=samples_per_gpu,workers_per_gpu=cfg.data.workers_per_gpu,dist=distributed,shuffle=False)# build the model and load checkpointif 'DenseCLIP' in cfg.model.type:cfg.model.class_names = list(dataset.CLASSES)if not hasattr(cfg, 'test_cfg'):cfg.test_cfg = Nonemodel = build_detector(cfg.model, train_cfg=None, test_cfg=cfg.test_cfg)fp16_cfg = cfg.get('fp16', None)if fp16_cfg is not None:wrap_fp16_model(model)checkpoint = load_checkpoint(model, args.checkpoint, map_location='cpu')if args.fuse_conv_bn:model = fuse_conv_bn(model)# old versions did not save class info in checkpoints, this walkaround is# for backward compatibilityif 'CLASSES' in checkpoint['meta']:model.CLASSES = checkpoint['meta']['CLASSES']else:model.CLASSES = dataset.CLASSESif not distributed:model = MMDataParallel(model, device_ids=[0])outputs = single_gpu_test(model, data_loader, args.show, args.show_dir,args.show_score_thr)else:model = MMDistributedDataParallel(model.cuda(),device_ids=[torch.cuda.current_device()],broadcast_buffers=False)outputs = multi_gpu_test(model, data_loader, args.tmpdir,args.gpu_collect)rank, _ = get_dist_info()if rank == 0:if args.out:print(f'\nwriting results to {args.out}')mmcv.dump(outputs, args.out)kwargs = {} if args.eval_options is None else args.eval_optionsif args.format_only:dataset.format_results(outputs, **kwargs)if args.eval:eval_kwargs = cfg.get('evaluation', {}).copy()# hard-code way to remove EvalHook argsfor key in ['interval', 'tmpdir', 'start', 'gpu_collect', 'save_best','rule']:eval_kwargs.pop(key, None)eval_kwargs.update(dict(metric=args.eval, **kwargs))print(dataset.evaluate(outputs, **eval_kwargs))if __name__ == '__main__':main()

相关文章:

可视化脚本用于使用MMDetection库进行图像的目标检测

# Copyright (c) OpenMMLab. All rights reserved. import asyncio from argparse import ArgumentParserfrom mmdet.apis import (async_inference_detector, inference_detector,init_detector, show_result_pyplot) import denseclip# 解析命令行参数 def parse_args():pars…...

React-组件通信

组件通信 概念:组件通信就是组件之间的数据传递,根据组件嵌套关系的不同,有不同的通信方法 父传子 基础实现 实现步骤: 1.父组件传递数据-在子组件标签上绑定属性 2.子组件接收数据-子组件通过props参数接收数据 props说明 1.…...

低代码选型要注意什么问题?

低代码选型时,确实需要从多个角度综合考虑,以下是根据您给出的角度进行的分析和建议: 公司的人才资源: 评估团队中是否有具备编程能力的开发人员,以确保能够充分利用低代码平台的高级功能和进行必要的定制开发。考察实…...

hive切换spark引擎倒入数据乱码

...

fpga入门 串口定时1秒发送1字节

一、 程序说明 FPGA通过串口定时发送数据,每秒发送1字节,数据不断自增 参考小梅哥教程 二、 uart_tx.v timescale 1ns / 1psmodule uart_tx(input wire sclk,input wire rst_n,output reg uart_tx);parameter …...

总结一下自己,最近三年,我做了哪些工作

简单总结下吧,我算是业务架构师,确实对得起这个名字,经常冲在一线,业务和架构相关的东西都有做,系统比较复杂,不过逐步了解谁都会熟悉的 下面简单列一列我这三年的工作情况吧,也算是给自己一个交…...

SpringCloud Gateway基础入门与使用实践总结

官网文档:点击查看官网文档 Cloud全家桶中有个很重要的组件就是网关,在1.x版本中都是采用的Zuul网关。但在2.x版本中,zuul的升级一直跳票,SpringCloud最后自己研发了一个网关替代Zuul,那就是SpringCloud Gateway一句话…...

TensorBoard在pytorch训练过程中如何使用,及数据读取问题解决方法

TensorBoard 模块导入日志记录文件的创建训练中如何写入数据如何提取保存的数据调用TensorBoard面板可能会遇到的问题 模块导入 首先从torch中导入tensorboard的SummaryWriter日志记录模块 from torch.utils.tensorboard import SummaryWriter然后导入要用到的os库&#xff0…...

【Vue】普通组件的注册使用-全局注册

文章目录 一、使用步骤二、练习 一、使用步骤 步骤 创建.vue组件&#xff08;三个组成部分&#xff09;main.js中进行全局注册 使用方式 当成HTML标签直接使用 <组件名></组件名> 注意 组件名规范 —> 大驼峰命名法&#xff0c; 如 HmHeader 技巧&#xf…...

爬虫之反爬思路与解决手段

阅读时间建议&#xff1a;4分钟 本篇概念比较多&#xff0c;嗯。。 0x01 反爬思路与解决手段 1、服务器反爬虫的原因 因为爬虫的访问次数高&#xff0c;浪费资源&#xff0c;公司资源被批量抓走&#xff0c;丧失竞争力&#xff0c;同时也是法律的灰色地带。 2、服务器反什么…...

2.1.4 采用配置类与注解方式使用MyBatis

实战概述&#xff1a;采用配置类与注解方式使用MyBatis 创建MyBatis配置类 在net.huawei.mybatis.config包中创建MyBatisConfig类&#xff0c;用于配置MyBatis核心组件&#xff0c;包括数据源、事务工厂和环境设置。 配置数据源和事务 使用PooledDataSource配置MySQL数据库连接…...

微信小程序云开发实现利用云函数将数据库表的数据导出到excel中

实现目标 将所有订单信息导出到excel表格中 思路 1、在页面中bindtap绑定一个导出点击事件daochu() 2、先获取所有订单信息&#xff0c;并将数据添加到List数组中 3、传入以List数组作为参数&#xff0c;调用get_excel云函数 4、get_excel云函数利用node-xlsx第三方库&#…...

python 字符串(str)、列表(list)、元组(tuple)、字典(dict)

学习目标: 1:能够知道如何定义一个字符串; [重点] 使用双引号引起来: 变量名 "xxxx" 2:能够知道切片的语法格式; [重点] [起始: 结束] 3:掌握如何定义一个列表; [重点] 使用[ ]引起来: 变量名 [xx,xx,...] 4:能够说出4个列表相关的方法; [了解] ap…...

【源码】SpringBoot事务注册原理

前言 对于数据库的操作&#xff0c;可能存在脏读、不可重复读、幻读等问题&#xff0c;从而引入了事务的概念。 事务 1.1 事务的定义 事务是指在数据库管理系统中&#xff0c;一系列紧密相关的操作序列&#xff0c;这些操作作为一个单一的工作单元执行。事务的特点是要么全…...

技巧:合并ZIP分卷压缩包

如果ZIP压缩文件文件体积过大&#xff0c;大家可能会选择“分卷压缩”来压缩ZIP文件&#xff0c;那么&#xff0c;如何合并zip分卷压缩包呢&#xff1f;今天我们分享两个ZIP分卷压缩包合并的方法给大家。 方法一&#xff1a; 我们可以将分卷压缩包&#xff0c;通过解压的方式…...

数据挖掘 | 实验三 决策树分类算法

文章目录 一、目的与要求二、实验设备与环境、数据三、实验内容四、实验小结 一、目的与要求 1&#xff09;熟悉决策树的原理&#xff1b; 2&#xff09;熟练使用sklearn库中相关决策树分类算法、预测方法&#xff1b; 3&#xff09;熟悉pydotplus、 GraphViz等库中决策树模型…...

Python机器学习预测区间估计工具库之mapie使用详解

概要 在数据科学和机器学习领域,预测的不确定性估计是一个非常重要的课题。Python的mapie库是一种专注于预测区间估计的工具,旨在提供简单易用的接口来计算和评估预测的不确定性。通过mapie库,用户可以为各种回归和分类模型计算预测区间,从而更好地理解模型预测的可靠性。…...

Linux基础指令磁盘管理002

LVM&#xff08;Logical Volume Manager&#xff09;是Linux系统中一种灵活的磁盘管理和存储解决方案&#xff0c;它允许用户在物理卷&#xff08;Physical Volumes, PV&#xff09;上创建卷组&#xff08;Volume Groups, VG&#xff09;&#xff0c;然后在卷组上创建逻辑卷&am…...

Python怎么添加库:深入解析与操作指南

Python怎么添加库&#xff1a;深入解析与操作指南 在Python编程中&#xff0c;库&#xff08;Library&#xff09;扮演着至关重要的角色。它们为我们提供了大量的函数、类和模块&#xff0c;使得我们可以更高效地编写代码&#xff0c;实现各种功能。那么&#xff0c;Python如何…...

Python | 虚拟环境的增删改查

mkvirtualenv创建虚拟环境 mkvirtualenv是用于在Pyhon中创建虚拟环境的命令。它通过使用vitualenv库来创建一个隔离的Python环境&#xff0c;以便您可以安装特定版本的Python包&#xff0c;而不会影响全局Python环境。 使用方法: 安装virtualenv&#xff1a;pip install vir…...

日语AI面试高效通关秘籍:专业解读与青柚面试智能助攻

在如今就业市场竞争日益激烈的背景下&#xff0c;越来越多的求职者将目光投向了日本及中日双语岗位。但是&#xff0c;一场日语面试往往让许多人感到步履维艰。你是否也曾因为面试官抛出的“刁钻问题”而心生畏惧&#xff1f;面对生疏的日语交流环境&#xff0c;即便提前恶补了…...

【力扣数据库知识手册笔记】索引

索引 索引的优缺点 优点1. 通过创建唯一性索引&#xff0c;可以保证数据库表中每一行数据的唯一性。2. 可以加快数据的检索速度&#xff08;创建索引的主要原因&#xff09;。3. 可以加速表和表之间的连接&#xff0c;实现数据的参考完整性。4. 可以在查询过程中&#xff0c;…...

IGP(Interior Gateway Protocol,内部网关协议)

IGP&#xff08;Interior Gateway Protocol&#xff0c;内部网关协议&#xff09; 是一种用于在一个自治系统&#xff08;AS&#xff09;内部传递路由信息的路由协议&#xff0c;主要用于在一个组织或机构的内部网络中决定数据包的最佳路径。与用于自治系统之间通信的 EGP&…...

Qwen3-Embedding-0.6B深度解析:多语言语义检索的轻量级利器

第一章 引言&#xff1a;语义表示的新时代挑战与Qwen3的破局之路 1.1 文本嵌入的核心价值与技术演进 在人工智能领域&#xff0c;文本嵌入技术如同连接自然语言与机器理解的“神经突触”——它将人类语言转化为计算机可计算的语义向量&#xff0c;支撑着搜索引擎、推荐系统、…...

令牌桶 滑动窗口->限流 分布式信号量->限并发的原理 lua脚本分析介绍

文章目录 前言限流限制并发的实际理解限流令牌桶代码实现结果分析令牌桶lua的模拟实现原理总结&#xff1a; 滑动窗口代码实现结果分析lua脚本原理解析 限并发分布式信号量代码实现结果分析lua脚本实现原理 双注解去实现限流 并发结果分析&#xff1a; 实际业务去理解体会统一注…...

[Java恶补day16] 238.除自身以外数组的乘积

给你一个整数数组 nums&#xff0c;返回 数组 answer &#xff0c;其中 answer[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积 。 题目数据 保证 数组 nums之中任意元素的全部前缀元素和后缀的乘积都在 32 位 整数范围内。 请 不要使用除法&#xff0c;且在 O(n) 时间复杂度…...

Android 之 kotlin 语言学习笔记三(Kotlin-Java 互操作)

参考官方文档&#xff1a;https://developer.android.google.cn/kotlin/interop?hlzh-cn 一、Java&#xff08;供 Kotlin 使用&#xff09; 1、不得使用硬关键字 不要使用 Kotlin 的任何硬关键字作为方法的名称 或字段。允许使用 Kotlin 的软关键字、修饰符关键字和特殊标识…...

安宝特方案丨船舶智造的“AR+AI+作业标准化管理解决方案”(装配)

船舶制造装配管理现状&#xff1a;装配工作依赖人工经验&#xff0c;装配工人凭借长期实践积累的操作技巧完成零部件组装。企业通常制定了装配作业指导书&#xff0c;但在实际执行中&#xff0c;工人对指导书的理解和遵循程度参差不齐。 船舶装配过程中的挑战与需求 挑战 (1…...

Mysql中select查询语句的执行过程

目录 1、介绍 1.1、组件介绍 1.2、Sql执行顺序 2、执行流程 2.1. 连接与认证 2.2. 查询缓存 2.3. 语法解析&#xff08;Parser&#xff09; 2.4、执行sql 1. 预处理&#xff08;Preprocessor&#xff09; 2. 查询优化器&#xff08;Optimizer&#xff09; 3. 执行器…...

Linux nano命令的基本使用

参考资料 GNU nanoを使いこなすnano基础 目录 一. 简介二. 文件打开2.1 普通方式打开文件2.2 只读方式打开文件 三. 文件查看3.1 打开文件时&#xff0c;显示行号3.2 翻页查看 四. 文件编辑4.1 Ctrl K 复制 和 Ctrl U 粘贴4.2 Alt/Esc U 撤回 五. 文件保存与退出5.1 Ctrl …...