reader.py 12.9 KB
Newer Older
G
gaoyuan 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# Copyright (c) 2016 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.

import image_util
from paddle.utils.image_util import *
from PIL import Image
X
Xingyuan Bu 已提交
18
from PIL import ImageDraw
G
gaoyuan 已提交
19 20 21
import numpy as np
import xml.etree.ElementTree
import os
X
Xingyuan Bu 已提交
22 23
import time
import copy
M
minqiyang 已提交
24
import six
B
Bai Yifan 已提交
25
from data_util import GeneratorEnqueuer
X
Xingyuan Bu 已提交
26

G
gaoyuan 已提交
27 28

class Settings(object):
D
Dang Qingqing 已提交
29 30 31 32 33 34 35 36 37
    def __init__(self,
                 dataset=None,
                 data_dir=None,
                 label_file=None,
                 resize_h=300,
                 resize_w=300,
                 mean_value=[127.5, 127.5, 127.5],
                 apply_distort=True,
                 apply_expand=True,
B
Bai Yifan 已提交
38
                 ap_version='11point'):
X
Xingyuan Bu 已提交
39
        self._dataset = dataset
40
        self._ap_version = ap_version
G
gaoyuan 已提交
41
        self._data_dir = data_dir
42
        if 'pascalvoc' in dataset:
X
Xingyuan Bu 已提交
43 44 45 46
            self._label_list = []
            label_fpath = os.path.join(data_dir, label_file)
            for line in open(label_fpath):
                self._label_list.append(line.strip())
G
gaoyuan 已提交
47

G
gaoyuan 已提交
48 49
        self._apply_distort = apply_distort
        self._apply_expand = apply_expand
G
gaoyuan 已提交
50 51 52 53
        self._resize_height = resize_h
        self._resize_width = resize_w
        self._img_mean = np.array(mean_value)[:, np.newaxis, np.newaxis].astype(
            'float32')
G
gaoyuan 已提交
54 55 56 57 58 59 60 61 62 63 64
        self._expand_prob = 0.5
        self._expand_max_ratio = 4
        self._hue_prob = 0.5
        self._hue_delta = 18
        self._contrast_prob = 0.5
        self._contrast_delta = 0.5
        self._saturation_prob = 0.5
        self._saturation_delta = 0.5
        self._brightness_prob = 0.5
        self._brightness_delta = 0.125

X
Xingyuan Bu 已提交
65 66 67 68
    @property
    def dataset(self):
        return self._dataset

69 70 71 72
    @property
    def ap_version(self):
        return self._ap_version

G
gaoyuan 已提交
73 74 75 76 77 78 79
    @property
    def apply_distort(self):
        return self._apply_expand

    @property
    def apply_distort(self):
        return self._apply_distort
G
gaoyuan 已提交
80 81 82 83 84

    @property
    def data_dir(self):
        return self._data_dir

X
Xingyuan Bu 已提交
85 86 87 88
    @data_dir.setter
    def data_dir(self, data_dir):
        self._data_dir = data_dir

G
gaoyuan 已提交
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
    @property
    def label_list(self):
        return self._label_list

    @property
    def resize_h(self):
        return self._resize_height

    @property
    def resize_w(self):
        return self._resize_width

    @property
    def img_mean(self):
        return self._img_mean


D
Dang Qingqing 已提交
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
def preprocess(img, bbox_labels, mode, settings):
    img_width, img_height = img.size
    sampled_labels = bbox_labels
    if mode == 'train':
        if settings._apply_distort:
            img = image_util.distort_image(img, settings)
        if settings._apply_expand:
            img, bbox_labels, img_width, img_height = image_util.expand_image(
                img, bbox_labels, img_width, img_height, settings)
        # sampling
        batch_sampler = []
        # hard-code here
        batch_sampler.append(
            image_util.sampler(1, 1, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0))
        batch_sampler.append(
            image_util.sampler(1, 50, 0.3, 1.0, 0.5, 2.0, 0.1, 0.0))
        batch_sampler.append(
            image_util.sampler(1, 50, 0.3, 1.0, 0.5, 2.0, 0.3, 0.0))
        batch_sampler.append(
            image_util.sampler(1, 50, 0.3, 1.0, 0.5, 2.0, 0.5, 0.0))
        batch_sampler.append(
            image_util.sampler(1, 50, 0.3, 1.0, 0.5, 2.0, 0.7, 0.0))
        batch_sampler.append(
            image_util.sampler(1, 50, 0.3, 1.0, 0.5, 2.0, 0.9, 0.0))
        batch_sampler.append(
            image_util.sampler(1, 50, 0.3, 1.0, 0.5, 2.0, 0.0, 1.0))
        sampled_bbox = image_util.generate_batch_samples(batch_sampler,
                                                         bbox_labels)

        img = np.array(img)
        if len(sampled_bbox) > 0:
137
            idx = int(np.random.uniform(0, len(sampled_bbox)))
D
Dang Qingqing 已提交
138 139 140 141 142 143 144 145
            img, sampled_labels = image_util.crop_image(
                img, bbox_labels, sampled_bbox[idx], img_width, img_height)

        img = Image.fromarray(img)
    img = img.resize((settings.resize_w, settings.resize_h), Image.ANTIALIAS)
    img = np.array(img)

    if mode == 'train':
146
        mirror = int(np.random.uniform(0, 2))
D
Dang Qingqing 已提交
147 148
        if mirror == 1:
            img = img[:, ::-1, :]
M
minqiyang 已提交
149
            for i in six.moves.xrange(len(sampled_labels)):
D
Dang Qingqing 已提交
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
                tmp = sampled_labels[i][1]
                sampled_labels[i][1] = 1 - sampled_labels[i][3]
                sampled_labels[i][3] = 1 - tmp
    # HWC to CHW
    if len(img.shape) == 3:
        img = np.swapaxes(img, 1, 2)
        img = np.swapaxes(img, 1, 0)
    # RBG to BGR
    img = img[[2, 1, 0], :, :]
    img = img.astype('float32')
    img -= settings.img_mean
    img = img * 0.007843
    return img, sampled_labels


B
Bai Yifan 已提交
165
def coco(settings, file_list, mode, batch_size, shuffle):
D
Dang Qingqing 已提交
166 167 168 169 170 171 172 173 174
    # cocoapi
    from pycocotools.coco import COCO
    from pycocotools.cocoeval import COCOeval

    coco = COCO(file_list)
    image_ids = coco.getImgIds()
    images = coco.loadImgs(image_ids)
    print("{} on {} with {} images".format(mode, settings.dataset, len(images)))

B
Bai Yifan 已提交
175 176
    def reader():
        if mode == 'train' and shuffle:
177
            np.random.shuffle(images)
B
Bai Yifan 已提交
178
        batch_out = []
179 180 181 182 183
        if '2014' in file_list:
            sub_dir = "train2014" if model == "train" else "val2014"
        elif '2017' in file_list:
            sub_dir = "train2017" if mode == "train" else "val2017"
        data_dir = os.path.join(settings.data_dir, sub_dir)
X
Xingyuan Bu 已提交
184
        for image in images:
D
Dang Qingqing 已提交
185
            image_name = image['file_name']
186 187 188 189
            image_path = os.path.join(data_dir, image_name)
            if not os.path.exists(image_path):
                raise ValueError("%s is not exist, you should specify "
                                 "data path correctly." % image_path)
D
Dang Qingqing 已提交
190 191 192 193
            im = Image.open(image_path)
            if im.mode == 'L':
                im = im.convert('RGB')
            im_width, im_height = im.size
194
            im_id = image['id']
D
Dang Qingqing 已提交
195

196
            # layout: category_id | xmin | ymin | xmax | ymax | iscrowd
D
Dang Qingqing 已提交
197 198 199 200 201 202
            bbox_labels = []
            annIds = coco.getAnnIds(imgIds=image['id'])
            anns = coco.loadAnns(annIds)
            for ann in anns:
                bbox_sample = []
                # start from 1, leave 0 to background
203
                bbox_sample.append(float(ann['category_id']))
D
Dang Qingqing 已提交
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
                bbox = ann['bbox']
                xmin, ymin, w, h = bbox
                xmax = xmin + w
                ymax = ymin + h
                bbox_sample.append(float(xmin) / im_width)
                bbox_sample.append(float(ymin) / im_height)
                bbox_sample.append(float(xmax) / im_width)
                bbox_sample.append(float(ymax) / im_height)
                bbox_sample.append(float(ann['iscrowd']))
                bbox_labels.append(bbox_sample)
            im, sample_labels = preprocess(im, bbox_labels, mode, settings)
            sample_labels = np.array(sample_labels)
            if len(sample_labels) == 0: continue
            im = im.astype('float32')
            boxes = sample_labels[:, 1:5]
            lbls = sample_labels[:, 0].astype('int32')
220 221
            iscrowd = sample_labels[:, -1].astype('int32')
            if 'cocoMAP' in settings.ap_version:
B
Bai Yifan 已提交
222 223
                batch_out.append((im, boxes, lbls, iscrowd,
                                  [im_id, im_width, im_height]))
224
            else:
B
Bai Yifan 已提交
225 226 227 228 229 230 231 232 233
                batch_out.append((im, boxes, lbls, iscrowd))

            if len(batch_out) == batch_size:
                yield batch_out
                batch_out = []

        if mode == 'test' and len(batch_out) > 1:
            yield batch_out
            batch_out = []
B
Bai Yifan 已提交
234 235

    return reader
D
Dang Qingqing 已提交
236

X
Xingyuan Bu 已提交
237

B
Bai Yifan 已提交
238
def pascalvoc(settings, file_list, mode, batch_size, shuffle):
D
Dang Qingqing 已提交
239 240 241 242
    flist = open(file_list)
    images = [line.strip() for line in flist]
    print("{} on {} with {} images".format(mode, settings.dataset, len(images)))

B
Bai Yifan 已提交
243 244
    def reader():
        if mode == 'train' and shuffle:
245
            np.random.shuffle(images)
B
Bai Yifan 已提交
246 247
        batch_out = []
        cnt = 0
D
Dang Qingqing 已提交
248 249 250 251
        for image in images:
            image_path, label_path = image.split()
            image_path = os.path.join(settings.data_dir, image_path)
            label_path = os.path.join(settings.data_dir, label_path)
252 253 254
            if not os.path.exists(image_path):
                raise ValueError("%s is not exist, you should specify "
                                 "data path correctly." % image_path)
D
Dang Qingqing 已提交
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
            im = Image.open(image_path)
            if im.mode == 'L':
                im = im.convert('RGB')
            im_width, im_height = im.size

            # layout: label | xmin | ymin | xmax | ymax | difficult
            bbox_labels = []
            root = xml.etree.ElementTree.parse(label_path).getroot()
            for object in root.findall('object'):
                bbox_sample = []
                # start from 1
                bbox_sample.append(
                    float(settings.label_list.index(object.find('name').text)))
                bbox = object.find('bndbox')
                difficult = float(object.find('difficult').text)
                bbox_sample.append(float(bbox.find('xmin').text) / im_width)
                bbox_sample.append(float(bbox.find('ymin').text) / im_height)
                bbox_sample.append(float(bbox.find('xmax').text) / im_width)
                bbox_sample.append(float(bbox.find('ymax').text) / im_height)
                bbox_sample.append(difficult)
                bbox_labels.append(bbox_sample)
            im, sample_labels = preprocess(im, bbox_labels, mode, settings)
X
Xingyuan Bu 已提交
277
            sample_labels = np.array(sample_labels)
D
Dang Qingqing 已提交
278 279 280 281 282
            if len(sample_labels) == 0: continue
            im = im.astype('float32')
            boxes = sample_labels[:, 1:5]
            lbls = sample_labels[:, 0].astype('int32')
            difficults = sample_labels[:, -1].astype('int32')
B
Bai Yifan 已提交
283 284 285 286 287 288 289 290 291 292 293

            batch_out.append((im, boxes, lbls, difficults))
            if len(batch_out) == batch_size:
                yield batch_out
                cnt += len(batch_out)
                batch_out = []

        if mode == 'test' and len(batch_out) > 1:
            yield batch_out
            cnt += len(batch_out)
            batch_out = []
G
gaoyuan 已提交
294 295 296 297

    return reader


B
Bai Yifan 已提交
298 299 300 301 302 303
def train(settings,
          file_list,
          batch_size,
          shuffle=True,
          use_multiprocessing=True,
          num_workers=8,
B
Bai Yifan 已提交
304 305
          max_queue=24,
          enable_ce=False):
306
    file_list = os.path.join(settings.data_dir, file_list)
307
    if 'coco' in settings.dataset:
B
Bai Yifan 已提交
308
        generator = coco(settings, file_list, "train", batch_size, shuffle)
D
Dang Qingqing 已提交
309
    else:
B
Bai Yifan 已提交
310 311
        generator = pascalvoc(settings, file_list, "train", batch_size, shuffle)

B
Bai Yifan 已提交
312 313 314 315 316
    def infinite_reader():
        while True:
            for data in generator():
                yield data

B
Bai Yifan 已提交
317 318 319
    def reader():
        try:
            enqueuer = GeneratorEnqueuer(
B
Bai Yifan 已提交
320
                infinite_reader(), use_multiprocessing=use_multiprocessing)
B
Bai Yifan 已提交
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
            enqueuer.start(max_queue_size=max_queue, workers=num_workers)
            generator_output = None
            while True:
                while enqueuer.is_running():
                    if not enqueuer.queue.empty():
                        generator_output = enqueuer.queue.get()
                        break
                    else:
                        time.sleep(0.02)
                yield generator_output
                generator_output = None
        finally:
            if enqueuer is not None:
                enqueuer.stop()

B
Bai Yifan 已提交
336 337 338 339
    if enable_ce:
        return infinite_reader
    else:
        return reader
G
gaoyuan 已提交
340 341


B
Bai Yifan 已提交
342
def test(settings, file_list, batch_size):
343
    file_list = os.path.join(settings.data_dir, file_list)
344
    if 'coco' in settings.dataset:
B
Bai Yifan 已提交
345
        return coco(settings, file_list, 'test', batch_size, False)
D
Dang Qingqing 已提交
346
    else:
B
Bai Yifan 已提交
347
        return pascalvoc(settings, file_list, 'test', batch_size, False)
D
Dang Qingqing 已提交
348 349 350


def infer(settings, image_path):
D
Dang Qingqing 已提交
351
    def reader():
352 353 354
        if not os.path.exists(image_path):
            raise ValueError("%s is not exist, you should specify "
                             "data path correctly." % image_path)
355 356 357 358
        img = Image.open(image_path)
        if img.mode == 'L':
            img = im.convert('RGB')
        im_width, im_height = img.size
D
Dang Qingqing 已提交
359 360 361 362 363 364 365 366 367 368 369 370
        img = img.resize((settings.resize_w, settings.resize_h),
                         Image.ANTIALIAS)
        img = np.array(img)
        # HWC to CHW
        if len(img.shape) == 3:
            img = np.swapaxes(img, 1, 2)
            img = np.swapaxes(img, 1, 0)
        # RBG to BGR
        img = img[[2, 1, 0], :, :]
        img = img.astype('float32')
        img -= settings.img_mean
        img = img * 0.007843
371
        return img
D
Dang Qingqing 已提交
372 373

    return reader