MAMe / MAMe.py
davanstrien's picture
davanstrien HF Staff
fix
89c644a
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# 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.
"""Dataset for dating historical color images"""
from pathlib import Path
import datasets
import csv
import os
_CITATION = """@inproceedings{10.1007/978-3-642-33783-3_36,
author = {Palermo, Frank and Hays, James and Efros, Alexei A.},
title = {Dating Historical Color Images},
year = {2012},
isbn = {9783642337826},
publisher = {Springer-Verlag},
address = {Berlin, Heidelberg},
url = {https://doi.org/10.1007/978-3-642-33783-3_36},
doi = {10.1007/978-3-642-33783-3_36},
abstract = {We introduce the task of automatically estimating the age of historical color photographs. We suggest features which attempt to capture temporally discriminative information based on the evolution of color imaging processes over time and evaluate the performance of both these novel features and existing features commonly utilized in other problem domains on a novel historical image data set. For the challenging classification task of sorting historical color images into the decade during which they were photographed, we demonstrate significantly greater accuracy than that shown by untrained humans on the same data set. Additionally, we apply the concept of data-driven camera response function estimation to historical color imagery, demonstrating its relevance to both the age estimation task and the popular application of imitating the appearance of vintage color photography.},
booktitle = {Proceedings of the 12th European Conference on Computer Vision - Volume Part VI},
pages = {499–512},
numpages = {14},
location = {Florence, Italy},
series = {ECCV'12}
}
"""
_DESCRIPTION = """\
This dataset contains color photographs taken between the 1930s and 1970s.
The goal of the dataset is to develop methods for dating historical color photographs
"""
_HOMEPAGE = "http://graphics.cs.cmu.edu/projects/historicalColor/"
_URLS = {
"metadata": "https://storage.hpai.bsc.es/mame-dataset/MAMe_metadata.zip",
"images": "https://storage.hpai.bsc.es/mame-dataset/MAMe_data_256.zip",
"full_images": "https://storage.hpai.bsc.es/mame-dataset/MAMe_data.zip",
}
def generate_mapping_dict(csv_file):
with open(csv_file) as f:
mapping_dict = {}
dictreater = csv.DictReader(f)
for row in dictreater:
split = row["Subset"]
image_file = row["Image file"]
del row["Image file"]
del row["Subset"]
# add row to subset dictionary
row_dict = {image_file: row}
if split not in mapping_dict:
mapping_dict[split] = row_dict
else:
mapping_dict[split].update(row_dict)
return mapping_dict
class MAMeConfig(datasets.BuilderConfig):
"""TODO"""
def __init__(self, image_data_url, **kwargs):
"""TODO"""
super().__init__(version=datasets.Version("1.0.2"), **kwargs)
self.image_data_url = image_data_url
class MAMe(datasets.GeneratorBasedBuilder):
"""TODO"""
VERSION = datasets.Version("1.1.0")
BUILDER_CONFIGS = [
MAMeConfig(name="256", image_data_url=_URLS["images"]),
MAMeConfig(name="full", image_data_url=_URLS["full_images"]),
]
DEFAULT_CONFIG_NAME = "256"
def _info(self):
features = datasets.Features(
{
"image": datasets.Image(),
"label": datasets.ClassLabel(
names=[
"Albumen photograph",
"Bronze",
"Ceramic",
"Clay",
"Engraving",
"Etching",
"Faience",
"Glass",
"Gold",
"Graphite",
"Hand-colored engraving",
"Hand-colored etching",
"Iron",
"Ivory",
"Limestone",
"Lithograph",
"Marble",
"Oil on canvas",
"Pen and brown ink",
"Polychromed wood",
"Porcelain",
"Silk and metal thread",
"Silver",
"Steel",
"Wood",
"Wood engraving",
"Woodblock",
"Woodcut",
"Woven fabric",
]
),
"Museum": datasets.Value("string"),
"Museum-based instance ID": datasets.Value("string"),
"Width": datasets.Value("float32"),
"Height": datasets.Value("float32"),
"Product size": datasets.Value("float32"),
"Aspect ratio": datasets.Value("float32"),
}
)
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=features,
homepage=_HOMEPAGE,
citation=_CITATION,
)
def _split_generators(self, dl_manager):
metadata = dl_manager.download_and_extract(_URLS["metadata"])
metadata = os.path.join(metadata, "MAMe_dataset.csv")
images = dl_manager.download_and_extract(self.config.image_data_url)
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={
"metadata": metadata,
"images": images,
"split": "train",
},
),
datasets.SplitGenerator(
name=datasets.Split.VALIDATION,
gen_kwargs={
"metadata": metadata,
"images": images,
"split": "val",
},
),
datasets.SplitGenerator(
name=datasets.Split.TEST,
gen_kwargs={
"metadata": metadata,
"images": images,
"split": "test",
},
),
]
def _generate_examples(self, metadata, images, split):
if self.config.name == 'full':
from PIL import Image # to prevent decompression bomb warnings
Image.MAX_IMAGE_PIXELS = None
mapping = generate_mapping_dict(metadata)
subset = mapping[split]
for i, kv in enumerate(subset.items()):
k, v = kv
if self.config.name == "256":
im = f"{images}/data_256/{k}"
if self.config.name == "full":
im = f"{images}/data/{k}"
v["label"] = v["Medium"]
del v["Medium"]
v["image"] = im
yield i, v