infer.py 4.7 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
26 27 28 29 30 31 32 33 34 35 36
import transforms as T
import models
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 40 41 42
    parser.add_argument(
        '--model_name',
        dest='model_name',
        help="Model type for traing, which is one of ('UNet')",
        type=str,
        default='UNet')
43 44

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

    # params of prediction
C
chenguowei01 已提交
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
    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')
78 79 80 81 82

    return parser.parse_args()


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


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

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

    logging.info("Start to predict...")
C
chenguowei01 已提交
98 99
    for im, im_info, im_path in tqdm.tqdm(test_dataset):
        im = im[np.newaxis, ...]
100 101 102 103 104 105 106 107 108 109 110 111 112
        im = to_variable(im)
        pred, _ = model(im, mode='test')
        pred = pred.numpy()
        pred = np.squeeze(pred).astype('uint8')
        keys = list(im_info.keys())
        for k in keys[::-1]:
            if k == 'shape_before_resize':
                h, w = im_info[k][0], im_info[k][1]
                pred = cv2.resize(pred, (w, h), cv2.INTER_NEAREST)
            elif k == 'shape_before_padding':
                h, w = im_info[k][0], im_info[k][1]
                pred = pred[0:h, 0:w]

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

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


def main(args):
C
chenguowei01 已提交
130 131 132 133
    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 已提交
134 135 136 137 138 139 140

    if args.dataset.lower() == 'opticdiscseg':
        dataset = OpticDiscSeg
    else:
        raise Exception(
            "The --dataset set wrong. It should be one of ('OpticDiscSeg',)")

C
chenguowei01 已提交
141 142
    with fluid.dygraph.guard(places):
        test_transforms = T.Compose([T.Resize(args.input_size), T.Normalize()])
C
chenguowei01 已提交
143
        test_dataset = dataset(transforms=test_transforms, mode='test')
144

C
chenguowei01 已提交
145
        if args.model_name == 'UNet':
C
chenguowei01 已提交
146
            model = models.UNet(num_classes=test_dataset.num_classes)
147

C
chenguowei01 已提交
148 149 150 151 152
        infer(
            model,
            model_dir=args.model_dir,
            test_dataset=test_dataset,
            save_dir=args.save_dir)
153 154 155 156


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