data_reader.py 26.6 KB
Newer Older
L
lvmengsi 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.
#
#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 print_function
from six.moves import range
from PIL import Image, ImageOps

import gzip
import numpy as np
import argparse
import struct
import os
import paddle
Z
zhumanyu 已提交
25
import random
Z
zhumanyu 已提交
26
import sys
L
lvmengsi 已提交
27 28 29


def RandomCrop(img, crop_w, crop_h):
L
lvmengsi 已提交
30
    w, h = img.size[0], img.size[1]
L
lvmengsi 已提交
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
    i = np.random.randint(0, w - crop_w)
    j = np.random.randint(0, h - crop_h)
    return img.crop((i, j, i + crop_w, j + crop_h))


def CentorCrop(img, crop_w, crop_h):
    w, h = img.size[0], img.size[1]
    i = int((w - crop_w) / 2.0)
    j = int((h - crop_h) / 2.0)
    return img.crop((i, j, i + crop_w, j + crop_h))


def RandomHorizonFlip(img):
    i = np.random.rand()
    if i > 0.5:
Z
zhumanyu 已提交
46
        img = ImageOps.mirror(img)
L
lvmengsi 已提交
47 48 49
    return img


Z
zhumanyu 已提交
50 51 52 53 54 55 56 57 58 59 60 61
def get_preprocess_param(load_size, crop_size):
    x = np.random.randint(0, np.maximum(0, load_size - crop_size))
    y = np.random.randint(0, np.maximum(0, load_size - crop_size))
    flip = np.random.rand() > 0.5
    return {
        "crop_pos": (x, y),
        "flip": flip,
        "load_size": load_size,
        "crop_size": crop_size
    }


Z
zhumanyu 已提交
62 63 64 65 66 67 68 69
def get_preprocess_param(load_width, load_height, crop_width, crop_height):
    if crop_width == load_width:
        x = 0
        y = 0
    else:
        x = np.random.randint(0, np.maximum(0, load_width - crop_width))
        y = np.random.randint(0, np.maximum(0, load_height - crop_height))
    flip = np.random.rand() > 0.5
L
lvmengsi 已提交
70 71
    return {"crop_pos": (x, y), "flip": flip}

Z
zhumanyu 已提交
72

L
lvmengsi 已提交
73 74 75
class reader_creator(object):
    ''' read and preprocess dataset'''

L
lvmengsi 已提交
76 77 78 79 80 81
    def __init__(self,
                 image_dir,
                 list_filename,
                 shuffle=False,
                 batch_size=1,
                 mode="TRAIN"):
L
lvmengsi 已提交
82 83 84
        self.image_dir = image_dir
        self.list_filename = list_filename
        self.batch_size = batch_size
L
lvmengsi 已提交
85
        self.mode = mode
L
lvmengsi 已提交
86

L
lvmengsi 已提交
87 88 89
        self.name2id = {}
        self.id2name = {}

L
lvmengsi 已提交
90 91
        self.lines = open(self.list_filename).readlines()

L
lvmengsi 已提交
92 93 94 95 96
        if self.mode == "TRAIN":
            self.shuffle = shuffle
        else:
            self.shuffle = False

L
lvmengsi 已提交
97
    def len(self):
L
lvmengsi 已提交
98
        return len(self.lines) // self.batch_size
L
lvmengsi 已提交
99

L
lvmengsi 已提交
100
    def make_reader(self, args, return_name=False):
L
lvmengsi 已提交
101 102 103 104
        print(self.image_dir, self.list_filename)

        def reader():
            batch_out = []
L
lvmengsi 已提交
105
            batch_out_name = []
L
lvmengsi 已提交
106

L
lvmengsi 已提交
107 108
            if self.shuffle:
                np.random.shuffle(self.lines)
L
lvmengsi 已提交
109

L
lvmengsi 已提交
110
            for i, file in enumerate(self.lines):
L
lvmengsi 已提交
111
                file = file.strip('\n\r\t ')
L
lvmengsi 已提交
112 113
                self.name2id[os.path.basename(file)] = i
                self.id2name[i] = os.path.basename(file)
L
lvmengsi 已提交
114 115
                img = Image.open(os.path.join(self.image_dir, file)).convert(
                    'RGB')
L
lvmengsi 已提交
116 117 118 119 120 121 122 123 124 125
                if self.mode == "TRAIN":
                    img = img.resize((args.image_size, args.image_size),
                                     Image.BICUBIC)
                    if args.crop_type == 'Centor':
                        img = CentorCrop(img, args.crop_size, args.crop_size)
                    elif args.crop_type == 'Random':
                        img = RandomCrop(img, args.crop_size, args.crop_size)
                else:
                    img = img.resize((args.crop_size, args.crop_size),
                                     Image.BICUBIC)
L
lvmengsi 已提交
126 127
                img = (np.array(img).astype('float32') / 255.0 - 0.5) / 0.5
                img = img.transpose([2, 0, 1])
L
lvmengsi 已提交
128

L
lvmengsi 已提交
129
                if return_name:
L
lvmengsi 已提交
130
                    batch_out.append(img)
L
lvmengsi 已提交
131
                    batch_out_name.append(i)
L
lvmengsi 已提交
132 133 134
                else:
                    batch_out.append(img)
                if len(batch_out) == self.batch_size:
L
lvmengsi 已提交
135 136 137 138
                    if return_name:
                        yield batch_out, batch_out_name
                        batch_out_name = []
                    else:
L
lvmengsi 已提交
139
                        yield [batch_out]
L
lvmengsi 已提交
140 141 142 143 144
                    batch_out = []

        return reader


Z
zhumanyu 已提交
145 146 147
class pair_reader_creator(reader_creator):
    ''' read and preprocess dataset'''

L
lvmengsi 已提交
148 149 150 151 152 153
    def __init__(self,
                 image_dir,
                 list_filename,
                 shuffle=False,
                 batch_size=1,
                 mode="TRAIN"):
Z
zhumanyu 已提交
154
        super(pair_reader_creator, self).__init__(
L
lvmengsi 已提交
155 156 157 158 159 160 161
            image_dir,
            list_filename,
            shuffle=shuffle,
            batch_size=batch_size,
            mode=mode)

    def make_reader(self, args, return_name=False):
Z
zhumanyu 已提交
162 163 164 165 166
        print(self.image_dir, self.list_filename)

        def reader():
            batch_out_1 = []
            batch_out_2 = []
L
lvmengsi 已提交
167 168 169
            batch_out_name = []
            if self.shuffle:
                np.random.shuffle(self.lines)
L
lvmengsi 已提交
170
            for i, line in enumerate(self.lines):
L
lvmengsi 已提交
171 172 173 174 175 176
                files = line.strip('\n\r\t ').split('\t')
                img1 = Image.open(os.path.join(self.image_dir, files[
                    0])).convert('RGB')
                img2 = Image.open(os.path.join(self.image_dir, files[
                    1])).convert('RGB')

L
lvmengsi 已提交
177 178 179
                self.name2id[os.path.basename(files[0])] = i
                self.id2name[i] = os.path.basename(files[0])

L
lvmengsi 已提交
180 181 182 183
                if self.mode == "TRAIN":
                    param = get_preprocess_param(args.image_size,
                                                 args.crop_size)
                    img1 = img1.resize((args.image_size, args.image_size),
Z
zhumanyu 已提交
184
                                       Image.BICUBIC)
L
lvmengsi 已提交
185
                    img2 = img2.resize((args.image_size, args.image_size),
Z
zhumanyu 已提交
186 187 188 189 190 191 192 193 194 195 196
                                       Image.BICUBIC)
                    if args.crop_type == 'Centor':
                        img1 = CentorCrop(img1, args.crop_size, args.crop_size)
                        img2 = CentorCrop(img2, args.crop_size, args.crop_size)
                    elif args.crop_type == 'Random':
                        x = param['crop_pos'][0]
                        y = param['crop_pos'][1]
                        img1 = img1.crop(
                            (x, y, x + args.crop_size, y + args.crop_size))
                        img2 = img2.crop(
                            (x, y, x + args.crop_size, y + args.crop_size))
L
lvmengsi 已提交
197 198 199 200 201
                else:
                    img1 = img1.resize((args.crop_size, args.crop_size),
                                       Image.BICUBIC)
                    img2 = img2.resize((args.crop_size, args.crop_size),
                                       Image.BICUBIC)
Z
zhumanyu 已提交
202 203 204 205 206

                img1 = (np.array(img1).astype('float32') / 255.0 - 0.5) / 0.5
                img1 = img1.transpose([2, 0, 1])
                img2 = (np.array(img2).astype('float32') / 255.0 - 0.5) / 0.5
                img2 = img2.transpose([2, 0, 1])
L
lvmengsi 已提交
207 208 209

                batch_out_1.append(img1)
                batch_out_2.append(img2)
Z
zhumanyu 已提交
210
                if return_name:
L
lvmengsi 已提交
211
                    batch_out_name.append(i)
Z
zhumanyu 已提交
212 213
                if len(batch_out_1) == self.batch_size:
                    if return_name:
L
lvmengsi 已提交
214 215
                        yield batch_out_1, batch_out_2, batch_out_name
                        batch_out_name = []
Z
zhumanyu 已提交
216 217
                    else:
                        yield batch_out_1, batch_out_2
L
lvmengsi 已提交
218 219
                    batch_out_1 = []
                    batch_out_2 = []
Z
zhumanyu 已提交
220 221 222 223

        return reader


Z
zhumanyu 已提交
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
class triplex_reader_creator(reader_creator):
    ''' read and preprocess dataset'''

    def __init__(self,
                 image_dir,
                 list_filename,
                 shuffle=False,
                 batch_size=1,
                 mode="TRAIN"):
        super(triplex_reader_creator, self).__init__(
            image_dir,
            list_filename,
            shuffle=shuffle,
            batch_size=batch_size,
            mode=mode)

    def make_reader(self, args, return_name=False):
        print(self.image_dir, self.list_filename)
        print("files length:", len(self.lines))

        def reader():
            batch_out_1 = []
            batch_out_2 = []
            batch_out_3 = []
            batch_out_name = []
            if self.shuffle:
                np.random.shuffle(self.lines)
            for line in self.lines:
                files = line.strip('\n\r\t ').split('\t')
                if len(files) != 3:
                    print("files is not equal to 3!")
                    sys.exit(-1)
                #label image instance
L
lvmengsi 已提交
257
                img1 = Image.open(os.path.join(self.image_dir, files[0]))
Z
zhumanyu 已提交
258 259 260
                img2 = Image.open(os.path.join(self.image_dir, files[
                    1])).convert('RGB')
                if not args.no_instance:
L
lvmengsi 已提交
261
                    img3 = Image.open(os.path.join(self.image_dir, files[2]))
Z
zhumanyu 已提交
262 263

                if self.mode == "TRAIN":
L
lvmengsi 已提交
264 265 266
                    param = get_preprocess_param(
                        args.load_width, args.load_height, args.crop_width,
                        args.crop_height)
Z
zhumanyu 已提交
267 268 269 270 271 272 273 274
                    img1 = img1.resize((args.load_width, args.load_height),
                                       Image.NEAREST)
                    img2 = img2.resize((args.load_width, args.load_height),
                                       Image.BICUBIC)
                    if not args.no_instance:
                        img3 = img3.resize((args.load_width, args.load_height),
                                           Image.NEAREST)
                    if args.crop_type == 'Centor':
L
lvmengsi 已提交
275 276 277 278
                        img1 = CentorCrop(img1, args.crop_width,
                                          args.crop_height)
                        img2 = CentorCrop(img2, args.crop_width,
                                          args.crop_height)
Z
zhumanyu 已提交
279
                        if not args.no_instance:
L
lvmengsi 已提交
280 281
                            img3 = CentorCrop(img3, args.crop_width,
                                              args.crop_height)
Z
zhumanyu 已提交
282 283 284 285 286 287 288 289
                    elif args.crop_type == 'Random':
                        x = param['crop_pos'][0]
                        y = param['crop_pos'][1]
                        img1 = img1.crop(
                            (x, y, x + args.crop_width, y + args.crop_height))
                        img2 = img2.crop(
                            (x, y, x + args.crop_width, y + args.crop_height))
                        if not args.no_instance:
L
lvmengsi 已提交
290 291
                            img3 = img3.crop((x, y, x + args.crop_width,
                                              y + args.crop_height))
Z
zhumanyu 已提交
292 293 294 295 296 297 298 299 300 301
                else:
                    img1 = img1.resize((args.crop_width, args.crop_height),
                                       Image.NEAREST)
                    img2 = img2.resize((args.crop_width, args.crop_height),
                                       Image.BICUBIC)
                    if not args.no_instance:
                        img3 = img3.resize((args.crop_width, args.crop_height),
                                           Image.NEAREST)

                img1 = np.array(img1)
L
lvmengsi 已提交
302 303 304 305
                index = img1[np.newaxis, :, :]
                input_label = np.zeros(
                    (args.label_nc, index.shape[1], index.shape[2]))
                np.put_along_axis(input_label, index, 1.0, 0)
Z
zhumanyu 已提交
306 307 308 309 310 311 312 313 314
                img1 = input_label
                img2 = (np.array(img2).astype('float32') / 255.0 - 0.5) / 0.5
                img2 = img2.transpose([2, 0, 1])
                if not args.no_instance:
                    img3 = np.array(img3)[:, :, np.newaxis]
                    img3 = img3.transpose([2, 0, 1])
                    ###extracte edge from instance
                    edge = np.zeros(img3.shape)
                    edge = edge.astype('int8')
L
lvmengsi 已提交
315 316 317 318 319 320 321 322
                    edge[:, :, 1:] = edge[:, :, 1:] | (
                        img3[:, :, 1:] != img3[:, :, :-1])
                    edge[:, :, :-1] = edge[:, :, :-1] | (
                        img3[:, :, 1:] != img3[:, :, :-1])
                    edge[:, 1:, :] = edge[:, 1:, :] | (
                        img3[:, 1:, :] != img3[:, :-1, :])
                    edge[:, :-1, :] = edge[:, :-1, :] | (
                        img3[:, 1:, :] != img3[:, :-1, :])
Z
zhumanyu 已提交
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
                    img3 = edge.astype('float32')
                    ###end extracte
                batch_out_1.append(img1)
                batch_out_2.append(img2)
                if not args.no_instance:
                    batch_out_3.append(img3)
                if return_name:
                    batch_out_name.append(os.path.basename(files[0]))
                if len(batch_out_1) == self.batch_size:
                    if return_name:
                        if not args.no_instance:
                            yield batch_out_1, batch_out_2, batch_out_3, batch_out_name
                        else:
                            yield batch_out_1, batch_out_2, batch_out_name
                        batch_out_name = []
                    else:
                        if not args.no_instance:
                            yield batch_out_1, batch_out_2, batch_out_3
                        else:
                            yield batch_out_1, batch_out_2
                    batch_out_1 = []
                    batch_out_2 = []
                    batch_out_3 = []

        return reader


L
lvmengsi 已提交
350 351 352
class celeba_reader_creator(reader_creator):
    ''' read and preprocess dataset'''

L
lvmengsi 已提交
353
    def __init__(self, image_dir, list_filename, args, mode="TRAIN"):
L
lvmengsi 已提交
354 355
        self.image_dir = image_dir
        self.list_filename = list_filename
L
lvmengsi 已提交
356 357
        self.mode = mode
        self.args = args
L
lvmengsi 已提交
358 359

        lines = open(self.list_filename).readlines()
L
lvmengsi 已提交
360 361 362 363 364

        all_num = int(lines[0])
        train_end = 2 + int(all_num * 0.9)
        test_end = train_end + int(all_num * 0.003)

L
lvmengsi 已提交
365 366 367 368
        all_attr_names = lines[1].split()
        attr2idx = {}
        for i, attr_name in enumerate(all_attr_names):
            attr2idx[attr_name] = i
L
lvmengsi 已提交
369 370 371 372 373 374 375 376 377 378 379 380 381

        if self.mode == "TRAIN":
            self.batch_size = args.batch_size
            self.shuffle = args.shuffle
            lines = lines[2:train_end]
        else:
            self.batch_size = args.n_samples
            self.shuffle = False
            if self.mode == "TEST":
                lines = lines[train_end:test_end]
            else:
                lines = lines[test_end:]

L
lvmengsi 已提交
382 383
        self.images = []
        attr_names = args.selected_attrs.split(',')
L
lvmengsi 已提交
384
        for i, line in enumerate(lines):
L
lvmengsi 已提交
385
            arr = line.strip().split()
L
lvmengsi 已提交
386
            name = os.path.join('img_align_celeba', arr[0])
L
lvmengsi 已提交
387 388 389 390
            label = []
            for attr_name in attr_names:
                idx = attr2idx[attr_name]
                label.append(arr[idx + 1] == "1")
L
lvmengsi 已提交
391
            self.images.append((name, label, arr[0]))
L
lvmengsi 已提交
392 393

    def len(self):
L
lvmengsi 已提交
394
        return len(self.images) // self.batch_size
L
lvmengsi 已提交
395

L
lvmengsi 已提交
396 397
    def make_reader(self, return_name=False):
        print(self.image_dir, self.list_filename)
L
lvmengsi 已提交
398 399 400 401

        def reader():
            batch_out_1 = []
            batch_out_2 = []
L
lvmengsi 已提交
402
            batch_out_3 = []
L
lvmengsi 已提交
403 404 405
            batch_out_name = []
            if self.shuffle:
                np.random.shuffle(self.images)
L
lvmengsi 已提交
406
            for file, label, f_name in self.images:
L
lvmengsi 已提交
407 408
                img = Image.open(os.path.join(self.image_dir, file))
                label = np.array(label).astype("float32")
L
lvmengsi 已提交
409 410 411 412
                if self.args.model_net == "StarGAN":
                    img = RandomHorizonFlip(img)
                img = CentorCrop(img, self.args.crop_size, self.args.crop_size)
                img = img.resize((self.args.image_size, self.args.image_size),
L
lvmengsi 已提交
413
                                 Image.BILINEAR)
L
lvmengsi 已提交
414 415
                img = (np.array(img).astype('float32') / 255.0 - 0.5) / 0.5
                img = img.transpose([2, 0, 1])
L
lvmengsi 已提交
416 417 418

                batch_out_1.append(img)
                batch_out_2.append(label)
L
lvmengsi 已提交
419
                if return_name:
L
lvmengsi 已提交
420
                    batch_out_name.append(int(f_name.split('.')[0]))
L
lvmengsi 已提交
421
                if len(batch_out_1) == self.batch_size:
L
lvmengsi 已提交
422 423 424
                    batch_out_3 = np.copy(batch_out_2)
                    if self.shuffle:
                        np.random.shuffle(batch_out_3)
L
lvmengsi 已提交
425
                    if return_name:
L
lvmengsi 已提交
426
                        yield batch_out_1, batch_out_2, batch_out_3, batch_out_name
L
lvmengsi 已提交
427
                        batch_out_name = []
L
lvmengsi 已提交
428
                    else:
L
lvmengsi 已提交
429
                        yield batch_out_1, batch_out_2, batch_out_3
L
lvmengsi 已提交
430 431
                    batch_out_1 = []
                    batch_out_2 = []
L
lvmengsi 已提交
432
                    batch_out_3 = []
L
lvmengsi 已提交
433 434 435 436

        return reader


L
lvmengsi 已提交
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
def mnist_reader_creator(image_filename, label_filename, buffer_size):
    def reader():
        with gzip.GzipFile(image_filename, 'rb') as image_file:
            img_buf = image_file.read()
            with gzip.GzipFile(label_filename, 'rb') as label_file:
                lab_buf = label_file.read()

                step_label = 0

                offset_img = 0
                # read from Big-endian
                # get file info from magic byte
                # image file : 16B
                magic_byte_img = '>IIII'
                magic_img, image_num, rows, cols = struct.unpack_from(
                    magic_byte_img, img_buf, offset_img)
                offset_img += struct.calcsize(magic_byte_img)

                offset_lab = 0
                # label file : 8B
                magic_byte_lab = '>II'
                magic_lab, label_num = struct.unpack_from(magic_byte_lab,
                                                          lab_buf, offset_lab)
                offset_lab += struct.calcsize(magic_byte_lab)

                while True:
                    if step_label >= label_num:
                        break
                    fmt_label = '>' + str(buffer_size) + 'B'
                    labels = struct.unpack_from(fmt_label, lab_buf, offset_lab)
                    offset_lab += struct.calcsize(fmt_label)
                    step_label += buffer_size

                    fmt_images = '>' + str(buffer_size * rows * cols) + 'B'
                    images_temp = struct.unpack_from(fmt_images, img_buf,
                                                     offset_img)
                    images = np.reshape(images_temp, (buffer_size, rows *
                                                      cols)).astype('float32')
                    offset_img += struct.calcsize(fmt_images)

                    images = images / 255.0 * 2.0 - 1.0
                    for i in range(buffer_size):
                        yield images[i, :], int(
                            labels[i])  # get image and label

    return reader


class data_reader(object):
    def __init__(self, cfg):
        self.cfg = cfg
        self.shuffle = self.cfg.shuffle

    def make_data(self):
        if self.cfg.dataset == 'mnist':
            train_images = os.path.join(self.cfg.data_dir, self.cfg.dataset,
                                        "train-images-idx3-ubyte.gz")
            train_labels = os.path.join(self.cfg.data_dir, self.cfg.dataset,
                                        "train-labels-idx1-ubyte.gz")

            train_reader = paddle.batch(
                paddle.reader.shuffle(
                    mnist_reader_creator(train_images, train_labels, 100),
                    buf_size=60000),
                batch_size=self.cfg.batch_size)
            return train_reader
        else:
L
lvmengsi 已提交
504
            if self.cfg.model_net in ['CycleGAN']:
L
lvmengsi 已提交
505 506 507 508 509 510
                dataset_dir = os.path.join(self.cfg.data_dir, self.cfg.dataset)
                trainA_list = os.path.join(dataset_dir, "trainA.txt")
                trainB_list = os.path.join(dataset_dir, "trainB.txt")
                a_train_reader = reader_creator(
                    image_dir=dataset_dir,
                    list_filename=trainA_list,
L
lvmengsi 已提交
511
                    shuffle=self.cfg.shuffle,
L
lvmengsi 已提交
512
                    batch_size=self.cfg.batch_size,
L
lvmengsi 已提交
513
                    mode="TRAIN")
L
lvmengsi 已提交
514 515 516
                b_train_reader = reader_creator(
                    image_dir=dataset_dir,
                    list_filename=trainB_list,
L
lvmengsi 已提交
517
                    shuffle=self.cfg.shuffle,
L
lvmengsi 已提交
518
                    batch_size=self.cfg.batch_size,
L
lvmengsi 已提交
519
                    mode="TRAIN")
L
lvmengsi 已提交
520 521
                a_reader_test = None
                b_reader_test = None
L
lvmengsi 已提交
522 523
                a_id2name = None
                b_id2name = None
L
lvmengsi 已提交
524 525 526 527 528 529
                if self.cfg.run_test:
                    testA_list = os.path.join(dataset_dir, "testA.txt")
                    testB_list = os.path.join(dataset_dir, "testB.txt")
                    a_test_reader = reader_creator(
                        image_dir=dataset_dir,
                        list_filename=testA_list,
L
lvmengsi 已提交
530
                        shuffle=False,
L
lvmengsi 已提交
531
                        batch_size=1,
L
lvmengsi 已提交
532
                        mode="TEST")
L
lvmengsi 已提交
533 534 535
                    b_test_reader = reader_creator(
                        image_dir=dataset_dir,
                        list_filename=testB_list,
L
lvmengsi 已提交
536
                        shuffle=False,
L
lvmengsi 已提交
537
                        batch_size=1,
L
lvmengsi 已提交
538 539 540 541 542
                        mode="TEST")
                    a_reader_test = a_test_reader.make_reader(
                        self.cfg, return_name=True)
                    b_reader_test = b_test_reader.make_reader(
                        self.cfg, return_name=True)
L
lvmengsi 已提交
543 544
                    a_id2name = a_test_reader.id2name
                    b_id2name = b_test_reader.id2name
L
lvmengsi 已提交
545 546

                batch_num = max(a_train_reader.len(), b_train_reader.len())
L
lvmengsi 已提交
547 548
                a_reader = a_train_reader.make_reader(self.cfg)
                b_reader = b_train_reader.make_reader(self.cfg)
L
lvmengsi 已提交
549

L
lvmengsi 已提交
550
                return a_reader, b_reader, a_reader_test, b_reader_test, batch_num, a_id2name, b_id2name
L
lvmengsi 已提交
551

L
lvmengsi 已提交
552
            elif self.cfg.model_net in ['StarGAN', 'STGAN', 'AttGAN']:
L
lvmengsi 已提交
553 554 555 556 557 558 559 560
                dataset_dir = os.path.join(self.cfg.data_dir, self.cfg.dataset)
                train_list = os.path.join(dataset_dir, 'train.txt')
                if self.cfg.train_list is not None:
                    train_list = self.cfg.train_list
                train_reader = celeba_reader_creator(
                    image_dir=dataset_dir,
                    list_filename=train_list,
                    args=self.cfg,
L
lvmengsi 已提交
561
                    mode="TRAIN")
L
lvmengsi 已提交
562 563
                reader_test = None
                if self.cfg.run_test:
L
lvmengsi 已提交
564
                    test_list = train_list
L
lvmengsi 已提交
565 566 567 568
                    if self.cfg.test_list is not None:
                        test_list = self.cfg.test_list
                    test_reader = celeba_reader_creator(
                        image_dir=dataset_dir,
L
lvmengsi 已提交
569 570 571 572
                        list_filename=train_list,
                        args=self.cfg,
                        mode="TEST")
                    reader_test = test_reader.make_reader(return_name=True)
L
lvmengsi 已提交
573
                batch_num = train_reader.len()
L
lvmengsi 已提交
574
                reader = train_reader.make_reader()
L
lvmengsi 已提交
575
                return reader, reader_test, batch_num, None
L
lvmengsi 已提交
576

L
lvmengsi 已提交
577
            elif self.cfg.model_net in ['Pix2pix']:
Z
zhumanyu 已提交
578 579 580 581 582 583 584
                dataset_dir = os.path.join(self.cfg.data_dir, self.cfg.dataset)
                train_list = os.path.join(dataset_dir, 'train.txt')
                if self.cfg.train_list is not None:
                    train_list = self.cfg.train_list
                train_reader = pair_reader_creator(
                    image_dir=dataset_dir,
                    list_filename=train_list,
L
lvmengsi 已提交
585
                    shuffle=self.cfg.shuffle,
Z
zhumanyu 已提交
586
                    batch_size=self.cfg.batch_size,
L
lvmengsi 已提交
587
                    mode="TRAIN")
Z
zhumanyu 已提交
588
                reader_test = None
L
lvmengsi 已提交
589
                id2name = None
Z
zhumanyu 已提交
590 591 592 593 594 595 596
                if self.cfg.run_test:
                    test_list = os.path.join(dataset_dir, "test.txt")
                    if self.cfg.test_list is not None:
                        test_list = self.cfg.test_list
                    test_reader = pair_reader_creator(
                        image_dir=dataset_dir,
                        list_filename=test_list,
L
lvmengsi 已提交
597
                        shuffle=False,
Z
zhumanyu 已提交
598
                        batch_size=1,
L
lvmengsi 已提交
599 600 601
                        mode="TEST")
                    reader_test = test_reader.make_reader(
                        self.cfg, return_name=True)
L
lvmengsi 已提交
602
                    id2name = test_reader.id2name
Z
zhumanyu 已提交
603 604
                batch_num = train_reader.len()
                reader = train_reader.make_reader(self.cfg)
L
lvmengsi 已提交
605
                return reader, reader_test, batch_num, id2name
Z
zhumanyu 已提交
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
            elif self.cfg.model_net in ['SPADE']:
                dataset_dir = os.path.join(self.cfg.data_dir, self.cfg.dataset)
                train_list = os.path.join(dataset_dir, 'train.txt')
                if self.cfg.train_list is not None:
                    train_list = self.cfg.train_list
                train_reader = triplex_reader_creator(
                    image_dir=dataset_dir,
                    list_filename=train_list,
                    shuffle=self.cfg.shuffle,
                    batch_size=self.cfg.batch_size,
                    mode="TRAIN")
                reader_test = None
                if self.cfg.run_test:
                    test_list = os.path.join(dataset_dir, "test.txt")
                    if self.cfg.test_list is not None:
                        test_list = self.cfg.test_list
                    test_reader = triplex_reader_creator(
                        image_dir=dataset_dir,
                        list_filename=test_list,
                        shuffle=False,
                        batch_size=1,
                        mode="TEST")
                    reader_test = test_reader.make_reader(
                        self.cfg, return_name=True)
L
lvmengsi 已提交
630
                    id2name = test_reader.id2name
Z
zhumanyu 已提交
631
                batch_num = train_reader.len()
L
lvmengsi 已提交
632
                reader = train_reader.make_reader(self.cfg)
L
lvmengsi 已提交
633
                return reader, reader_test, batch_num, id2name
L
lvmengsi 已提交
634 635 636 637 638 639 640 641
            else:
                dataset_dir = os.path.join(self.cfg.data_dir, self.cfg.dataset)
                train_list = os.path.join(dataset_dir, 'train.txt')
                if self.cfg.train_list is not None:
                    train_list = self.cfg.train_list
                train_reader = reader_creator(
                    image_dir=dataset_dir, list_filename=train_list)
                reader_test = None
L
lvmengsi 已提交
642
                id2name = None
L
lvmengsi 已提交
643 644 645 646 647
                if self.cfg.run_test:
                    test_list = os.path.join(dataset_dir, "test.txt")
                    test_reader = reader_creator(
                        image_dir=dataset_dir,
                        list_filename=test_list,
L
lvmengsi 已提交
648
                        batch_size=self.cfg.n_samples)
L
lvmengsi 已提交
649 650
                    reader_test = test_reader.get_test_reader(
                        self.cfg, shuffle=False, return_name=True)
L
lvmengsi 已提交
651
                    id2name = test_reader.id2name
L
lvmengsi 已提交
652
                batch_num = train_reader.len()
L
lvmengsi 已提交
653
                return train_reader, reader_test, batch_num, id2name