inference.py 2.2 KB
Newer Older
M
MegEngine Team 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# -*- coding: utf-8 -*-
# MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
#
# Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import argparse
import importlib
import os
import sys

import cv2
import numpy as np
16 17

import megengine as mge
M
MegEngine Team 已提交
18 19 20
from megengine import jit
from megengine.data.dataset import COCO

21
from official.vision.detection.tools.utils import DetEvaluator
M
MegEngine Team 已提交
22 23 24 25 26 27 28 29 30

logger = mge.get_logger(__name__)


def make_parser():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "-f", "--file", default="net.py", type=str, help="net description file"
    )
31 32 33
    parser.add_argument(
        "-w", "--weight_file", default=None, type=str, help="weights file",
    )
M
MegEngine Team 已提交
34 35 36 37 38 39 40 41
    parser.add_argument("-i", "--image", default="example.jpg", type=str)
    return parser


def main():
    parser = make_parser()
    args = parser.parse_args()

42
    logger.info("Load Model : %s completed", args.weight_file)
M
MegEngine Team 已提交
43 44 45 46 47 48 49 50

    @jit.trace(symbolic=True)
    def val_func():
        pred = model(model.inputs)
        return pred

    sys.path.insert(0, os.path.dirname(args.file))
    current_network = importlib.import_module(os.path.basename(args.file).split(".")[0])
51 52 53
    cfg = current_network.Cfg()
    cfg.backbone_pretrained = False
    model = current_network.Net(cfg, batch_size=1)
M
MegEngine Team 已提交
54
    model.eval()
55
    state_dict = mge.load(args.weight_file)
56 57 58
    if "state_dict" in state_dict:
        state_dict = state_dict["state_dict"]
    model.load_state_dict(state_dict)
M
MegEngine Team 已提交
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76

    evaluator = DetEvaluator(model)

    ori_img = cv2.imread(args.image)
    data, im_info = DetEvaluator.process_inputs(
        ori_img.copy(), model.cfg.test_image_short_size, model.cfg.test_image_max_size,
    )
    model.inputs["im_info"].set_value(im_info)
    model.inputs["image"].set_value(data.astype(np.float32))
    pred_res = evaluator.predict(val_func)
    res_img = DetEvaluator.vis_det(
        ori_img, pred_res, is_show_label=True, classes=COCO.class_names,
    )
    cv2.imwrite("results.jpg", res_img)


if __name__ == "__main__":
    main()