reader.py 4.6 KB
Newer Older
W
wangmeng28 已提交
1
import os
W
wangmeng28 已提交
2
import math
W
wangmeng28 已提交
3 4 5
import random
import functools
import numpy as np
6
import paddle
W
wangmeng28 已提交
7 8 9 10 11 12 13
from PIL import Image, ImageEnhance

random.seed(0)

DATA_DIM = 224

THREAD = 8
14
BUF_SIZE = 102400
W
wangmeng28 已提交
15

16 17 18
DATA_DIR = 'data/ILSVRC2012'
TRAIN_LIST = 'data/ILSVRC2012/train_list.txt'
TEST_LIST = 'data/ILSVRC2012/val_list.txt'
W
wangmeng28 已提交
19

W
wangmeng28 已提交
20 21
img_mean = np.array([0.485, 0.456, 0.406]).reshape((3, 1, 1))
img_std = np.array([0.229, 0.224, 0.225]).reshape((3, 1, 1))
W
wangmeng28 已提交
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46


def resize_short(img, target_size):
    percent = float(target_size) / min(img.size[0], img.size[1])
    resized_width = int(round(img.size[0] * percent))
    resized_height = int(round(img.size[1] * percent))
    img = img.resize((resized_width, resized_height), Image.LANCZOS)
    return img


def crop_image(img, target_size, center):
    width, height = img.size
    size = target_size
    if center == True:
        w_start = (width - size) / 2
        h_start = (height - size) / 2
    else:
        w_start = random.randint(0, width - size)
        h_start = random.randint(0, height - size)
    w_end = w_start + size
    h_end = h_start + size
    img = img.crop((w_start, h_start, w_end, h_end))
    return img


W
wangmeng28 已提交
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
def random_crop(img, size, scale=[0.08, 1.0], ratio=[3. / 4., 4. / 3.]):
    aspect_ratio = math.sqrt(random.uniform(*ratio))
    w = 1. * aspect_ratio
    h = 1. / aspect_ratio

    bound = min((float(img.size[0]) / img.size[1]) / (w**2),
                (float(img.size[1]) / img.size[0]) / (h**2))
    scale_max = min(scale[1], bound)
    scale_min = min(scale[0], bound)

    target_area = img.size[0] * img.size[1] * random.uniform(scale_min,
                                                             scale_max)
    target_size = math.sqrt(target_area)
    w = int(target_size * w)
    h = int(target_size * h)

    i = random.randint(0, img.size[0] - w)
    j = random.randint(0, img.size[1] - h)

    img = img.crop((i, j, i + w, j + h))
    img = img.resize((size, size), Image.LANCZOS)
    return img


71 72 73 74 75 76
def rotate_image(img):
    angle = random.randint(-10, 10)
    img = img.rotate(angle)
    return img


W
wangmeng28 已提交
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
def distort_color(img):
    def random_brightness(img, lower=0.5, upper=1.5):
        e = random.uniform(lower, upper)
        return ImageEnhance.Brightness(img).enhance(e)

    def random_contrast(img, lower=0.5, upper=1.5):
        e = random.uniform(lower, upper)
        return ImageEnhance.Contrast(img).enhance(e)

    def random_color(img, lower=0.5, upper=1.5):
        e = random.uniform(lower, upper)
        return ImageEnhance.Color(img).enhance(e)

    ops = [random_brightness, random_contrast, random_color]
    random.shuffle(ops)

    img = ops[0](img)
    img = ops[1](img)
    img = ops[2](img)

    return img


W
wangmeng28 已提交
100
def process_image(sample, mode, color_jitter, rotate):
W
wangmeng28 已提交
101 102 103 104
    img_path = sample[0]

    img = Image.open(img_path)
    if mode == 'train':
W
wangmeng28 已提交
105 106
        if rotate: img = rotate_image(img)
        img = random_crop(img, DATA_DIM)
W
wangmeng28 已提交
107
    else:
108
        img = resize_short(img, target_size=256)
W
wangmeng28 已提交
109
        img = crop_image(img, target_size=DATA_DIM, center=True)
W
wangmeng28 已提交
110
    if mode == 'train':
W
wangmeng28 已提交
111 112
        if color_jitter:
            img = distort_color(img)
W
wangmeng28 已提交
113 114 115 116 117 118
        if random.randint(0, 1) == 1:
            img = img.transpose(Image.FLIP_LEFT_RIGHT)

    if img.mode != 'RGB':
        img = img.convert('RGB')

W
wangmeng28 已提交
119
    img = np.array(img).astype('float32').transpose((2, 0, 1)) / 255
W
wangmeng28 已提交
120
    img -= img_mean
W
wangmeng28 已提交
121
    img /= img_std
W
wangmeng28 已提交
122

123
    if mode == 'train' or mode == 'val':
W
wangmeng28 已提交
124
        return img, sample[1]
125
    elif mode == 'test':
126
        return [img]
W
wangmeng28 已提交
127 128


W
wangmeng28 已提交
129 130 131 132 133
def _reader_creator(file_list,
                    mode,
                    shuffle=False,
                    color_jitter=False,
                    rotate=False):
W
wangmeng28 已提交
134 135 136 137 138 139
    def reader():
        with open(file_list) as flist:
            lines = [line.strip() for line in flist]
            if shuffle:
                random.shuffle(lines)
            for line in lines:
140
                if mode == 'train' or mode == 'val':
W
wangmeng28 已提交
141 142 143
                    img_path, label = line.split()
                    img_path = os.path.join(DATA_DIR, img_path)
                    yield img_path, int(label)
144
                elif mode == 'test':
W
wangmeng28 已提交
145 146 147
                    img_path = os.path.join(DATA_DIR, line)
                    yield [img_path]

W
wangmeng28 已提交
148 149
    mapper = functools.partial(
        process_image, mode=mode, color_jitter=color_jitter, rotate=rotate)
W
wangmeng28 已提交
150 151 152 153

    return paddle.reader.xmap_readers(mapper, reader, THREAD, BUF_SIZE)


154
def train(file_list=TRAIN_LIST):
W
wangmeng28 已提交
155
    return _reader_creator(
156
        file_list, 'train', shuffle=True, color_jitter=False, rotate=False)
W
wangmeng28 已提交
157 158


159 160
def val(file_list=TEST_LIST):
    return _reader_creator(file_list, 'val', shuffle=False)
W
wangmeng28 已提交
161 162


163 164
def test(file_list):
    return _reader_creator(file_list, 'test', shuffle=False)