infer.py 4.8 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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
    parser.add_argument(
        '--data_dir',
        dest='data_dir',
        help='The root directory of dataset',
        type=str)
    parser.add_argument(
        '--test_list',
        dest='test_list',
        help='Val list file of dataset',
        type=str,
        default=None)
    parser.add_argument(
        '--num_classes',
        dest='num_classes',
        help='Number of classes',
        type=int,
        default=2)
62 63

    # params of prediction
C
chenguowei01 已提交
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
    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')
89 90 91 92 93

    return parser.parse_args()


def mkdir(path):
C
chenguowei01 已提交
94 95
    sub_dir = os.path.dirname(path)
    if not os.path.exists(sub_dir):
96 97 98
        os.makedirs(sub_dir)


C
chenguowei01 已提交
99
def infer(model, test_dataset=None, model_dir=None, save_dir='output'):
C
chenguowei01 已提交
100
    ckpt_path = os.path.join(model_dir, 'model')
101 102 103 104
    para_state_dict, opti_state_dict = fluid.load_dygraph(ckpt_path)
    model.set_dict(para_state_dict)
    model.eval()

C
chenguowei01 已提交
105 106
    added_saved_dir = os.path.join(save_dir, 'added')
    pred_saved_dir = os.path.join(save_dir, 'prediction')
107 108

    logging.info("Start to predict...")
C
chenguowei01 已提交
109 110
    for im, im_info, im_path in tqdm.tqdm(test_dataset):
        im = im[np.newaxis, ...]
111 112 113 114 115 116 117 118 119 120 121 122 123
        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 已提交
124 125 126
        im_file = im_path.replace(test_dataset.data_dir, '')
        if im_file[0] == '/':
            im_file = im_file[1:]
127
        # save added image
C
chenguowei01 已提交
128 129
        added_image = utils.visualize(im_path, pred, weight=0.6)
        added_image_path = os.path.join(added_saved_dir, im_file)
130 131 132 133
        mkdir(added_image_path)
        cv2.imwrite(added_image_path, added_image)

        # save prediction
C
chenguowei01 已提交
134 135
        pred_im = utils.visualize(im_path, pred, weight=0.0)
        pred_saved_path = os.path.join(pred_saved_dir, im_file)
136 137 138 139 140
        mkdir(pred_saved_path)
        cv2.imwrite(pred_saved_path, pred_im)


def main(args):
C
chenguowei01 已提交
141 142 143 144
    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 已提交
145 146
    with fluid.dygraph.guard(places):
        test_transforms = T.Compose([T.Resize(args.input_size), T.Normalize()])
C
chenguowei01 已提交
147
        test_dataset = OpticDiscSeg(transforms=test_transforms, mode='test')
148

C
chenguowei01 已提交
149 150
        if args.model_name == 'UNet':
            model = models.UNet(num_classes=args.num_classes)
151

C
chenguowei01 已提交
152 153 154 155 156
        infer(
            model,
            model_dir=args.model_dir,
            test_dataset=test_dataset,
            save_dir=args.save_dir)
157 158 159 160


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