mmdetection中使用训练好的模型批量检测图片并保存到文件夹

保存到文件夹查看预测情况

from argparse import ArgumentParser
import os
from mmdet.apis import inference_detector, init_detector  #, show_result_pyplot
import cv2

def show_result_pyplot(model, img, result, score_thr=0.3, fig_size=(15, 10)):
    """Visualize the detection results on the image.

    Args:
        model (nn.Module): The loaded detector.
        img (str or np.ndarray): Image filename or loaded image.
        result (tuple[list] or list): The detection result, can be either
            (bbox, segm) or just bbox.
        score_thr (float): The threshold to visualize the bboxes and masks.
        fig_size (tuple): Figure size of the pyplot figure.
    """
    if hasattr(model, 'module'):
        model = model.module
    img = model.show_result(img, result, score_thr=score_thr, show=False)
    return img
    # plt.figure(figsize=fig_size)
    # plt.imshow(mmcv.bgr2rgb(img))
    # plt.show()


def main():
    # config文件
    config_file = '/mmdetection-master/work_dirs/faster_rcnn_r50_fpn_1x_voc0712.py'
    # 训练好的模型
    checkpoint_file = '/mmdetection-master/work_dirs/epoch_100.pth'

    # model = init_detector(config_file, checkpoint_file)
    model = init_detector(config_file, checkpoint_file, device='cuda:0')

    # 图片路径
    img_dir = '/data/VOCdevkit/VOC2007/JPEGImages/'
    # 检测后存放图片路径
    out_dir = '/mmdetection-master/frcnn_result/'

    if not os.path.exists(out_dir):
        os.mkdir(out_dir)
    
    # 测试集的图片名称txt
    test_path = '/data/VOCdevkit/VOC2007/ImageSets/Main/test.txt'
    fp = open(test_path, 'r')
    test_list = fp.readlines()

    count = 0
    imgs = []
    for test in test_list:
        test = test.replace('\n', '')
        name = img_dir + test + '.jpg'
        
        count += 1
        print('model is processing the {}/{} images.'.format(count, len(test_list)))
        # result = inference_detector(model, name)
        # model = init_detector(config_file, checkpoint_file, device='cuda:0')
        result = inference_detector(model, name)
        img = show_result_pyplot(model, name, result, score_thr=0.8)
        cv2.imwrite("{}/{}.jpg".format(out_dir, test), img)


if __name__ == '__main__':
    main()

 

  • 6
    点赞
  • 50
    收藏
    觉得还不错? 一键收藏
  • 22
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 22
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值