PaddleDetection 模型推理测试

2021SC@SDUSC
本周分析

#tools/infer.py
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os, sys
# add python path of PadleDetection to sys.path
parent_path = os.path.abspath(os.path.join(__file__, *(['..'] * 2)))
if parent_path not in sys.path:
    sys.path.append(parent_path)

# ignore numba warning
import warnings
warnings.filterwarnings('ignore')
import glob
import numpy as np
from PIL import Image

import paddle
from paddle.distributed import ParallelEnv
from ppdet.core.workspace import load_config, merge_config, create
from ppdet.utils.check import check_gpu, check_version, check_config
from ppdet.utils.visualizer import visualize_results
from ppdet.utils.cli import ArgsParser
from ppdet.utils.checkpoint import load_weight
from ppdet.utils.eval_utils import get_infer_results

from ppdet.utils.logger import setup_logger
logger = setup_logger('train')

#运行配置参数解析函数
def parse_args():
    parser = ArgsParser()
    parser.add_argument(
        "--infer_dir",
        type=str,
        default=None,
        help="Directory for images to perform inference on.")
    parser.add_argument(
        "--infer_img",
        type=str,
        default=None,
        help="Image path, has higher priority over --infer_dir")
    parser.add_argument(
        "--output_dir",
        type=str,
        default="output",
        help="Directory for storing the output visualization files.")
    parser.add_argument(
        "--draw_threshold",
        type=float,
        default=0.5,
        help="Threshold to reserve the result for visualization.")
    parser.add_argument(
        "--slim_config",
        default=None,
        type=str,
        help="Configuration file of slim method.")
    parser.add_argument(
        "--use_vdl",
        type=bool,
        default=False,
        help="Whether to record the data to VisualDL.")
    parser.add_argument(
        '--vdl_log_dir',
        type=str,
        default="vdl_log_dir/image",
        help='VisualDL logging directory for image.')
    parser.add_argument(
        "--save_txt",
        type=bool,
        default=False,
        help="Whether to save inference result in txt.")
    args = parser.parse_args()
    return args



# 获取测试图片函数
def get_test_images(infer_dir, infer_img):
    """
    Get image path list in TEST mode
    """
    assert infer_img is not None or infer_dir is not None, \
        "--infer_img or --infer_dir should be set"
    assert infer_img is None or os.path.isfile(infer_img), \
            "{} is not a file".format(infer_img)
    assert infer_dir is None or os.path.isdir(infer_dir), \
            "{} is not a directory".format(infer_dir)

    # infer_img has a higher priority
    if infer_img and os.path.isfile(infer_img):
        return [infer_img]

    images = set()
    infer_dir = os.path.abspath(infer_dir)
    assert os.path.isdir(infer_dir), \
        "infer_dir {} is not a directory".format(infer_dir)
    exts = ['jpg', 'jpeg', 'png', 'bmp']
    exts += [ext.upper() for ext in exts]
    for ext in exts:
        images.update(glob.glob('{}/*.{}'.format(infer_dir, ext)))
    images = list(images)

    assert len(images) > 0, "no image found in {}".format(infer_dir)
    logger.info("Found {} inference images in total.".format(len(images)))

    return images

#run函数,detection套件执行的核心部分

def run(FLAGS, cfg):
    # build trainer   *******************注册模型,最最核心部分**********************
    trainer = Trainer(cfg, mode='test')

    # load weights   #加载模型权重
    trainer.load_weights(cfg.weights)

    # get inference images  #获取推理数据
    images = get_test_images(FLAGS.infer_dir, FLAGS.infer_img)

    # inference    #执行推理,(图片数据、阈值、结果保存目录、文本保存)
    trainer.predict(
        images,
        draw_threshold=FLAGS.draw_threshold,
        output_dir=FLAGS.output_dir,
        save_txt=FLAGS.save_txt)


#主函数定义
def main():


    FLAGS = parse_args()   #加载运行参数
    cfg = load_config(FLAGS.config)   #加载yaml配置
    cfg['use_vdl'] = FLAGS.use_vdl  #是否启动可视化
    cfg['vdl_log_dir'] = FLAGS.vdl_log_dir  #可视化文件目录
    merge_config(FLAGS.opt)   #合并配置
    #执行环境配置
    place = paddle.set_device('gpu' if cfg.use_gpu else 'cpu')
    # 是否采用同步BN
    if 'norm_type' in cfg and cfg['norm_type'] == 'sync_bn' and not cfg.use_gpu:
        cfg['norm_type'] = 'bn'
    #slim_config配置
    if FLAGS.slim_config:
        cfg = build_slim_model(cfg, FLAGS.slim_config, mode='test')
    #检查配置文件是否正确
    check_config(cfg)
    check_gpu(cfg.use_gpu)
    check_version()
    #执行run函数
    run(FLAGS, cfg)


#程序入口
if __name__ == '__main__':
    main()#主函数入口

###########infer.py流程解析###############
从程序入口开始(if name == ‘main’:)
1.直接进入main函数
初始化训练参数:
①.parser = ArgsParser() #读取命令行传递参数,加载yaml文件参数
②.将参数整合在一起,检查参数配置是否正确
③.是否使用GPU加速
④.查看paddledet版本是否正确
⑤.进入run()函数
配置阶段
a.创建网络结构类
b.初始化模型权重,加载预训练模型
c.创建数据读取类
d.选择推理标准
开启推理
e.遍历数据,开启前向推理,收集结果
f.保存推理结果(box or mask)
g.使用VisualDL保存图片结果
直到迭代结束输出结果

你可能感兴趣的:(笔记,pytorch,人工智能,python)