sun397 / sun397.py
SaulLu's picture
fix image path
8c03acb
# Copyright 2020 The HuggingFace Datasets Authors.
#
# 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.
"""Sun397 loading script."""
import csv
import json
import os
from pathlib import Path
import datasets
_CITATION = """\
@INPROCEEDINGS{Xiao:2010,
author={J. {Xiao} and J. {Hays} and K. A. {Ehinger} and A. {Oliva} and A. {Torralba} },
booktitle={2010 IEEE Computer Society Conference on Computer Vision and Pattern Recognition},
title={SUN database: Large-scale scene recognition from abbey to zoo},
year={2010},
volume={},
number={},
pages={3485-3492},
keywords={computer vision;human factors;image classification;object recognition;visual databases;SUN database;large-scale scene recognition;abbey;zoo;scene categorization;computer vision;scene understanding research;scene category;object categorization;scene understanding database;state-of-the-art algorithms;human scene classification performance;finer-grained scene representation;Sun;Large-scale systems;Layout;Humans;Image databases;Computer vision;Anthropometry;Bridges;Legged locomotion;Spatial databases},
doi={10.1109/CVPR.2010.5539970},
ISSN={1063-6919},
month={June},}
"""
_DESCRIPTION = """\
Scene UNderstanding (SUN) database contains 899 categories. The number of images varies across categories, but there are at least 100 images per category, and 108,754 images in total. Images are in jpg, png, or gif format. The images provided here are for research purposes only.
"""
_HOMEPAGE = "https://vision.princeton.edu/projects/2010/SUN/"
_LICENSE = ""
_URLs = {
"images": "http://vision.princeton.edu/projects/2010/SUN/SUN397.tar.gz",
"partitions": "http://vision.princeton.edu/projects/2010/SUN/download/Partitions.zip",
}
_VERSION = datasets.Version("1.0.0")
_NAMES = [
"abbey",
"airplane_cabin",
"airport_terminal",
"alley",
"amphitheater",
"amusement_arcade",
"amusement_park",
"anechoic_chamber",
"apartment_building/outdoor",
"apse/indoor",
"aquarium",
"aqueduct",
"arch",
"archive",
"arrival_gate/outdoor",
"art_gallery",
"art_school",
"art_studio",
"assembly_line",
"athletic_field/outdoor",
"atrium/public",
"attic",
"auditorium",
"auto_factory",
"badlands",
"badminton_court/indoor",
"baggage_claim",
"bakery/shop",
"balcony/exterior",
"balcony/interior",
"ball_pit",
"ballroom",
"bamboo_forest",
"banquet_hall",
"bar",
"barn",
"barndoor",
"baseball_field",
"basement",
"basilica",
"basketball_court/outdoor",
"bathroom",
"batters_box",
"bayou",
"bazaar/indoor",
"bazaar/outdoor",
"beach",
"beauty_salon",
"bedroom",
"berth",
"biology_laboratory",
"bistro/indoor",
"boardwalk",
"boat_deck",
"boathouse",
"bookstore",
"booth/indoor",
"botanical_garden",
"bow_window/indoor",
"bow_window/outdoor",
"bowling_alley",
"boxing_ring",
"brewery/indoor",
"bridge",
"building_facade",
"bullring",
"burial_chamber",
"bus_interior",
"butchers_shop",
"butte",
"cabin/outdoor",
"cafeteria",
"campsite",
"campus",
"canal/natural",
"canal/urban",
"candy_store",
"canyon",
"car_interior/backseat",
"car_interior/frontseat",
"carrousel",
"casino/indoor",
"castle",
"catacomb",
"cathedral/indoor",
"cathedral/outdoor",
"cavern/indoor",
"cemetery",
"chalet",
"cheese_factory",
"chemistry_lab",
"chicken_coop/indoor",
"chicken_coop/outdoor",
"childs_room",
"church/indoor",
"church/outdoor",
"classroom",
"clean_room",
"cliff",
"cloister/indoor",
"closet",
"clothing_store",
"coast",
"cockpit",
"coffee_shop",
"computer_room",
"conference_center",
"conference_room",
"construction_site",
"control_room",
"control_tower/outdoor",
"corn_field",
"corral",
"corridor",
"cottage_garden",
"courthouse",
"courtroom",
"courtyard",
"covered_bridge/exterior",
"creek",
"crevasse",
"crosswalk",
"cubicle/office",
"dam",
"delicatessen",
"dentists_office",
"desert/sand",
"desert/vegetation",
"diner/indoor",
"diner/outdoor",
"dinette/home",
"dinette/vehicle",
"dining_car",
"dining_room",
"discotheque",
"dock",
"doorway/outdoor",
"dorm_room",
"driveway",
"driving_range/outdoor",
"drugstore",
"electrical_substation",
"elevator/door",
"elevator/interior",
"elevator_shaft",
"engine_room",
"escalator/indoor",
"excavation",
"factory/indoor",
"fairway",
"fastfood_restaurant",
"field/cultivated",
"field/wild",
"fire_escape",
"fire_station",
"firing_range/indoor",
"fishpond",
"florist_shop/indoor",
"food_court",
"forest/broadleaf",
"forest/needleleaf",
"forest_path",
"forest_road",
"formal_garden",
"fountain",
"galley",
"game_room",
"garage/indoor",
"garbage_dump",
"gas_station",
"gazebo/exterior",
"general_store/indoor",
"general_store/outdoor",
"gift_shop",
"golf_course",
"greenhouse/indoor",
"greenhouse/outdoor",
"gymnasium/indoor",
"hangar/indoor",
"hangar/outdoor",
"harbor",
"hayfield",
"heliport",
"herb_garden",
"highway",
"hill",
"home_office",
"hospital",
"hospital_room",
"hot_spring",
"hot_tub/outdoor",
"hotel/outdoor",
"hotel_room",
"house",
"hunting_lodge/outdoor",
"ice_cream_parlor",
"ice_floe",
"ice_shelf",
"ice_skating_rink/indoor",
"ice_skating_rink/outdoor",
"iceberg",
"igloo",
"industrial_area",
"inn/outdoor",
"islet",
"jacuzzi/indoor",
"jail/indoor",
"jail_cell",
"jewelry_shop",
"kasbah",
"kennel/indoor",
"kennel/outdoor",
"kindergarden_classroom",
"kitchen",
"kitchenette",
"labyrinth/outdoor",
"lake/natural",
"landfill",
"landing_deck",
"laundromat",
"lecture_room",
"library/indoor",
"library/outdoor",
"lido_deck/outdoor",
"lift_bridge",
"lighthouse",
"limousine_interior",
"living_room",
"lobby",
"lock_chamber",
"locker_room",
"mansion",
"manufactured_home",
"market/indoor",
"market/outdoor",
"marsh",
"martial_arts_gym",
"mausoleum",
"medina",
"moat/water",
"monastery/outdoor",
"mosque/indoor",
"mosque/outdoor",
"motel",
"mountain",
"mountain_snowy",
"movie_theater/indoor",
"museum/indoor",
"music_store",
"music_studio",
"nuclear_power_plant/outdoor",
"nursery",
"oast_house",
"observatory/outdoor",
"ocean",
"office",
"office_building",
"oil_refinery/outdoor",
"oilrig",
"operating_room",
"orchard",
"outhouse/outdoor",
"pagoda",
"palace",
"pantry",
"park",
"parking_garage/indoor",
"parking_garage/outdoor",
"parking_lot",
"parlor",
"pasture",
"patio",
"pavilion",
"pharmacy",
"phone_booth",
"physics_laboratory",
"picnic_area",
"pilothouse/indoor",
"planetarium/outdoor",
"playground",
"playroom",
"plaza",
"podium/indoor",
"podium/outdoor",
"pond",
"poolroom/establishment",
"poolroom/home",
"power_plant/outdoor",
"promenade_deck",
"pub/indoor",
"pulpit",
"putting_green",
"racecourse",
"raceway",
"raft",
"railroad_track",
"rainforest",
"reception",
"recreation_room",
"residential_neighborhood",
"restaurant",
"restaurant_kitchen",
"restaurant_patio",
"rice_paddy",
"riding_arena",
"river",
"rock_arch",
"rope_bridge",
"ruin",
"runway",
"sandbar",
"sandbox",
"sauna",
"schoolhouse",
"sea_cliff",
"server_room",
"shed",
"shoe_shop",
"shopfront",
"shopping_mall/indoor",
"shower",
"skatepark",
"ski_lodge",
"ski_resort",
"ski_slope",
"sky",
"skyscraper",
"slum",
"snowfield",
"squash_court",
"stable",
"stadium/baseball",
"stadium/football",
"stage/indoor",
"staircase",
"street",
"subway_interior",
"subway_station/platform",
"supermarket",
"sushi_bar",
"swamp",
"swimming_pool/indoor",
"swimming_pool/outdoor",
"synagogue/indoor",
"synagogue/outdoor",
"television_studio",
"temple/east_asia",
"temple/south_asia",
"tennis_court/indoor",
"tennis_court/outdoor",
"tent/outdoor",
"theater/indoor_procenium",
"theater/indoor_seats",
"thriftshop",
"throne_room",
"ticket_booth",
"toll_plaza",
"topiary_garden",
"tower",
"toyshop",
"track/outdoor",
"train_railway",
"train_station/platform",
"tree_farm",
"tree_house",
"trench",
"underwater/coral_reef",
"utility_room",
"valley",
"van_interior",
"vegetable_garden",
"veranda",
"veterinarians_office",
"viaduct",
"videostore",
"village",
"vineyard",
"volcano",
"volleyball_court/indoor",
"volleyball_court/outdoor",
"waiting_room",
"warehouse/indoor",
"water_tower",
"waterfall/block",
"waterfall/fan",
"waterfall/plunge",
"watering_hole",
"wave",
"wet_bar",
"wheat_field",
"wind_farm",
"windmill",
"wine_cellar/barrel_storage",
"wine_cellar/bottle_storage",
"wrestling_ring/indoor",
"yard",
"youth_hostel",
]
class Sun397Config(datasets.BuilderConfig):
def __init__(self, partition, **kwargs):
super(Sun397Config, self).__init__(**kwargs)
self.partition = partition
class Sun397Dataset(datasets.GeneratorBasedBuilder):
BUILDER_CONFIGS = [
Sun397Config(
name=f"standard-part{partition:d}-120k",
version=_VERSION,
partition=partition,
description=f"Train and test splits from the official partition number {partition:d}.",
)
for partition in range(1, 10 + 1)
]
# DEFAULT_CONFIG_NAME = "first_domain" # It's not mandatory to have a default configuration. Just use one if it make sense.
def _info(self):
features = datasets.Features(
{
"image": datasets.Image(),
"label": datasets.features.ClassLabel(names=_NAMES),
}
)
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=features,
homepage=_HOMEPAGE,
license=_LICENSE,
citation=_CITATION,
)
def _split_generators(self, dl_manager):
data_dir = dl_manager.download_and_extract(_URLs)
data_dir = {key: Path(path) for key, path in data_dir.items()}
data_dir["images"] = data_dir["images"] / "SUN397"
subset_images = self._get_partition_subsets_images(
data_dir["images"], data_dir["partitions"]
)
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={
"images_dir": data_dir["images"],
"subset_images": subset_images["tr"],
},
),
datasets.SplitGenerator(
name=datasets.Split.TEST,
gen_kwargs={
"images_dir": data_dir["images"],
"subset_images": subset_images["te"],
},
),
datasets.SplitGenerator(
name="other",
gen_kwargs={
"images_dir": data_dir["images"],
"subset_images": subset_images["va"],
},
),
]
def _load_image_set_from_file(self, filepath):
with open(filepath, mode="r") as f:
return set([line.strip() for line in f])
def _get_all_image_paths(self, images_dir):
return [
str(path)[len(str(images_dir)) :] for path in images_dir.rglob("sun_*.jpg")
]
def _get_partition_subsets_images(self, images_dir, partitions_dir):
# Get the ID of all images in the dataset.
all_images = set(self._get_all_image_paths(images_dir))
# Load the images in the training/test split of this partition.
partition = self.config.partition
filenames = {
"tr": f"Training_{partition:02d}.txt",
"te": f"Testing_{partition:02d}.txt",
}
splits_sets = {}
for split, filename in filenames.items():
filepath = partitions_dir / filename
splits_sets[split] = self._load_image_set_from_file(filepath)
# Put the remaining images in the dataset into the "validation" split.
splits_sets["va"] = all_images - (splits_sets["tr"] | splits_sets["te"])
return splits_sets
def _generate_examples(self, images_dir, subset_images):
for image_name in subset_images:
label = "/".join(image_name.split("/")[2:-1])
image_path = os.path.join(str(images_dir), *image_name.split("/"))
record = {"image": str(image_path), "label": label}
yield image_name, record