flowers.py 8.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# 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.
"""
This module will download dataset from
16
http://www.robots.ox.ac.uk/~vgg/data/flowers/102/index.html
17 18
and parse train/test set intopaddle reader creators.

19
This set contains images of flowers belonging to 102 different categories.
20 21 22 23 24 25
The images were acquired by searching the web and taking pictures. There are a
minimum of 40 images for each category.

The database was used in:

Nilsback, M-E. and Zisserman, A. Automated flower classification over a large
26 27
 number of classes.Proceedings of the Indian Conference on Computer Vision,
Graphics and Image Processing (2008)
28 29 30
http://www.robots.ox.ac.uk/~vgg/publications/papers/nilsback08.{pdf,ps.gz}.

"""
31 32 33

from __future__ import print_function

34
import itertools
35
import functools
36
from .common import download
37
import tarfile
38 39 40 41 42 43

from paddle.dataset.image import load_image_bytes
from paddle.dataset.image import load_image
from paddle.dataset.image import simple_transform
from paddle.dataset.image import batch_images_from_tar

44
from paddle.reader import map_readers, xmap_readers
M
minqiyang 已提交
45
from paddle import compat as cpt
46
import paddle.utils.deprecated as deprecated
47 48
import os
import numpy as np
49
from multiprocessing import cpu_count
M
minqiyang 已提交
50
import six
51
from six.moves import cPickle as pickle
L
LielinJiang 已提交
52
from paddle.utils import try_import
53

54 55
__all__ = []

56 57 58
DATA_URL = 'http://paddlemodels.bj.bcebos.com/flowers/102flowers.tgz'
LABEL_URL = 'http://paddlemodels.bj.bcebos.com/flowers/imagelabels.mat'
SETID_URL = 'http://paddlemodels.bj.bcebos.com/flowers/setid.mat'
M
minqiyang 已提交
59
DATA_MD5 = '52808999861908f626f3c1f4e79d11fa'
60 61
LABEL_MD5 = 'e0620be6f572b9609742df49c70aed4d'
SETID_MD5 = 'a5357ecc9cb78c4bef273ce3793fc85c'
W
wanghaoshuang 已提交
62 63 64 65 66 67
# In official 'readme', tstid is the flag of test data
# and trnid is the flag of train data. But test data is more than train data.
# So we exchange the train data and test data.
TRAIN_FLAG = 'tstid'
TEST_FLAG = 'trnid'
VALID_FLAG = 'valid'
68 69


70
def default_mapper(is_train, sample):
71 72 73 74
    '''
    map image bytes data to type needed by model input layer
    '''
    img, label = sample
75
    img = load_image_bytes(img)
D
dangqingqing 已提交
76
    img = simple_transform(
D
dangqingqing 已提交
77
        img, 256, 224, is_train, mean=[103.94, 116.78, 123.68])
78 79 80
    return img.flatten().astype('float32'), label


81 82 83 84
train_mapper = functools.partial(default_mapper, True)
test_mapper = functools.partial(default_mapper, False)


85 86 87
def reader_creator(data_file,
                   label_file,
                   setid_file,
88
                   dataset_name,
89
                   mapper,
90
                   buffered_size=1024,
91 92
                   use_xmap=True,
                   cycle=False):
93
    '''
94
    1. read images from tar file and
95 96
        merge images into batch files in 102flowers.tgz_batch/
    2. get a reader to read sample from batch file
97 98

    :param data_file: downloaded data file
99
    :type data_file: string
100
    :param label_file: downloaded label file
101 102 103 104
    :type label_file: string
    :param setid_file: downloaded setid file containing information
                        about how to split dataset
    :type setid_file: string
105 106
    :param dataset_name: data set name (tstid|trnid|valid)
    :type dataset_name: string
107
    :param mapper: a function to map image bytes data to type
108 109
                    needed by model input layer
    :type mapper: callable
110 111
    :param buffered_size: the size of buffer used to process images
    :type buffered_size: int
112 113
    :param cycle: whether to cycle through the dataset
    :type cycle: bool
114 115 116
    :return: data reader
    :rtype: callable
    '''
L
LielinJiang 已提交
117 118
    scio = try_import('scipy.io')

119 120
    labels = scio.loadmat(label_file)['labels'][0]
    indexes = scio.loadmat(setid_file)[dataset_name][0]
L
LielinJiang 已提交
121

122 123 124 125 126
    img2label = {}
    for i in indexes:
        img = "jpg/image_%05d.jpg" % i
        img2label[img] = labels[i - 1]
    file_list = batch_images_from_tar(data_file, dataset_name, img2label)
127 128

    def reader():
129
        while True:
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
            with open(file_list, 'r') as f_list:
                for file in f_list:
                    file = file.strip()
                    batch = None
                    with open(file, 'rb') as f:
                        if six.PY2:
                            batch = pickle.load(f)
                        else:
                            batch = pickle.load(f, encoding='bytes')

                        if six.PY3:
                            batch = cpt.to_text(batch)
                        data_batch = batch['data']
                        labels_batch = batch['label']
                        for sample, label in six.moves.zip(data_batch,
                                                           labels_batch):
                            yield sample, int(label) - 1
147 148
            if not cycle:
                break
149

W
wanghaoshuang 已提交
150
    if use_xmap:
C
chengduo 已提交
151
        return xmap_readers(mapper, reader, min(4, cpu_count()), buffered_size)
152 153
    else:
        return map_readers(mapper, reader)
154 155


156 157 158 159
@deprecated(
    since="2.0.0",
    update_to="paddle.vision.datasets.Flowers",
    reason="Please use new dataset API which supports paddle.io.DataLoader")
160
def train(mapper=train_mapper, buffered_size=1024, use_xmap=True, cycle=False):
161
    '''
162 163 164
    Create flowers training set reader.
    It returns a reader, each sample in the reader is
    image pixels in [0, 1] and label in [1, 102]
165 166 167 168 169 170
    translated from original color image by steps:
    1. resize to 256*256
    2. random crop to 224*224
    3. flatten
    :param mapper:  a function to map sample.
    :type mapper: callable
171 172
    :param buffered_size: the size of buffer used to process images
    :type buffered_size: int
173 174
    :param cycle: whether to cycle through the dataset
    :type cycle: bool
175 176 177 178 179 180
    :return: train data reader
    :rtype: callable
    '''
    return reader_creator(
        download(DATA_URL, 'flowers', DATA_MD5),
        download(LABEL_URL, 'flowers', LABEL_MD5),
181 182 183 184 185 186
        download(SETID_URL, 'flowers', SETID_MD5),
        TRAIN_FLAG,
        mapper,
        buffered_size,
        use_xmap,
        cycle=cycle)
187 188


189 190 191 192
@deprecated(
    since="2.0.0",
    update_to="paddle.vision.datasets.Flowers",
    reason="Please use new dataset API which supports paddle.io.DataLoader")
193
def test(mapper=test_mapper, buffered_size=1024, use_xmap=True, cycle=False):
194
    '''
195 196 197
    Create flowers test set reader.
    It returns a reader, each sample in the reader is
    image pixels in [0, 1] and label in [1, 102]
198 199 200 201 202 203
    translated from original color image by steps:
    1. resize to 256*256
    2. random crop to 224*224
    3. flatten
    :param mapper:  a function to map sample.
    :type mapper: callable
204 205
    :param buffered_size: the size of buffer used to process images
    :type buffered_size: int
206 207
    :param cycle: whether to cycle through the dataset
    :type cycle: bool
208 209 210 211 212 213
    :return: test data reader
    :rtype: callable
    '''
    return reader_creator(
        download(DATA_URL, 'flowers', DATA_MD5),
        download(LABEL_URL, 'flowers', LABEL_MD5),
214 215 216 217 218 219
        download(SETID_URL, 'flowers', SETID_MD5),
        TEST_FLAG,
        mapper,
        buffered_size,
        use_xmap,
        cycle=cycle)
220 221


222 223 224 225
@deprecated(
    since="2.0.0",
    update_to="paddle.vision.datasets.Flowers",
    reason="Please use new dataset API which supports paddle.io.DataLoader")
226
def valid(mapper=test_mapper, buffered_size=1024, use_xmap=True):
227
    '''
228 229 230
    Create flowers validation set reader.
    It returns a reader, each sample in the reader is
    image pixels in [0, 1] and label in [1, 102]
231 232 233 234
    translated from original color image by steps:
    1. resize to 256*256
    2. random crop to 224*224
    3. flatten
235 236 237 238 239 240
    :param mapper:  a function to map sample.
    :type mapper: callable
    :param buffered_size: the size of buffer used to process images
    :type buffered_size: int
    :return: test data reader
    :rtype: callable
241 242 243 244
    '''
    return reader_creator(
        download(DATA_URL, 'flowers', DATA_MD5),
        download(LABEL_URL, 'flowers', LABEL_MD5),
W
wanghaoshuang 已提交
245 246
        download(SETID_URL, 'flowers', SETID_MD5), VALID_FLAG, mapper,
        buffered_size, use_xmap)
247 248 249 250 251 252


def fetch():
    download(DATA_URL, 'flowers', DATA_MD5)
    download(LABEL_URL, 'flowers', LABEL_MD5)
    download(SETID_URL, 'flowers', SETID_MD5)