data_reader.py 27.4 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


50
def get_preprocess_param2(load_size, crop_size):
Z
zhumanyu 已提交
51 52 53 54 55 56 57 58 59 60 61
    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
    }


62
def get_preprocess_param4(load_width, load_height, crop_width, crop_height):
Z
zhumanyu 已提交
63 64 65 66 67 68 69
    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
                if self.mode == "TRAIN":
181 182
                    param = get_preprocess_param2(args.image_size,
                                                  args.crop_size)
L
lvmengsi 已提交
183
                    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
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)

L
lvmengsi 已提交
240 241
        self.name2id = {}
        self.id2name = {}
L
lvmengsi 已提交
242

Z
zhumanyu 已提交
243 244 245 246 247 248 249 250 251 252 253
    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)
L
lvmengsi 已提交
254
            for i, line in enumerate(self.lines):
Z
zhumanyu 已提交
255 256 257 258
                files = line.strip('\n\r\t ').split('\t')
                if len(files) != 3:
                    print("files is not equal to 3!")
                    sys.exit(-1)
L
lvmengsi 已提交
259 260
                self.name2id[os.path.basename(files[0])] = i
                self.id2name[i] = os.path.basename(files[0])
Z
zhumanyu 已提交
261
                #label image instance
L
lvmengsi 已提交
262
                img1 = Image.open(os.path.join(self.image_dir, files[0]))
Z
zhumanyu 已提交
263 264 265
                img2 = Image.open(os.path.join(self.image_dir, files[
                    1])).convert('RGB')
                if not args.no_instance:
L
lvmengsi 已提交
266
                    img3 = Image.open(os.path.join(self.image_dir, files[2]))
Z
zhumanyu 已提交
267 268

                if self.mode == "TRAIN":
269
                    param = get_preprocess_param4(
L
lvmengsi 已提交
270 271
                        args.load_width, args.load_height, args.crop_width,
                        args.crop_height)
Z
zhumanyu 已提交
272 273 274 275 276 277 278 279
                    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 已提交
280 281 282 283
                        img1 = CentorCrop(img1, args.crop_width,
                                          args.crop_height)
                        img2 = CentorCrop(img2, args.crop_width,
                                          args.crop_height)
Z
zhumanyu 已提交
284
                        if not args.no_instance:
L
lvmengsi 已提交
285 286
                            img3 = CentorCrop(img3, args.crop_width,
                                              args.crop_height)
Z
zhumanyu 已提交
287 288 289 290 291 292 293 294
                    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 已提交
295 296
                            img3 = img3.crop((x, y, x + args.crop_width,
                                              y + args.crop_height))
Z
zhumanyu 已提交
297 298 299 300 301 302 303 304 305 306
                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 已提交
307 308 309 310
                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)
L
Lv Mengsi 已提交
311
                img1 = input_label.astype('float32')
Z
zhumanyu 已提交
312 313 314 315 316 317 318 319
                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 已提交
320 321 322 323 324 325 326 327
                    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 已提交
328 329 330 331 332 333 334
                    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:
L
lvmengsi 已提交
335
                    batch_out_name.append(i)
Z
zhumanyu 已提交
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
                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 已提交
355 356 357
class celeba_reader_creator(reader_creator):
    ''' read and preprocess dataset'''

L
lvmengsi 已提交
358
    def __init__(self, image_dir, list_filename, args, mode="TRAIN"):
L
lvmengsi 已提交
359 360
        self.image_dir = image_dir
        self.list_filename = list_filename
L
lvmengsi 已提交
361 362
        self.mode = mode
        self.args = args
L
lvmengsi 已提交
363 364

        lines = open(self.list_filename).readlines()
L
lvmengsi 已提交
365 366 367 368 369

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

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

        if self.mode == "TRAIN":
            self.batch_size = args.batch_size
            self.shuffle = args.shuffle
            lines = lines[2:train_end]
L
lvmengsi 已提交
379
        elif self.mode == 'TEST':
L
lvmengsi 已提交
380 381
            self.batch_size = args.n_samples
            self.shuffle = False
L
lvmengsi 已提交
382 383 384 385 386 387 388 389 390
            lines = lines[train_end:test_end]
        elif self.mode == 'VAL':
            self.batch_size = args.n_samples
            self.shuffle = False
            lines = lines[2:]
        else:
            raise NotImplementedError(
                "Wrong Reader MODE: {}, mode must in [TRAIN|TEST|VAL]".format(
                    self.mode))
L
lvmengsi 已提交
391

L
lvmengsi 已提交
392 393
        self.images = []
        attr_names = args.selected_attrs.split(',')
L
lvmengsi 已提交
394
        for i, line in enumerate(lines):
L
lvmengsi 已提交
395
            arr = line.strip().split()
L
lvmengsi 已提交
396
            name = os.path.join('img_align_celeba', arr[0])
L
lvmengsi 已提交
397 398 399 400
            label = []
            for attr_name in attr_names:
                idx = attr2idx[attr_name]
                label.append(arr[idx + 1] == "1")
L
lvmengsi 已提交
401
            self.images.append((name, label, arr[0]))
L
lvmengsi 已提交
402 403

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

L
lvmengsi 已提交
406 407
    def make_reader(self, return_name=False):
        print(self.image_dir, self.list_filename)
L
lvmengsi 已提交
408 409 410 411

        def reader():
            batch_out_1 = []
            batch_out_2 = []
L
lvmengsi 已提交
412
            batch_out_3 = []
L
lvmengsi 已提交
413 414 415
            batch_out_name = []
            if self.shuffle:
                np.random.shuffle(self.images)
L
lvmengsi 已提交
416
            for file, label, f_name in self.images:
L
lvmengsi 已提交
417 418
                img = Image.open(os.path.join(self.image_dir, file))
                label = np.array(label).astype("float32")
L
lvmengsi 已提交
419 420 421 422
                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 已提交
423
                                 Image.BILINEAR)
L
lvmengsi 已提交
424 425
                img = (np.array(img).astype('float32') / 255.0 - 0.5) / 0.5
                img = img.transpose([2, 0, 1])
L
lvmengsi 已提交
426 427 428

                batch_out_1.append(img)
                batch_out_2.append(label)
L
lvmengsi 已提交
429
                if return_name:
L
lvmengsi 已提交
430
                    batch_out_name.append(int(f_name.split('.')[0]))
L
lvmengsi 已提交
431
                if len(batch_out_1) == self.batch_size:
L
lvmengsi 已提交
432 433 434
                    batch_out_3 = np.copy(batch_out_2)
                    if self.shuffle:
                        np.random.shuffle(batch_out_3)
L
lvmengsi 已提交
435
                    if return_name:
L
lvmengsi 已提交
436
                        yield batch_out_1, batch_out_2, batch_out_3, batch_out_name
L
lvmengsi 已提交
437
                        batch_out_name = []
L
lvmengsi 已提交
438
                    else:
L
lvmengsi 已提交
439
                        yield batch_out_1, batch_out_2, batch_out_3
L
lvmengsi 已提交
440 441
                    batch_out_1 = []
                    batch_out_2 = []
L
lvmengsi 已提交
442
                    batch_out_3 = []
L
lvmengsi 已提交
443 444 445 446

        return reader


L
lvmengsi 已提交
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 504 505 506 507 508 509 510 511 512 513
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 已提交
514
            if self.cfg.model_net in ['CycleGAN']:
L
lvmengsi 已提交
515 516 517 518 519 520
                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 已提交
521
                    shuffle=self.cfg.shuffle,
L
lvmengsi 已提交
522
                    batch_size=self.cfg.batch_size,
L
lvmengsi 已提交
523
                    mode="TRAIN")
L
lvmengsi 已提交
524 525 526
                b_train_reader = reader_creator(
                    image_dir=dataset_dir,
                    list_filename=trainB_list,
L
lvmengsi 已提交
527
                    shuffle=self.cfg.shuffle,
L
lvmengsi 已提交
528
                    batch_size=self.cfg.batch_size,
L
lvmengsi 已提交
529
                    mode="TRAIN")
L
lvmengsi 已提交
530 531
                a_reader_test = None
                b_reader_test = None
L
lvmengsi 已提交
532 533
                a_id2name = None
                b_id2name = None
L
lvmengsi 已提交
534 535 536 537 538 539
                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 已提交
540
                        shuffle=False,
L
lvmengsi 已提交
541
                        batch_size=1,
L
lvmengsi 已提交
542
                        mode="TEST")
L
lvmengsi 已提交
543 544 545
                    b_test_reader = reader_creator(
                        image_dir=dataset_dir,
                        list_filename=testB_list,
L
lvmengsi 已提交
546
                        shuffle=False,
L
lvmengsi 已提交
547
                        batch_size=1,
L
lvmengsi 已提交
548 549 550 551 552
                        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 已提交
553 554
                    a_id2name = a_test_reader.id2name
                    b_id2name = b_test_reader.id2name
L
lvmengsi 已提交
555 556

                batch_num = max(a_train_reader.len(), b_train_reader.len())
L
lvmengsi 已提交
557 558
                a_reader = a_train_reader.make_reader(self.cfg)
                b_reader = b_train_reader.make_reader(self.cfg)
L
lvmengsi 已提交
559

L
lvmengsi 已提交
560
                return a_reader, b_reader, a_reader_test, b_reader_test, batch_num, a_id2name, b_id2name
L
lvmengsi 已提交
561

L
lvmengsi 已提交
562
            elif self.cfg.model_net in ['StarGAN', 'STGAN', 'AttGAN']:
L
lvmengsi 已提交
563 564 565 566 567 568 569 570
                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 已提交
571
                    mode="TRAIN")
L
lvmengsi 已提交
572 573
                reader_test = None
                if self.cfg.run_test:
L
lvmengsi 已提交
574
                    test_list = train_list
L
lvmengsi 已提交
575 576 577 578
                    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 已提交
579 580 581 582
                        list_filename=train_list,
                        args=self.cfg,
                        mode="TEST")
                    reader_test = test_reader.make_reader(return_name=True)
L
lvmengsi 已提交
583
                batch_num = train_reader.len()
L
lvmengsi 已提交
584
                reader = train_reader.make_reader()
L
lvmengsi 已提交
585
                return reader, reader_test, batch_num, None
L
lvmengsi 已提交
586

L
lvmengsi 已提交
587
            elif self.cfg.model_net in ['Pix2pix']:
Z
zhumanyu 已提交
588 589 590 591 592 593 594
                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 已提交
595
                    shuffle=self.cfg.shuffle,
Z
zhumanyu 已提交
596
                    batch_size=self.cfg.batch_size,
L
lvmengsi 已提交
597
                    mode="TRAIN")
Z
zhumanyu 已提交
598
                reader_test = None
L
lvmengsi 已提交
599
                id2name = None
Z
zhumanyu 已提交
600 601 602 603 604 605 606
                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 已提交
607
                        shuffle=False,
Z
zhumanyu 已提交
608
                        batch_size=1,
L
lvmengsi 已提交
609 610 611
                        mode="TEST")
                    reader_test = test_reader.make_reader(
                        self.cfg, return_name=True)
L
lvmengsi 已提交
612
                    id2name = test_reader.id2name
Z
zhumanyu 已提交
613 614
                batch_num = train_reader.len()
                reader = train_reader.make_reader(self.cfg)
L
lvmengsi 已提交
615
                return reader, reader_test, batch_num, id2name
Z
zhumanyu 已提交
616 617 618 619 620
            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
L
lvmengsi 已提交
621 622 623 624 625
                if not os.path.exists(train_list):
                    print(
                        "train_list is NOT EXIST!!! Please prepare train list first"
                    )
                    sys.exit(1)
Z
zhumanyu 已提交
626 627 628 629 630 631 632
                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
C
ceci3 已提交
633
                id2name = None
Z
zhumanyu 已提交
634 635 636 637
                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
L
lvmengsi 已提交
638 639 640 641 642
                    if not os.path.exists(test_list):
                        print(
                            "test_list is NOT EXIST!!! Please prepare test list first"
                        )
                        sys.exit(1)
Z
zhumanyu 已提交
643 644 645 646 647 648 649 650
                    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 已提交
651
                    id2name = test_reader.id2name
Z
zhumanyu 已提交
652
                batch_num = train_reader.len()
L
lvmengsi 已提交
653
                reader = train_reader.make_reader(self.cfg)
L
lvmengsi 已提交
654
                return reader, reader_test, batch_num, id2name
L
lvmengsi 已提交
655 656 657 658 659 660 661 662
            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 已提交
663
                id2name = None
L
lvmengsi 已提交
664 665 666 667 668
                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 已提交
669
                        batch_size=self.cfg.n_samples)
L
lvmengsi 已提交
670 671
                    reader_test = test_reader.get_test_reader(
                        self.cfg, shuffle=False, return_name=True)
L
lvmengsi 已提交
672
                    id2name = test_reader.id2name
L
lvmengsi 已提交
673
                batch_num = train_reader.len()
L
lvmengsi 已提交
674
                return train_reader, reader_test, batch_num, id2name