infer.py 7.6 KB
Newer Older
W
wangguanzhong 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# 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.

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
Q
qingqing01 已提交
30

W
wangguanzhong 已提交
31 32 33 34 35 36
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
W
wangguanzhong 已提交
37
from ppdet.utils.checkpoint import load_weight
W
wangguanzhong 已提交
38
from ppdet.utils.eval_utils import get_infer_results
Q
qingqing01 已提交
39 40 41

from ppdet.utils.logger import setup_logger
logger = setup_logger('train')
W
wangguanzhong 已提交
42 43 44 45 46 47 48 49 50 51 52 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 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121


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(
        "--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.')
    args = parser.parse_args()
    return args


def get_save_image_name(output_dir, image_path):
    """
    Get save image name from source image path.
    """
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    image_name = os.path.split(image_path)[-1]
    name, ext = os.path.splitext(image_name)
    return os.path.join(output_dir, "{}".format(name)) + ext


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


G
Guanghua Yu 已提交
122
def run(FLAGS, cfg, place):
W
wangguanzhong 已提交
123 124 125 126 127

    # Model
    main_arch = cfg.architecture
    model = create(cfg.architecture)

G
Guanghua Yu 已提交
128 129
    # data
    dataset = cfg.TestDataset
W
wangguanzhong 已提交
130 131
    test_images = get_test_images(FLAGS.infer_dir, FLAGS.infer_img)
    dataset.set_images(test_images)
Q
qingqing01 已提交
132
    test_loader = create('TestReader')(dataset, cfg['worker_num'])
K
Kaipeng Deng 已提交
133 134 135
    extra_key = ['im_shape', 'scale_factor', 'im_id']
    if cfg.metric == 'VOC':
        extra_key += ['gt_bbox', 'gt_class', 'difficult']
W
wangguanzhong 已提交
136 137 138 139 140 141

    # TODO: support other metrics
    imid2path = dataset.get_imid2path()

    from ppdet.utils.coco_eval import get_category_info
    anno_file = dataset.get_anno()
G
Guanghua Yu 已提交
142
    with_background = cfg.with_background
W
wangguanzhong 已提交
143 144 145 146 147
    use_default_label = dataset.use_default_label
    clsid2catid, catid2name = get_category_info(anno_file, with_background,
                                                use_default_label)

    # Init Model
W
wangguanzhong 已提交
148
    load_weight(model, cfg.weights)
W
wangguanzhong 已提交
149 150

    # Run Infer 
G
Guanghua Yu 已提交
151
    for iter_id, data in enumerate(test_loader):
W
wangguanzhong 已提交
152 153
        # forward
        model.eval()
K
Kaipeng Deng 已提交
154 155 156
        outs = model(data, mode='infer')
        for key in extra_key:
            outs[key] = data[key]
W
wangguanzhong 已提交
157 158
        for key, value in outs.items():
            outs[key] = value.numpy()
159

W
wangguanzhong 已提交
160 161 162
        if 'mask' in outs and 'bbox' in outs:
            mask_resolution = model.mask_post_process.mask_resolution
            from ppdet.py_op.post_process import mask_post_process
K
Kaipeng Deng 已提交
163 164
            outs['mask'] = mask_post_process(
                outs, outs['im_shape'], outs['scale_factor'], mask_resolution)
W
wangguanzhong 已提交
165 166 167 168 169 170 171

        eval_type = []
        if 'bbox' in outs:
            eval_type.append('bbox')
        if 'mask' in outs:
            eval_type.append('mask')

K
Kaipeng Deng 已提交
172
        batch_res = get_infer_results([outs], eval_type, clsid2catid)
W
wangguanzhong 已提交
173 174 175 176 177 178
        logger.info('Infer iter {}'.format(iter_id))
        bbox_res = None
        mask_res = None

        bbox_num = outs['bbox_num']
        start = 0
K
Kaipeng Deng 已提交
179
        for i, im_id in enumerate(outs['im_id']):
W
wangguanzhong 已提交
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
            image_path = imid2path[int(im_id)]
            image = Image.open(image_path).convert('RGB')
            end = start + bbox_num[i]

            # use VisualDL to log original image
            if FLAGS.use_vdl:
                original_image_np = np.array(image)
                vdl_writer.add_image(
                    "original/frame_{}".format(vdl_image_frame),
                    original_image_np, vdl_image_step)

            if 'bbox' in batch_res:
                bbox_res = batch_res['bbox'][start:end]
            if 'mask' in batch_res:
                mask_res = batch_res['mask'][start:end]

            image = visualize_results(image, bbox_res, mask_res,
K
Kaipeng Deng 已提交
197
                                      int(outs['im_id']), catid2name,
W
wangguanzhong 已提交
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
                                      FLAGS.draw_threshold)

            # use VisualDL to log image with bbox
            if FLAGS.use_vdl:
                infer_image_np = np.array(image)
                vdl_writer.add_image("bbox/frame_{}".format(vdl_image_frame),
                                     infer_image_np, vdl_image_step)
                vdl_image_step += 1
                if vdl_image_step % 10 == 0:
                    vdl_image_step = 0
                    vdl_image_frame += 1

            # save image with detection
            save_name = get_save_image_name(FLAGS.output_dir, image_path)
            logger.info("Detection bbox results save in {}".format(save_name))
            image.save(save_name, quality=95)
            start = end


def main():
    FLAGS = parse_args()

    cfg = load_config(FLAGS.config)
    merge_config(FLAGS.opt)
    check_config(cfg)
    check_gpu(cfg.use_gpu)
    check_version()

G
Guanghua Yu 已提交
226 227 228
    place = 'gpu:{}'.format(ParallelEnv().dev_id) if cfg.use_gpu else 'cpu'
    place = paddle.set_device(place)
    run(FLAGS, cfg, place)
W
wangguanzhong 已提交
229 230 231 232


if __name__ == '__main__':
    main()