以下代码亲测可用
自建test.py
,测试Faster R-CNN模型:
# coding=utf-8
import mmcv
from mmdet.apis import init_detector
from mmdet.apis import inference_detector
from mmdet.apis import show_result_pyplot
# from mmdet.models.detectors.base import BaseDetector
# 模型配置文件
config_file = '/home/cv/mmdetection/configs/faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py'
# 预训练模型文件
checkpoint_file = '/home/cv/mmdetection/checkpoints/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth'
# 通过模型配置文件与预训练文件构建模型
model = init_detector(config_file, checkpoint_file, device='cuda:0')
# 测试单张图片并进行展示
# img = '/home/cv/mmdetection/my_pictures/cars1.jpeg'
img = '/home/cv/mmdetection/my_pictures/peoples1.jpeg'
result = inference_detector(model, img)
show_result_pyplot(model, img, result)
# 测试一个图像列表并保存结果图像
# imgs = ['test1.jpg', 'test2.jpg', 'test3.jpg']
# for i, result in enumerate(inference_detector(model, imgs)):
# show_result_pyplot(model, imgs[i], result)
结果
也可以用自带的测试文件demo/image_demo.py
,测试Mask R-CNN模型:
python demo/image_demo.py demo/demo.jpg configs/mask_rcnn/mask_rcnn_r50_fpn_1x_coco.py checkpoints/mask_rcnn_r50_fpn_1x_coco_20200205-d4b0c5d6.pth
import asyncio
from argparse import ArgumentParser
from mmdet.apis import (async_inference_detector, inference_detector,
init_detector, show_result_pyplot)
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(
'--device', default='cuda:0', help='Device used for inference')
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):
# build the model from a config file and a checkpoint file
model = init_detector(args.config, args.checkpoint, device=args.device)
# test a single image
result = inference_detector(model, args.img)
# show the results
show_result_pyplot(model, args.img, result, score_thr=args.score_thr)
async def async_main(args):
# build the model from a config file and a checkpoint file
model = init_detector(args.config, args.checkpoint, device=args.device)
# test a single image
tasks = asyncio.create_task(async_inference_detector(model, args.img))
result = await asyncio.gather(tasks)
# show the results
show_result_pyplot(model, args.img, result[0], score_thr=args.score_thr)
if __name__ == '__main__':
args = parse_args()
if args.async_test:
asyncio.run(async_main(args))
else:
main(args)