infer.py 5.1 KB
Newer Older
C
chenguowei01 已提交
1
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse
import os

from paddle.fluid.dygraph.base import to_variable
import numpy as np
import paddle.fluid as fluid
C
chenguowei01 已提交
21
from paddle.fluid.dygraph.parallel import ParallelEnv
22 23 24
import cv2
import tqdm

C
chenguowei01 已提交
25
from datasets import OpticDiscSeg, Cityscapes
26
import transforms as T
C
chenguowei01 已提交
27
from models import MODELS
28 29 30 31 32 33 34 35 36
import utils
import utils.logging as logging
from utils import get_environ_info


def parse_args():
    parser = argparse.ArgumentParser(description='Model training')

    # params of model
C
chenguowei01 已提交
37 38 39
    parser.add_argument(
        '--model_name',
        dest='model_name',
R
update  
root 已提交
40 41
        help='Model type for testing, which is one of {}'.format(
            str(list(MODELS.keys()))),
C
chenguowei01 已提交
42 43
        type=str,
        default='UNet')
44 45

    # params of dataset
C
chenguowei01 已提交
46
    parser.add_argument(
C
chenguowei01 已提交
47 48
        '--dataset',
        dest='dataset',
C
chenguowei01 已提交
49 50
        help=
        "The dataset you want to train, which is one of ('OpticDiscSeg', 'Cityscapes')",
C
chenguowei01 已提交
51
        type=str,
C
chenguowei01 已提交
52
        default='OpticDiscSeg')
53 54

    # params of prediction
C
chenguowei01 已提交
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
    parser.add_argument(
        "--input_size",
        dest="input_size",
        help="The image size for net inputs.",
        nargs=2,
        default=[512, 512],
        type=int)
    parser.add_argument(
        '--batch_size',
        dest='batch_size',
        help='Mini batch size',
        type=int,
        default=2)
    parser.add_argument(
        '--model_dir',
        dest='model_dir',
        help='The path of model for evaluation',
        type=str,
        default=None)
    parser.add_argument(
        '--save_dir',
        dest='save_dir',
        help='The directory for saving the inference results',
        type=str,
        default='./output/result')
80 81 82 83 84

    return parser.parse_args()


def mkdir(path):
C
chenguowei01 已提交
85 86
    sub_dir = os.path.dirname(path)
    if not os.path.exists(sub_dir):
87 88 89
        os.makedirs(sub_dir)


C
chenguowei01 已提交
90
def infer(model, test_dataset=None, model_dir=None, save_dir='output'):
C
chenguowei01 已提交
91
    ckpt_path = os.path.join(model_dir, 'model')
92 93 94 95
    para_state_dict, opti_state_dict = fluid.load_dygraph(ckpt_path)
    model.set_dict(para_state_dict)
    model.eval()

C
chenguowei01 已提交
96 97
    added_saved_dir = os.path.join(save_dir, 'added')
    pred_saved_dir = os.path.join(save_dir, 'prediction')
98 99

    logging.info("Start to predict...")
C
chenguowei01 已提交
100
    for im, im_info, im_path in tqdm.tqdm(test_dataset):
101 102 103 104
        im = to_variable(im)
        pred, _ = model(im, mode='test')
        pred = pred.numpy()
        pred = np.squeeze(pred).astype('uint8')
C
chenguowei01 已提交
105 106 107
        for info in im_info[::-1]:
            if info[0] == 'resize':
                h, w = info[1][0], info[1][1]
108
                pred = cv2.resize(pred, (w, h), cv2.INTER_NEAREST)
C
chenguowei01 已提交
109 110
            elif info[0] == 'padding':
                h, w = info[1][0], info[1][1]
111
                pred = pred[0:h, 0:w]
C
chenguowei01 已提交
112 113 114
            else:
                raise Exception("Unexpected info '{}' in im_info".format(
                    info[0]))
115

C
chenguowei01 已提交
116 117 118
        im_file = im_path.replace(test_dataset.data_dir, '')
        if im_file[0] == '/':
            im_file = im_file[1:]
119
        # save added image
C
chenguowei01 已提交
120 121
        added_image = utils.visualize(im_path, pred, weight=0.6)
        added_image_path = os.path.join(added_saved_dir, im_file)
122 123 124 125
        mkdir(added_image_path)
        cv2.imwrite(added_image_path, added_image)

        # save prediction
C
chenguowei01 已提交
126 127
        pred_im = utils.visualize(im_path, pred, weight=0.0)
        pred_saved_path = os.path.join(pred_saved_dir, im_file)
128 129 130 131 132
        mkdir(pred_saved_path)
        cv2.imwrite(pred_saved_path, pred_im)


def main(args):
C
chenguowei01 已提交
133 134 135 136
    env_info = get_environ_info()
    places = fluid.CUDAPlace(ParallelEnv().dev_id) \
        if env_info['place'] == 'cuda' and fluid.is_compiled_with_cuda() \
        else fluid.CPUPlace()
C
chenguowei01 已提交
137 138 139

    if args.dataset.lower() == 'opticdiscseg':
        dataset = OpticDiscSeg
C
chenguowei01 已提交
140 141
    elif args.dataset.lower() == 'cityscapes':
        dataset = Cityscapes
C
chenguowei01 已提交
142 143
    else:
        raise Exception(
C
chenguowei01 已提交
144 145
            "The --dataset set wrong. It should be one of ('OpticDiscSeg', 'Cityscapes')"
        )
C
chenguowei01 已提交
146

C
chenguowei01 已提交
147 148
    with fluid.dygraph.guard(places):
        test_transforms = T.Compose([T.Resize(args.input_size), T.Normalize()])
C
chenguowei01 已提交
149
        test_dataset = dataset(transforms=test_transforms, mode='test')
150

C
chenguowei01 已提交
151 152 153 154 155
        if args.model_name not in MODELS:
            raise Exception(
                '--model_name is invalid. it should be one of {}'.format(
                    str(list(MODELS.keys()))))
        model = MODELS[args.model_name](num_classes=test_dataset.num_classes)
156

C
chenguowei01 已提交
157 158 159 160 161
        infer(
            model,
            model_dir=args.model_dir,
            test_dataset=test_dataset,
            save_dir=args.save_dir)
162 163 164 165


if __name__ == '__main__':
    args = parse_args()
C
chenguowei01 已提交
166
    main(args)