在mmrotate中新建一个detect.py文件,写入以下代码即可实现对一个文件夹内的多张图片进行推理检测。
import os
from argparse import ArgumentParser
from mmdet.apis import inference_detector, init_detector, show_result_pyplot
import mmrotate # noqa: F401
def parse_args():
parser = ArgumentParser()
parser.add_argument('img_dir', help='Directory of images')
parser.add_argument('config', help='Config file')
parser.add_argument('checkpoint', help='Checkpoint file')
parser.add_argument('--out-dir', default='./output', help='Path to output directory')
parser.add_argument(
'--device', default='cuda:0', help='Device used for inference')
parser.add_argument(
'--palette',
default='dota',
choices=['dota', 'sar', 'hrsc', 'hrsc_classwise', 'random'],
help='Color palette used for visualization')
parser.add_argument(
'--score-thr', type=float, default=0.3, help='bbox score threshold')
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)
# Create output directory if it doesn't exist
if not os.path.exists(args.out_dir):
os.makedirs(args.out_dir)
# Iterate through all images in the directory
for img_file in os.listdir(args.img_dir):
if img_file.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp')):
img_path = os.path.join(args.img_dir, img_file)
# test the image
result = inference_detector(model, img_path)
# show the results
out_file = os.path.join(args.out_dir, img_file)
show_result_pyplot(
model,
img_path,
result,
palette=args.palette,
score_thr=args.score_thr,
out_file=out_file)
if __name__ == '__main__':
args = parse_args()
main(args)
在终端中调用:
python demo/image_demo.py <存储图片的文件夹路径> <模型配置文件.py> <模型权重文件.pth> --out-dir <输出结果的存储文件夹路径>
示例如下:
python demo/image_demo.py data/temp/images my_demo/output/work_dir/two_stage/oriented_rcnn/train_0.01/my_oriented_rcnn_r50_fpn_1x_dota_le90.py my_demo/output/work_dir/two_stage/oriented_rcnn/train_0.01/best_mAP_epoch_14.pth --out-dir data/temp/detect