【mmdetection小目标检测教程】五、使用mmdet和mmcv的api进行图像/视频推理预测,含异步推理工作

【mmdetection小目标检测教程】五、使用mmdet和mmcv的api进行图像/视频推理预测,含异步推理工作

  • 1.图片推理
  • 2.视频推理
  • 3.异步推理

在上一篇文章中,我们已经训练出了自定义数据集的模型文件,那么这篇文件将介绍如何基于已有文件进行推理预测


mmdetection小目标检测系列教程:
一、openmmlab基础环境搭建(含mmcv、mmengine、mmdet的安装)
二、labelimg标注文件voc格式转coco格式
三、使用sahi库切分高分辨率图片,一键生成coco格式数据集
四、修改配置文件,训练专属于你的目标检测模型
五、使用mmdet和mmcv的api进行图像/视频推理预测,含异步推理工作

1.图片推理

# 导入库
from mmdet.apis import init_detector, inference_detector
import mmcv

# 选择配置文件以及权重文件,该文件位于之前指定的训练目录work_dirs/yolox_l下
config_file = 'work_dirs/yolox_l/yolox_l_8xb8-300e_coco.py'
checkpoint_file = 'work_dirs/yolox_l/latest.pth'

# 从配置文件和权重文件构建模型,使用0号GPU进行推理
model = init_detector(config_file, checkpoint_file, device='cuda:0')

# 指定预测图片
img = 'data/infer/new.jpg' 
# 也可以使用下述方法,二者取其一
#img = mmcv.imread('data/infer/new.jpg' )
# 获得推理结果
result = inference_detector(model, img)
# 结果可视化(窗口模式)
model.show_result(img, result)
# 结果可视化(保存图片模式)
model.show_result(img, result, out_file='result.jpg')

2.视频推理

# 导入库
from mmdet.apis import init_detector, inference_detector
import mmcv
# 导入视频
video = mmcv.VideoReader('data/infer/test.mp4')
# 选择配置文件以及权重文件
config_file = 'work_dirs/yolox_l/yolox_l_8xb8-300e_coco.py'
checkpoint_file = 'work_dirs/yolox_l/latest.pth'
# 从配置文件和权重文件构建模型,使用0号GPU进行推理
model = init_detector(config_file, checkpoint_file, device='cuda:0')
# 遍历每一帧
for frame in video:
	# 预测结果
    result = inference_detector(model, frame)
    # 展示结果
    model.show_result(frame, result, wait_time=1)

3.异步推理

通过利用 CUDA 流,它允许在 GPU 绑定推理代码上不阻塞 CPU,并为单线程应用程序提供更好的 CPU/GPU 利用率。推理可以在不同的输入数据样本之间或某些推理管道的不同模型之间同时进行。

# 导入库
import asyncio
import torch
from mmdet.apis import init_detector, async_inference_detector
from mmdet.utils.contextmanagers import concurrent

async def main():
	# 选择配置文件以及权重文件
    config_file = 'work_dirs/yolox_l/yolox_l_8xb8-300e_coco.py'
    checkpoint_file = 'work_dirs/yolox_l/latest.pth'
    # 指定gpu
    device = 'cuda:0'
    # 从配置文件和权重文件构建模型
    model = init_detector(config_file, checkpoint=checkpoint_file, device=device)
    # 队列用于多个图像的并发推理
    streamqueue = asyncio.Queue()
    # 队列大小定义并发级别
    streamqueue_size = 3
	
    for _ in range(streamqueue_size):
        streamqueue.put_nowait(torch.cuda.Stream(device=device))

    # 指定预测图片
    img = 'data/infer/new.jpg' 

    async with concurrent(streamqueue):
        result = await async_inference_detector(model, img)

	# 结果可视化(窗口模式)
	model.show_result(img, result)
	# 结果可视化(保存图片模式)
	model.show_result(img, result, out_file='result.jpg')


asyncio.run(main())

你可能感兴趣的:(目标检测,python,深度学习)