# Copyright (c) OpenMMLab. All rights reserved.
import asyncio
from argparse import ArgumentParser
from mmdet.apis import (async_inference_detector, inference_detector,
init_detector, show_result_pyplot)
import numpy as np
import mmcv
import matplotlib.pyplot as plt
import cv2
import os
from PIL import Image
def parse_args():
parser = ArgumentParser()
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):
# build the model from a config file and a checkpoint file
model = init_detector('configs/faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py','work_dirs/faster_rcnn_r50_fpn_1x_coco/latest.pth', device=args.device)
fileurl = '1.jpg'
cv2_img = cv2.imread(fileurl)
# 推理演示图像
img = mmcv.imread(fileurl)
# 以 mmdetection 的方法进行推理
result = inference_detector(model, img)
# test a single image
#result = inference_detector(model, args.img)
# 手动获取标记框位置
bboxes = np.vstack(result)
# 手动获取推理结果标签
labels = [np.full(bbox.shape[0], i, dtype=np.int32) for i, bbox in enumerate(result)]
labels = np.concatenate(labels)
# 推理分数FCOS算法结果会多出来两个分数极低的检测框,需要将其过滤掉
scores = bboxes[:, -1]
score_thr = 0.3
inds = scores > score_thr
bboxes = bboxes[inds, :]
for i, bbox in enumerate(bboxes):
bbox_int = bbox.astype(np.int32)
poly = [[bbox_int[0], bbox_int[1]], [bbox_int[0], bbox_int[3]],
[bbox_int[2], bbox_int[3]], [bbox_int[2], bbox_int[1]]]
cv2.rectangle(cv2_img, (bbox_int[0], bbox_int[1]), (bbox_int[2], bbox_int[3]), (0, 255, 0), thickness=2)
cv2.imwrite("result.jpg", cv2_img)
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],
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)
获取mmdetection标记框坐标
最新推荐文章于 2023-06-08 22:18:26 发布