reader.py 6.6 KB
Newer Older
J
jerrywgz 已提交
1
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved
J
jerrywgz 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#
# 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 random
import numpy as np
import xml.etree.ElementTree
import os
import time
import copy
import six
Q
qingqing01 已提交
22
import cv2
23
from collections import deque
J
jerrywgz 已提交
24 25 26

from roidbs import JsonDataset
import data_utils
J
jerrywgz 已提交
27
from config import cfg
J
jerrywgz 已提交
28
import segm_utils
29
num_trainers = int(os.environ.get('PADDLE_TRAINERS_NUM', 1))
J
jerrywgz 已提交
30 31 32 33 34 35 36 37


def roidb_reader(roidb, mode):
    im, im_scales = data_utils.get_image_blob(roidb, mode)
    im_id = roidb['id']
    im_height = np.round(roidb['height'] * im_scales)
    im_width = np.round(roidb['width'] * im_scales)
    im_info = np.array([im_height, im_width, im_scales], dtype=np.float32)
J
jerrywgz 已提交
38
    if mode == 'val':
J
jerrywgz 已提交
39 40 41 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
        return im, im_info, im_id

    gt_boxes = roidb['gt_boxes'].astype('float32')
    gt_classes = roidb['gt_classes'].astype('int32')
    is_crowd = roidb['is_crowd'].astype('int32')
    segms = roidb['segms']

    outs = (im, gt_boxes, gt_classes, is_crowd, im_info, im_id)

    if cfg.MASK_ON:
        gt_masks = []
        valid = True
        segms = roidb['segms']
        assert len(segms) == is_crowd.shape[0]
        for i in range(len(roidb['segms'])):
            segm, iscrowd = segms[i], is_crowd[i]
            gt_segm = []
            if iscrowd:
                gt_segm.append([[0, 0]])
            else:
                for poly in segm:
                    if len(poly) == 0:
                        valid = False
                        break
                    gt_segm.append(np.array(poly).reshape(-1, 2))
            if (not valid) or len(gt_segm) == 0:
                break
            gt_masks.append(gt_segm)
        outs = outs + (gt_masks, )
    return outs
J
jerrywgz 已提交
69 70


J
jerrywgz 已提交
71
def coco(mode,
72 73 74
         batch_size=None,
         total_batch_size=None,
         padding_total=False,
75 76
         shuffle=False,
         shuffle_seed=None):
77
    total_batch_size = total_batch_size if total_batch_size else batch_size
Q
qingqing01 已提交
78
    assert total_batch_size % batch_size == 0
79
    json_dataset = JsonDataset(mode)
J
jerrywgz 已提交
80 81
    roidbs = json_dataset.get_roidb()

J
jerrywgz 已提交
82
    print("{} on {} with {} roidbs".format(mode, cfg.dataset, len(roidbs)))
J
jerrywgz 已提交
83

84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
    def padding_minibatch(batch_data):
        if len(batch_data) == 1:
            return batch_data

        max_shape = np.array([data[0].shape for data in batch_data]).max(axis=0)

        padding_batch = []
        for data in batch_data:
            im_c, im_h, im_w = data[0].shape[:]
            padding_im = np.zeros(
                (im_c, max_shape[1], max_shape[2]), dtype=np.float32)
            padding_im[:, :im_h, :im_w] = data[0]
            padding_batch.append((padding_im, ) + data[1:])
        return padding_batch

99 100
    def reader():
        if mode == "train":
J
jerrywgz 已提交
101
            if shuffle:
102 103
                if shuffle_seed is not None:
                    np.random.seed(shuffle_seed)
J
jerrywgz 已提交
104 105 106
                roidb_perm = deque(np.random.permutation(roidbs))
            else:
                roidb_perm = deque(roidbs)
107
            roidb_cur = 0
J
jerrywgz 已提交
108
            count = 0
109
            batch_out = []
J
jerrywgz 已提交
110
            device_num = total_batch_size / batch_size
111 112 113 114 115
            while True:
                roidb = roidb_perm[0]
                roidb_cur += 1
                roidb_perm.rotate(-1)
                if roidb_cur >= len(roidbs):
J
jerrywgz 已提交
116 117 118 119
                    if shuffle:
                        roidb_perm = deque(np.random.permutation(roidbs))
                    else:
                        roidb_perm = deque(roidbs)
J
jerrywgz 已提交
120
                    roidb_cur = 0
J
jerrywgz 已提交
121 122 123
                # im, gt_boxes, gt_classes, is_crowd, im_info, im_id, gt_masks
                datas = roidb_reader(roidb, mode)
                if datas[1].shape[0] == 0:
124
                    continue
J
jerrywgz 已提交
125 126 127 128
                if cfg.MASK_ON:
                    if len(datas[-1]) != datas[1].shape[0]:
                        continue
                batch_out.append(datas)
129 130 131
                if not padding_total:
                    if len(batch_out) == batch_size:
                        yield padding_minibatch(batch_out)
J
jerrywgz 已提交
132
                        count += 1
133 134 135 136
                        batch_out = []
                else:
                    if len(batch_out) == total_batch_size:
                        batch_out = padding_minibatch(batch_out)
J
jerrywgz 已提交
137
                        for i in range(device_num):
138 139 140 141 142
                            sub_batch_out = []
                            for j in range(batch_size):
                                sub_batch_out.append(batch_out[i * batch_size +
                                                               j])
                            yield sub_batch_out
J
jerrywgz 已提交
143
                            count += 1
144 145
                            sub_batch_out = []
                        batch_out = []
J
jerrywgz 已提交
146
                iter_id = count // device_num
147
                if iter_id >= cfg.max_iter * num_trainers:
J
jerrywgz 已提交
148
                    return
149
        elif mode == "val":
150 151
            batch_out = []
            for roidb in roidbs:
J
jerrywgz 已提交
152 153
                im, im_info, im_id = roidb_reader(roidb, mode)
                batch_out.append((im, im_info, im_id))
154 155 156
                if len(batch_out) == batch_size:
                    yield batch_out
                    batch_out = []
J
jerrywgz 已提交
157 158 159
            if len(batch_out) != 0:
                yield batch_out

J
jerrywgz 已提交
160 161 162
    return reader


163 164 165 166 167
def train(batch_size,
          total_batch_size=None,
          padding_total=False,
          shuffle=True,
          shuffle_seed=None):
168
    return coco(
169 170 171 172 173 174
        'train',
        batch_size,
        total_batch_size,
        padding_total,
        shuffle=shuffle,
        shuffle_seed=shuffle_seed)
J
jerrywgz 已提交
175 176


J
jerrywgz 已提交
177
def test(batch_size, total_batch_size=None, padding_total=False):
178
    return coco('val', batch_size, total_batch_size, shuffle=False)
J
jerrywgz 已提交
179 180


Q
qingqing01 已提交
181 182 183 184 185 186 187 188 189 190 191 192 193 194
def infer(file_path):
    def reader():
        if not os.path.exists(file_path):
            raise ValueError("Image path [%s] does not exist." % (file_path))
        im = cv2.imread(file_path)
        im = im.astype(np.float32, copy=False)
        im -= cfg.pixel_means
        im_height, im_width, channel = im.shape
        channel_swap = (2, 0, 1)  #(channel, height, width)
        im = im.transpose(channel_swap)
        im_info = np.array([im_height, im_width, 1.0], dtype=np.float32)
        yield [(im, im_info)]

    return reader