Commit 4f9f3a19 authored by Amelie Royer's avatar Amelie Royer

Adding CIFAR100

parent 330d96bd
......@@ -8,7 +8,9 @@
`TFDatasets` is a collection of scripts to preprocess various Computer Vision datasets and convert them to `TFRecords` for easy integration in the `tf.data.Dataset` pipeline.
The notebook `load_datasets.ipynb` displays examples of writing and parsing TFRecords for each dataset.
The notebook `load_datasets.ipynb` displays examples of writing and parsing TFRecords for each dataset. See the last section of this readme for an index of available datasets.
The notebook `preprocess.ipynb` displays of example of various preprocessing utilities for `tf.data.Dataset` (adding random crops, occlusion generation, subsampling etc.) demonstrated on the mnist dataset.
---
......@@ -35,7 +37,7 @@ The loader simply builds a proper parsing function to extract data from the TFRe
| ACwS | [Apparel Classification with Style](http://www.vision.ee.ethz.ch/~lbossard/projects/accv12/index.html) | ![acws_thumb](images/acws.png) | image, class |
| CelebA | [CelebA](http://mmlab.ie.cuhk.edu.hk/projects/CelebA.html) | ![celeba_thumb](images/celeba.png) | image, bounding-box, attributes, landmarks |
| CartoonSet | [CartoonSet](https://google.github.io/cartoonset/) | ![cartoonset_thumb](images/cartoonset.png) | image, bounding-box, attributes |
| CIFAR-10 | [CIFAR-10](https://www.cs.toronto.edu/~kriz/cifar.html) | ![cifar10_thumb](images/cifar10.png) | image, class, class-name |
| CIFAR-10(0) | [CIFAR](https://www.cs.toronto.edu/~kriz/cifar.html) | ![cifar10_thumb](images/cifar10.png) | image, class, (coarse_class), (coarse_)class-name, |
| Fashion MNIST| [Fashion MNIST](https://github.com/zalandoresearch/fashion-mnist) | ![fashion_mnist_thumb](images/fashion_mnist.png) | image, class, index|
| MNIST | [MNIST](http://yann.lecun.com/exdb/mnist/) | ![mnist_thumb](images/mnist.png) | image, digit-class, index |
| MNIST-M | [MNIST-M](http://yaroslav.ganin.net/) | ![mnistm_thumb](images/mnistm.png) | image, digit-class, index |
......
from __future__ import print_function
###############################################
# CIFAR-10 #
# CIFAR #
# https://www.cs.toronto.edu/~kriz/cifar.html #
###############################################
import base64
......@@ -63,9 +63,49 @@ class CIFAR10Converter(Converter):
writer.close()
print('\nWrote %s in file %s' % (name, writer_path))
print()
class CIFAR100Converter(CIFAR10Converter):
def __init__(self, data_dir):
"""Initialize the object for the CIFAR-100 dataset in `data_dir`"""
self.data_dir = data_dir
self.data = []
# Train
for name in ['train', 'test']:
batch = os.path.join(self.data_dir, name)
if not os.path.isfile(batch):
print('Warning: Missing test batch')
else:
self.data.append((name, [batch]))
# Labels
self.label_names = unpickle(os.path.join(self.data_dir, 'meta'))[b'coarse_label_names']
def convert(self, tfrecords_path, save_image_in_records=False):
"""Convert the dataset in TFRecords saved in the given `tfrecords_path`"""
for name, data in self.data:
writer_path = '%s_%s' % (tfrecords_path, name)
writer = tf.python_io.TFRecordWriter(writer_path)
print('\nLoad', name)
for i, item in enumerate(data):
print('\rBatch %d/%d' % (i + 1, len(data)), end='')
d = unpickle(item)
for img, label, coarse_label in zip(d[b'data'], d[b'fine_labels'], d[b'coarse_labels']):
class_name = self.label_names[coarse_label]
img = np.transpose(np.reshape(img, (3, 32, 32)), (1, 2, 0))
example = tf.train.Example(features=tf.train.Features(
feature={'image': bytes_feature([img.astype(np.uint8).tostring(order='C')]),
'class': int64_feature([label]),
'coarse_class': int64_feature([coarse_label]),
'coarse_class_str': bytes_feature([base64.b64encode(class_name)])}))
writer.write(example.SerializeToString())
writer.close()
print('\nWrote %s in file %s' % (name, writer_path))
print()
class CIFAR10Loader():
def __init__(self,
image_size=None,
verbose=False):
......@@ -87,4 +127,28 @@ class CIFAR10Loader():
parsed_features['class_str'] = tf.decode_base64(parsed_features['class_str'])
# Return
if self.verbose: print_records(parsed_features)
return parsed_features
class CIFAR100Loader(CIFAR10Loader):
def __init__(self, image_size=None, verbose=False):
super(CIFAR100Loader, self).__init__(image_size=image_size, verbose=verbose)
def parsing_fn(self, example_proto):
"""tf.data.Dataset parsing function."""
# Basic features
features = {'image' : tf.FixedLenFeature((), tf.string),
'class': tf.FixedLenFeature((), tf.int64),
'coarse_class': tf.FixedLenFeature((), tf.int64),
'coarse_class_str': tf.FixedLenFeature((), tf.string),
}
parsed_features = tf.parse_single_example(example_proto, features)
image = decode_raw_image(parsed_features['image'], (32, 32, 3), image_size=self.image_size)
parsed_features['image'] = tf.identity(image, name='image')
parsed_features['class'] = tf.to_int32(parsed_features['class'])
parsed_features['coarse_class'] = tf.to_int32(parsed_features['coarse_class'])
parsed_features['coarse_class_str'] = tf.decode_base64(parsed_features['coarse_class_str'])
# Return
if self.verbose: print_records(parsed_features)
return parsed_features
\ No newline at end of file
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment