Datasets:
Tasks:
Image Segmentation
Sub-tasks:
instance-segmentation
Languages:
English
Size:
10K<n<100K
ArXiv:
Tags:
scene-parsing
License:
Update phao_dataset.py
Browse files- phao_dataset.py +305 -305
phao_dataset.py
CHANGED
@@ -1,306 +1,306 @@
|
|
1 |
-
# Copyright 2022 The HuggingFace Datasets Authors and the current dataset script contributor.
|
2 |
-
#
|
3 |
-
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
-
# you may not use this file except in compliance with the License.
|
5 |
-
# You may obtain a copy of the License at
|
6 |
-
#
|
7 |
-
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
-
#
|
9 |
-
# Unless required by applicable law or agreed to in writing, software
|
10 |
-
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
-
# See the License for the specific language governing permissions and
|
13 |
-
# limitations under the License.
|
14 |
-
"""MIT Scene Parsing Benchmark."""
|
15 |
-
|
16 |
-
|
17 |
-
import os
|
18 |
-
|
19 |
-
import pandas as pd
|
20 |
-
|
21 |
-
import datasets
|
22 |
-
|
23 |
-
|
24 |
-
_CITATION = """\
|
25 |
-
@inproceedings{zhou2017scene,
|
26 |
-
title={Scene Parsing through ADE20K Dataset},
|
27 |
-
author={Zhou, Bolei and Zhao, Hang and Puig, Xavier and Fidler, Sanja and Barriuso, Adela and Torralba, Antonio},
|
28 |
-
booktitle={Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition},
|
29 |
-
year={2017}
|
30 |
-
}
|
31 |
-
|
32 |
-
@article{zhou2016semantic,
|
33 |
-
title={Semantic understanding of scenes through the ade20k dataset},
|
34 |
-
author={Zhou, Bolei and Zhao, Hang and Puig, Xavier and Fidler, Sanja and Barriuso, Adela and Torralba, Antonio},
|
35 |
-
journal={arXiv preprint arXiv:1608.05442},
|
36 |
-
year={2016}
|
37 |
-
}
|
38 |
-
"""
|
39 |
-
|
40 |
-
_DESCRIPTION = """\
|
41 |
-
Scene parsing is to segment and parse an image into different image regions associated with semantic categories, such as sky, road, person, and bed.
|
42 |
-
MIT Scene Parsing Benchmark (SceneParse150) provides a standard training and evaluation platform for the algorithms of scene parsing.
|
43 |
-
The data for this benchmark comes from ADE20K Dataset which contains more than 20K scene-centric images exhaustively annotated with objects and object parts.
|
44 |
-
Specifically, the benchmark is divided into 20K images for training, 2K images for validation, and another batch of held-out images for testing.
|
45 |
-
There are totally 150 semantic categories included for evaluation, which include stuffs like sky, road, grass, and discrete objects like person, car, bed.
|
46 |
-
Note that there are non-uniform distribution of objects occuring in the images, mimicking a more natural object occurrence in daily scene.
|
47 |
-
"""
|
48 |
-
|
49 |
-
_HOMEPAGE = "http://sceneparsing.csail.mit.edu/"
|
50 |
-
|
51 |
-
_LICENSE = "BSD 3-Clause License"
|
52 |
-
|
53 |
-
_URLS = {
|
54 |
-
"scene_parsing": {
|
55 |
-
"train/val": "https://
|
56 |
-
"test": "https://
|
57 |
-
},
|
58 |
-
"instance_segmentation": {
|
59 |
-
"images": "https://
|
60 |
-
"annotations": "https://
|
61 |
-
"test": "https://
|
62 |
-
},
|
63 |
-
}
|
64 |
-
|
65 |
-
_SCENE_CATEGORIES = """\
|
66 |
-
airport_terminal art_gallery badlands ball_pit bathroom beach bedroom booth_indoor botanical_garden bridge bullring
|
67 |
-
bus_interior butte canyon casino_outdoor castle church_outdoor closet coast conference_room construction_site corral
|
68 |
-
corridor crosswalk day_care_center sand elevator_interior escalator_indoor forest_road gangplank gas_station
|
69 |
-
golf_course gymnasium_indoor harbor hayfield heath hoodoo house hunting_lodge_outdoor ice_shelf joss_house kiosk_indoor
|
70 |
-
kitchen landfill library_indoor lido_deck_outdoor living_room locker_room market_outdoor mountain_snowy office orchard
|
71 |
-
arbor bookshelf mews nook preserve traffic_island palace palace_hall pantry patio phone_booth establishment
|
72 |
-
poolroom_home quonset_hut_outdoor rice_paddy sandbox shopfront skyscraper stone_circle subway_interior platform
|
73 |
-
supermarket swimming_pool_outdoor television_studio indoor_procenium train_railway coral_reef viaduct wave wind_farm
|
74 |
-
bottle_storage abbey access_road air_base airfield airlock airplane_cabin airport entrance airport_ticket_counter
|
75 |
-
alcove alley amphitheater amusement_arcade amusement_park anechoic_chamber apartment_building_outdoor apse_indoor
|
76 |
-
apse_outdoor aquarium aquatic_theater aqueduct arcade arch archaelogical_excavation archive basketball football hockey
|
77 |
-
performance rodeo soccer armory army_base arrival_gate_indoor arrival_gate_outdoor art_school art_studio artists_loft
|
78 |
-
assembly_line athletic_field_indoor athletic_field_outdoor atrium_home atrium_public attic auditorium auto_factory
|
79 |
-
auto_mechanics_indoor auto_mechanics_outdoor auto_racing_paddock auto_showroom backstage backstairs
|
80 |
-
badminton_court_indoor badminton_court_outdoor baggage_claim shop exterior balcony_interior ballroom bamboo_forest
|
81 |
-
bank_indoor bank_outdoor bank_vault banquet_hall baptistry_indoor baptistry_outdoor bar barbershop barn barndoor
|
82 |
-
barnyard barrack baseball_field basement basilica basketball_court_indoor basketball_court_outdoor bathhouse
|
83 |
-
batters_box batting_cage_indoor batting_cage_outdoor battlement bayou bazaar_indoor bazaar_outdoor beach_house
|
84 |
-
beauty_salon bedchamber beer_garden beer_hall belfry bell_foundry berth berth_deck betting_shop bicycle_racks bindery
|
85 |
-
biology_laboratory bistro_indoor bistro_outdoor bleachers_indoor bleachers_outdoor boardwalk boat_deck boathouse bog
|
86 |
-
bomb_shelter_indoor bookbindery bookstore bow_window_indoor bow_window_outdoor bowling_alley box_seat boxing_ring
|
87 |
-
breakroom brewery_indoor brewery_outdoor brickyard_indoor brickyard_outdoor building_complex building_facade bullpen
|
88 |
-
burial_chamber bus_depot_indoor bus_depot_outdoor bus_shelter bus_station_indoor bus_station_outdoor butchers_shop
|
89 |
-
cabana cabin_indoor cabin_outdoor cafeteria call_center campsite campus natural urban candy_store canteen
|
90 |
-
car_dealership backseat frontseat caravansary cardroom cargo_container_interior airplane boat freestanding
|
91 |
-
carport_indoor carport_outdoor carrousel casino_indoor catacomb cathedral_indoor cathedral_outdoor catwalk
|
92 |
-
cavern_indoor cavern_outdoor cemetery chalet chaparral chapel checkout_counter cheese_factory chemical_plant
|
93 |
-
chemistry_lab chicken_coop_indoor chicken_coop_outdoor chicken_farm_indoor chicken_farm_outdoor childs_room
|
94 |
-
choir_loft_interior church_indoor circus_tent_indoor circus_tent_outdoor city classroom clean_room cliff booth room
|
95 |
-
clock_tower_indoor cloister_indoor cloister_outdoor clothing_store coast_road cockpit coffee_shop computer_room
|
96 |
-
conference_center conference_hall confessional control_room control_tower_indoor control_tower_outdoor
|
97 |
-
convenience_store_indoor convenience_store_outdoor corn_field cottage cottage_garden courthouse courtroom courtyard
|
98 |
-
covered_bridge_interior crawl_space creek crevasse library cybercafe dacha dairy_indoor dairy_outdoor dam dance_school
|
99 |
-
darkroom delicatessen dentists_office department_store departure_lounge vegetation desert_road diner_indoor
|
100 |
-
diner_outdoor dinette_home vehicle dining_car dining_hall dining_room dirt_track discotheque distillery ditch dock
|
101 |
-
dolmen donjon doorway_indoor doorway_outdoor dorm_room downtown drainage_ditch dress_shop dressing_room drill_rig
|
102 |
-
driveway driving_range_indoor driving_range_outdoor drugstore dry_dock dugout earth_fissure editing_room
|
103 |
-
electrical_substation elevated_catwalk door freight_elevator elevator_lobby elevator_shaft embankment embassy
|
104 |
-
engine_room entrance_hall escalator_outdoor escarpment estuary excavation exhibition_hall fabric_store factory_indoor
|
105 |
-
factory_outdoor fairway farm fastfood_restaurant fence cargo_deck ferryboat_indoor passenger_deck cultivated wild
|
106 |
-
field_road fire_escape fire_station firing_range_indoor firing_range_outdoor fish_farm fishmarket fishpond
|
107 |
-
fitting_room_interior fjord flea_market_indoor flea_market_outdoor floating_dry_dock flood florist_shop_indoor
|
108 |
-
florist_shop_outdoor fly_bridge food_court football_field broadleaf needleleaf forest_fire forest_path formal_garden
|
109 |
-
fort fortress foundry_indoor foundry_outdoor fountain freeway funeral_chapel funeral_home furnace_room galley game_room
|
110 |
-
garage_indoor garage_outdoor garbage_dump gasworks gate gatehouse gazebo_interior general_store_indoor
|
111 |
-
general_store_outdoor geodesic_dome_indoor geodesic_dome_outdoor ghost_town gift_shop glacier glade gorge granary
|
112 |
-
great_hall greengrocery greenhouse_indoor greenhouse_outdoor grotto guardhouse gulch gun_deck_indoor gun_deck_outdoor
|
113 |
-
gun_store hacienda hallway handball_court hangar_indoor hangar_outdoor hardware_store hat_shop hatchery hayloft hearth
|
114 |
-
hedge_maze hedgerow heliport herb_garden highway hill home_office home_theater hospital hospital_room hot_spring
|
115 |
-
hot_tub_indoor hot_tub_outdoor hotel_outdoor hotel_breakfast_area hotel_room hunting_lodge_indoor hut ice_cream_parlor
|
116 |
-
ice_floe ice_skating_rink_indoor ice_skating_rink_outdoor iceberg igloo imaret incinerator_indoor incinerator_outdoor
|
117 |
-
industrial_area industrial_park inn_indoor inn_outdoor irrigation_ditch islet jacuzzi_indoor jacuzzi_outdoor
|
118 |
-
jail_indoor jail_outdoor jail_cell japanese_garden jetty jewelry_shop junk_pile junkyard jury_box kasbah kennel_indoor
|
119 |
-
kennel_outdoor kindergarden_classroom kiosk_outdoor kitchenette lab_classroom labyrinth_indoor labyrinth_outdoor lagoon
|
120 |
-
artificial landing landing_deck laundromat lava_flow lavatory lawn lean-to lecture_room legislative_chamber levee
|
121 |
-
library_outdoor lido_deck_indoor lift_bridge lighthouse limousine_interior liquor_store_indoor liquor_store_outdoor
|
122 |
-
loading_dock lobby lock_chamber loft lookout_station_indoor lookout_station_outdoor lumberyard_indoor
|
123 |
-
lumberyard_outdoor machine_shop manhole mansion manufactured_home market_indoor marsh martial_arts_gym mastaba
|
124 |
-
maternity_ward mausoleum medina menhir mesa mess_hall mezzanine military_hospital military_hut military_tent mine
|
125 |
-
mineshaft mini_golf_course_indoor mini_golf_course_outdoor mission dry water mobile_home monastery_indoor
|
126 |
-
monastery_outdoor moon_bounce moor morgue mosque_indoor mosque_outdoor motel mountain mountain_path mountain_road
|
127 |
-
movie_theater_indoor movie_theater_outdoor mudflat museum_indoor museum_outdoor music_store music_studio misc
|
128 |
-
natural_history_museum naval_base newsroom newsstand_indoor newsstand_outdoor nightclub nuclear_power_plant_indoor
|
129 |
-
nuclear_power_plant_outdoor nunnery nursery nursing_home oasis oast_house observatory_indoor observatory_outdoor
|
130 |
-
observatory_post ocean office_building office_cubicles oil_refinery_indoor oil_refinery_outdoor oilrig operating_room
|
131 |
-
optician organ_loft_interior orlop_deck ossuary outcropping outhouse_indoor outhouse_outdoor overpass oyster_bar
|
132 |
-
oyster_farm acropolis aircraft_carrier_object amphitheater_indoor archipelago questionable assembly_hall assembly_plant
|
133 |
-
awning_deck back_porch backdrop backroom backstage_outdoor backstairs_indoor backwoods ballet balustrade barbeque
|
134 |
-
basin_outdoor bath_indoor bath_outdoor bathhouse_outdoor battlefield bay booth_outdoor bottomland breakfast_table
|
135 |
-
bric-a-brac brooklet bubble_chamber buffet bulkhead bunk_bed bypass byroad cabin_cruiser cargo_helicopter cellar
|
136 |
-
chair_lift cocktail_lounge corner country_house country_road customhouse dance_floor deck-house_boat_deck_house
|
137 |
-
deck-house_deck_house dining_area diving_board embrasure entranceway_indoor entranceway_outdoor entryway_outdoor
|
138 |
-
estaminet farm_building farmhouse feed_bunk field_house field_tent_indoor field_tent_outdoor fire_trench fireplace
|
139 |
-
flashflood flatlet floating_dock flood_plain flowerbed flume_indoor flying_buttress foothill forecourt foreshore
|
140 |
-
front_porch garden gas_well glen grape_arbor grove guardroom guesthouse gymnasium_outdoor head_shop hen_yard hillock
|
141 |
-
housing_estate housing_project howdah inlet insane_asylum outside juke_joint jungle kraal laboratorywet landing_strip
|
142 |
-
layby lean-to_tent loge loggia_outdoor lower_deck luggage_van mansard meadow meat_house megalith mens_store_outdoor
|
143 |
-
mental_institution_indoor mental_institution_outdoor military_headquarters millpond millrace natural_spring
|
144 |
-
nursing_home_outdoor observation_station open-hearth_furnace operating_table outbuilding palestra parkway patio_indoor
|
145 |
-
pavement pawnshop_outdoor pinetum piste_road pizzeria_outdoor powder_room pumping_station reception_room rest_stop
|
146 |
-
retaining_wall rift_valley road rock_garden rotisserie safari_park salon saloon sanatorium science_laboratory scrubland
|
147 |
-
scullery seaside semidesert shelter shelter_deck shelter_tent shore shrubbery sidewalk snack_bar snowbank stage_set
|
148 |
-
stall stateroom store streetcar_track student_center study_hall sugar_refinery sunroom supply_chamber t-bar_lift
|
149 |
-
tannery teahouse threshing_floor ticket_window_indoor tidal_basin tidal_river tiltyard tollgate tomb tract_housing
|
150 |
-
trellis truck_stop upper_balcony vestibule vinery walkway war_room washroom water_fountain water_gate waterscape
|
151 |
-
waterway wetland widows_walk_indoor windstorm packaging_plant pagoda paper_mill park parking_garage_indoor
|
152 |
-
parking_garage_outdoor parking_lot parlor particle_accelerator party_tent_indoor party_tent_outdoor pasture pavilion
|
153 |
-
pawnshop pedestrian_overpass_indoor penalty_box pet_shop pharmacy physics_laboratory piano_store picnic_area pier
|
154 |
-
pig_farm pilothouse_indoor pilothouse_outdoor pitchers_mound pizzeria planetarium_indoor planetarium_outdoor
|
155 |
-
plantation_house playground playroom plaza podium_indoor podium_outdoor police_station pond pontoon_bridge poop_deck
|
156 |
-
porch portico portrait_studio postern power_plant_outdoor print_shop priory promenade promenade_deck pub_indoor
|
157 |
-
pub_outdoor pulpit putting_green quadrangle quicksand quonset_hut_indoor racecourse raceway raft railroad_track
|
158 |
-
railway_yard rainforest ramp ranch ranch_house reading_room reception recreation_room rectory recycling_plant_indoor
|
159 |
-
refectory repair_shop residential_neighborhood resort rest_area restaurant restaurant_kitchen restaurant_patio
|
160 |
-
restroom_indoor restroom_outdoor revolving_door riding_arena river road_cut rock_arch roller_skating_rink_indoor
|
161 |
-
roller_skating_rink_outdoor rolling_mill roof roof_garden root_cellar rope_bridge roundabout roundhouse rubble ruin
|
162 |
-
runway sacristy salt_plain sand_trap sandbar sauna savanna sawmill schoolhouse schoolyard science_museum scriptorium
|
163 |
-
sea_cliff seawall security_check_point server_room sewer sewing_room shed shipping_room shipyard_outdoor shoe_shop
|
164 |
-
shopping_mall_indoor shopping_mall_outdoor shower shower_room shrine signal_box sinkhole ski_jump ski_lodge ski_resort
|
165 |
-
ski_slope sky skywalk_indoor skywalk_outdoor slum snowfield massage_room mineral_bath spillway sporting_goods_store
|
166 |
-
squash_court stable baseball stadium_outdoor stage_indoor stage_outdoor staircase starting_gate steam_plant_outdoor
|
167 |
-
steel_mill_indoor storage_room storm_cellar street strip_mall strip_mine student_residence submarine_interior sun_deck
|
168 |
-
sushi_bar swamp swimming_hole swimming_pool_indoor synagogue_indoor synagogue_outdoor taxistand taxiway tea_garden
|
169 |
-
tearoom teashop television_room east_asia mesoamerican south_asia western tennis_court_indoor tennis_court_outdoor
|
170 |
-
tent_outdoor terrace_farm indoor_round indoor_seats theater_outdoor thriftshop throne_room ticket_booth
|
171 |
-
tobacco_shop_indoor toll_plaza tollbooth topiary_garden tower town_house toyshop track_outdoor trading_floor
|
172 |
-
trailer_park train_interior train_station_outdoor station tree_farm tree_house trench trestle_bridge tundra rail_indoor
|
173 |
-
rail_outdoor road_indoor road_outdoor turkish_bath ocean_deep ocean_shallow utility_room valley van_interior
|
174 |
-
vegetable_garden velodrome_indoor velodrome_outdoor ventilation_shaft veranda vestry veterinarians_office videostore
|
175 |
-
village vineyard volcano volleyball_court_indoor volleyball_court_outdoor voting_booth waiting_room walk_in_freezer
|
176 |
-
warehouse_indoor warehouse_outdoor washhouse_indoor washhouse_outdoor watchtower water_mill water_park water_tower
|
177 |
-
water_treatment_plant_indoor water_treatment_plant_outdoor block cascade cataract fan plunge watering_hole weighbridge
|
178 |
-
wet_bar wharf wheat_field whispering_gallery widows_walk_interior windmill window_seat barrel_storage winery
|
179 |
-
witness_stand woodland workroom workshop wrestling_ring_indoor wrestling_ring_outdoor yard youth_hostel zen_garden
|
180 |
-
ziggurat zoo forklift hollow hutment pueblo vat perfume_shop steel_mill_outdoor orchestra_pit bridle_path lyceum
|
181 |
-
one-way_street parade_ground pump_room recycling_plant_outdoor chuck_wagon
|
182 |
-
"""
|
183 |
-
_SCENE_CATEGORIES = _SCENE_CATEGORIES.strip().split()
|
184 |
-
|
185 |
-
|
186 |
-
class SceneParse150(datasets.GeneratorBasedBuilder):
|
187 |
-
"""MIT Scene Parsing Benchmark dataset."""
|
188 |
-
|
189 |
-
VERSION = datasets.Version("1.0.0")
|
190 |
-
|
191 |
-
BUILDER_CONFIGS = [
|
192 |
-
datasets.BuilderConfig(name="scene_parsing", version=VERSION, description="The scene parsing variant."),
|
193 |
-
datasets.BuilderConfig(
|
194 |
-
name="instance_segmentation", version=VERSION, description="The instance segmentation variant."
|
195 |
-
),
|
196 |
-
]
|
197 |
-
|
198 |
-
DEFAULT_CONFIG_NAME = "scene_parsing"
|
199 |
-
|
200 |
-
def _info(self):
|
201 |
-
if self.config.name == "scene_parsing":
|
202 |
-
features = datasets.Features(
|
203 |
-
{
|
204 |
-
"image": datasets.Image(),
|
205 |
-
"annotation": datasets.Image(),
|
206 |
-
"scene_category": datasets.ClassLabel(names=_SCENE_CATEGORIES),
|
207 |
-
}
|
208 |
-
)
|
209 |
-
else:
|
210 |
-
features = datasets.Features(
|
211 |
-
{
|
212 |
-
"image": datasets.Image(),
|
213 |
-
"annotation": datasets.Image(),
|
214 |
-
}
|
215 |
-
)
|
216 |
-
return datasets.DatasetInfo(
|
217 |
-
description=_DESCRIPTION,
|
218 |
-
features=features,
|
219 |
-
homepage=_HOMEPAGE,
|
220 |
-
license=_LICENSE,
|
221 |
-
citation=_CITATION,
|
222 |
-
)
|
223 |
-
|
224 |
-
def _split_generators(self, dl_manager):
|
225 |
-
urls = _URLS[self.config.name]
|
226 |
-
|
227 |
-
if self.config.name == "scene_parsing":
|
228 |
-
data_dirs = dl_manager.download_and_extract(urls)
|
229 |
-
train_data = val_data = os.path.join(data_dirs["train/val"], "ADEChallengeData2016")
|
230 |
-
test_data = os.path.join(data_dirs["test"], "release_test")
|
231 |
-
else:
|
232 |
-
data_dirs = dl_manager.download(urls)
|
233 |
-
train_data = dl_manager.iter_archive(data_dirs["images"]), dl_manager.iter_archive(
|
234 |
-
data_dirs["annotations"]
|
235 |
-
)
|
236 |
-
val_data = dl_manager.iter_archive(data_dirs["images"]), dl_manager.iter_archive(data_dirs["annotations"])
|
237 |
-
test_data = dl_manager.iter_archive(data_dirs["test"])
|
238 |
-
return [
|
239 |
-
datasets.SplitGenerator(
|
240 |
-
name=datasets.Split.TRAIN,
|
241 |
-
gen_kwargs={
|
242 |
-
"data": train_data,
|
243 |
-
"split": "training",
|
244 |
-
},
|
245 |
-
),
|
246 |
-
datasets.SplitGenerator(
|
247 |
-
name=datasets.Split.TEST,
|
248 |
-
gen_kwargs={"data": test_data, "split": "testing"},
|
249 |
-
),
|
250 |
-
datasets.SplitGenerator(
|
251 |
-
name=datasets.Split.VALIDATION,
|
252 |
-
gen_kwargs={
|
253 |
-
"data": val_data,
|
254 |
-
"split": "validation",
|
255 |
-
},
|
256 |
-
),
|
257 |
-
]
|
258 |
-
|
259 |
-
def _generate_examples(self, data, split):
|
260 |
-
if self.config.name == "scene_parsing":
|
261 |
-
if split == "testing":
|
262 |
-
image_dir = os.path.join(data, split)
|
263 |
-
for idx, image_file in enumerate(os.listdir(image_dir)):
|
264 |
-
yield idx, {
|
265 |
-
"image": os.path.join(image_dir, image_file),
|
266 |
-
"annotation": None,
|
267 |
-
"scene_category": None,
|
268 |
-
}
|
269 |
-
else:
|
270 |
-
image_id2cat = pd.read_csv(
|
271 |
-
os.path.join(data, "sceneCategories.txt"), sep=" ", names=["image_id", "scene_category"]
|
272 |
-
)
|
273 |
-
image_id2cat = image_id2cat.set_index("image_id")
|
274 |
-
images_dir = os.path.join(data, "images", split)
|
275 |
-
annotations_dir = os.path.join(data, "annotations", split)
|
276 |
-
for idx, image_file in enumerate(os.listdir(images_dir)):
|
277 |
-
image_id = image_file.split(".")[0]
|
278 |
-
yield idx, {
|
279 |
-
"image": os.path.join(images_dir, image_file),
|
280 |
-
"annotation": os.path.join(annotations_dir, image_id + ".
|
281 |
-
"scene_category": image_id2cat.loc[image_id, "scene_category"],
|
282 |
-
}
|
283 |
-
else:
|
284 |
-
if split == "testing":
|
285 |
-
for idx, (path, file) in enumerate(data):
|
286 |
-
if path.endswith(".jpg"):
|
287 |
-
yield idx, {
|
288 |
-
"image": {"path": path, "bytes": file.read()},
|
289 |
-
"annotation": None,
|
290 |
-
}
|
291 |
-
else:
|
292 |
-
images, annotations = data
|
293 |
-
image_id2annot = {}
|
294 |
-
# loads the annotations for the split into RAM (less than 100 MB) to support streaming
|
295 |
-
for path_annot, file_annot in annotations:
|
296 |
-
if split in path_annot and path_annot.endswith(".
|
297 |
-
image_id = os.path.basename(path_annot).split(".")[0]
|
298 |
-
image_id2annot[image_id] = (path_annot, file_annot.read())
|
299 |
-
for idx, (path_img, file_img) in enumerate(images):
|
300 |
-
if split in path_img and path_img.endswith(".jpg"):
|
301 |
-
image_id = os.path.basename(path_img).split(".")[0]
|
302 |
-
path_annot, bytes_annot = image_id2annot[image_id]
|
303 |
-
yield idx, {
|
304 |
-
"image": {"path": path_img, "bytes": file_img.read()},
|
305 |
-
"annotation": {"path": path_annot, "bytes": bytes_annot},
|
306 |
}
|
|
|
1 |
+
# Copyright 2022 The HuggingFace Datasets Authors and the current dataset script contributor.
|
2 |
+
#
|
3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
+
# you may not use this file except in compliance with the License.
|
5 |
+
# You may obtain a copy of the License at
|
6 |
+
#
|
7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
+
#
|
9 |
+
# Unless required by applicable law or agreed to in writing, software
|
10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
+
# See the License for the specific language governing permissions and
|
13 |
+
# limitations under the License.
|
14 |
+
"""MIT Scene Parsing Benchmark."""
|
15 |
+
|
16 |
+
|
17 |
+
import os
|
18 |
+
|
19 |
+
import pandas as pd
|
20 |
+
|
21 |
+
import datasets
|
22 |
+
|
23 |
+
|
24 |
+
_CITATION = """\
|
25 |
+
@inproceedings{zhou2017scene,
|
26 |
+
title={Scene Parsing through ADE20K Dataset},
|
27 |
+
author={Zhou, Bolei and Zhao, Hang and Puig, Xavier and Fidler, Sanja and Barriuso, Adela and Torralba, Antonio},
|
28 |
+
booktitle={Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition},
|
29 |
+
year={2017}
|
30 |
+
}
|
31 |
+
|
32 |
+
@article{zhou2016semantic,
|
33 |
+
title={Semantic understanding of scenes through the ade20k dataset},
|
34 |
+
author={Zhou, Bolei and Zhao, Hang and Puig, Xavier and Fidler, Sanja and Barriuso, Adela and Torralba, Antonio},
|
35 |
+
journal={arXiv preprint arXiv:1608.05442},
|
36 |
+
year={2016}
|
37 |
+
}
|
38 |
+
"""
|
39 |
+
|
40 |
+
_DESCRIPTION = """\
|
41 |
+
Scene parsing is to segment and parse an image into different image regions associated with semantic categories, such as sky, road, person, and bed.
|
42 |
+
MIT Scene Parsing Benchmark (SceneParse150) provides a standard training and evaluation platform for the algorithms of scene parsing.
|
43 |
+
The data for this benchmark comes from ADE20K Dataset which contains more than 20K scene-centric images exhaustively annotated with objects and object parts.
|
44 |
+
Specifically, the benchmark is divided into 20K images for training, 2K images for validation, and another batch of held-out images for testing.
|
45 |
+
There are totally 150 semantic categories included for evaluation, which include stuffs like sky, road, grass, and discrete objects like person, car, bed.
|
46 |
+
Note that there are non-uniform distribution of objects occuring in the images, mimicking a more natural object occurrence in daily scene.
|
47 |
+
"""
|
48 |
+
|
49 |
+
_HOMEPAGE = "http://sceneparsing.csail.mit.edu/"
|
50 |
+
|
51 |
+
_LICENSE = "BSD 3-Clause License"
|
52 |
+
|
53 |
+
_URLS = {
|
54 |
+
"scene_parsing": {
|
55 |
+
"train/val": "https://phaotestjson.s3.ap-southeast-2.amazonaws.com/LabelPhao.zip",
|
56 |
+
"test": "https://phaotestjson.s3.ap-southeast-2.amazonaws.com/release_test.zip",
|
57 |
+
},
|
58 |
+
"instance_segmentation": {
|
59 |
+
"images": "https://phaotestjson.s3.ap-southeast-2.amazonaws.com/images.zip",
|
60 |
+
"annotations": "https://phaotestjson.s3.ap-southeast-2.amazonaws.com/annotations_instance.zip",
|
61 |
+
"test": "https://phaotestjson.s3.ap-southeast-2.amazonaws.com/testing.zip",
|
62 |
+
},
|
63 |
+
}
|
64 |
+
|
65 |
+
_SCENE_CATEGORIES = """\
|
66 |
+
airport_terminal art_gallery badlands ball_pit bathroom beach bedroom booth_indoor botanical_garden bridge bullring
|
67 |
+
bus_interior butte canyon casino_outdoor castle church_outdoor closet coast conference_room construction_site corral
|
68 |
+
corridor crosswalk day_care_center sand elevator_interior escalator_indoor forest_road gangplank gas_station
|
69 |
+
golf_course gymnasium_indoor harbor hayfield heath hoodoo house hunting_lodge_outdoor ice_shelf joss_house kiosk_indoor
|
70 |
+
kitchen landfill library_indoor lido_deck_outdoor living_room locker_room market_outdoor mountain_snowy office orchard
|
71 |
+
arbor bookshelf mews nook preserve traffic_island palace palace_hall pantry patio phone_booth establishment
|
72 |
+
poolroom_home quonset_hut_outdoor rice_paddy sandbox shopfront skyscraper stone_circle subway_interior platform
|
73 |
+
supermarket swimming_pool_outdoor television_studio indoor_procenium train_railway coral_reef viaduct wave wind_farm
|
74 |
+
bottle_storage abbey access_road air_base airfield airlock airplane_cabin airport entrance airport_ticket_counter
|
75 |
+
alcove alley amphitheater amusement_arcade amusement_park anechoic_chamber apartment_building_outdoor apse_indoor
|
76 |
+
apse_outdoor aquarium aquatic_theater aqueduct arcade arch archaelogical_excavation archive basketball football hockey
|
77 |
+
performance rodeo soccer armory army_base arrival_gate_indoor arrival_gate_outdoor art_school art_studio artists_loft
|
78 |
+
assembly_line athletic_field_indoor athletic_field_outdoor atrium_home atrium_public attic auditorium auto_factory
|
79 |
+
auto_mechanics_indoor auto_mechanics_outdoor auto_racing_paddock auto_showroom backstage backstairs
|
80 |
+
badminton_court_indoor badminton_court_outdoor baggage_claim shop exterior balcony_interior ballroom bamboo_forest
|
81 |
+
bank_indoor bank_outdoor bank_vault banquet_hall baptistry_indoor baptistry_outdoor bar barbershop barn barndoor
|
82 |
+
barnyard barrack baseball_field basement basilica basketball_court_indoor basketball_court_outdoor bathhouse
|
83 |
+
batters_box batting_cage_indoor batting_cage_outdoor battlement bayou bazaar_indoor bazaar_outdoor beach_house
|
84 |
+
beauty_salon bedchamber beer_garden beer_hall belfry bell_foundry berth berth_deck betting_shop bicycle_racks bindery
|
85 |
+
biology_laboratory bistro_indoor bistro_outdoor bleachers_indoor bleachers_outdoor boardwalk boat_deck boathouse bog
|
86 |
+
bomb_shelter_indoor bookbindery bookstore bow_window_indoor bow_window_outdoor bowling_alley box_seat boxing_ring
|
87 |
+
breakroom brewery_indoor brewery_outdoor brickyard_indoor brickyard_outdoor building_complex building_facade bullpen
|
88 |
+
burial_chamber bus_depot_indoor bus_depot_outdoor bus_shelter bus_station_indoor bus_station_outdoor butchers_shop
|
89 |
+
cabana cabin_indoor cabin_outdoor cafeteria call_center campsite campus natural urban candy_store canteen
|
90 |
+
car_dealership backseat frontseat caravansary cardroom cargo_container_interior airplane boat freestanding
|
91 |
+
carport_indoor carport_outdoor carrousel casino_indoor catacomb cathedral_indoor cathedral_outdoor catwalk
|
92 |
+
cavern_indoor cavern_outdoor cemetery chalet chaparral chapel checkout_counter cheese_factory chemical_plant
|
93 |
+
chemistry_lab chicken_coop_indoor chicken_coop_outdoor chicken_farm_indoor chicken_farm_outdoor childs_room
|
94 |
+
choir_loft_interior church_indoor circus_tent_indoor circus_tent_outdoor city classroom clean_room cliff booth room
|
95 |
+
clock_tower_indoor cloister_indoor cloister_outdoor clothing_store coast_road cockpit coffee_shop computer_room
|
96 |
+
conference_center conference_hall confessional control_room control_tower_indoor control_tower_outdoor
|
97 |
+
convenience_store_indoor convenience_store_outdoor corn_field cottage cottage_garden courthouse courtroom courtyard
|
98 |
+
covered_bridge_interior crawl_space creek crevasse library cybercafe dacha dairy_indoor dairy_outdoor dam dance_school
|
99 |
+
darkroom delicatessen dentists_office department_store departure_lounge vegetation desert_road diner_indoor
|
100 |
+
diner_outdoor dinette_home vehicle dining_car dining_hall dining_room dirt_track discotheque distillery ditch dock
|
101 |
+
dolmen donjon doorway_indoor doorway_outdoor dorm_room downtown drainage_ditch dress_shop dressing_room drill_rig
|
102 |
+
driveway driving_range_indoor driving_range_outdoor drugstore dry_dock dugout earth_fissure editing_room
|
103 |
+
electrical_substation elevated_catwalk door freight_elevator elevator_lobby elevator_shaft embankment embassy
|
104 |
+
engine_room entrance_hall escalator_outdoor escarpment estuary excavation exhibition_hall fabric_store factory_indoor
|
105 |
+
factory_outdoor fairway farm fastfood_restaurant fence cargo_deck ferryboat_indoor passenger_deck cultivated wild
|
106 |
+
field_road fire_escape fire_station firing_range_indoor firing_range_outdoor fish_farm fishmarket fishpond
|
107 |
+
fitting_room_interior fjord flea_market_indoor flea_market_outdoor floating_dry_dock flood florist_shop_indoor
|
108 |
+
florist_shop_outdoor fly_bridge food_court football_field broadleaf needleleaf forest_fire forest_path formal_garden
|
109 |
+
fort fortress foundry_indoor foundry_outdoor fountain freeway funeral_chapel funeral_home furnace_room galley game_room
|
110 |
+
garage_indoor garage_outdoor garbage_dump gasworks gate gatehouse gazebo_interior general_store_indoor
|
111 |
+
general_store_outdoor geodesic_dome_indoor geodesic_dome_outdoor ghost_town gift_shop glacier glade gorge granary
|
112 |
+
great_hall greengrocery greenhouse_indoor greenhouse_outdoor grotto guardhouse gulch gun_deck_indoor gun_deck_outdoor
|
113 |
+
gun_store hacienda hallway handball_court hangar_indoor hangar_outdoor hardware_store hat_shop hatchery hayloft hearth
|
114 |
+
hedge_maze hedgerow heliport herb_garden highway hill home_office home_theater hospital hospital_room hot_spring
|
115 |
+
hot_tub_indoor hot_tub_outdoor hotel_outdoor hotel_breakfast_area hotel_room hunting_lodge_indoor hut ice_cream_parlor
|
116 |
+
ice_floe ice_skating_rink_indoor ice_skating_rink_outdoor iceberg igloo imaret incinerator_indoor incinerator_outdoor
|
117 |
+
industrial_area industrial_park inn_indoor inn_outdoor irrigation_ditch islet jacuzzi_indoor jacuzzi_outdoor
|
118 |
+
jail_indoor jail_outdoor jail_cell japanese_garden jetty jewelry_shop junk_pile junkyard jury_box kasbah kennel_indoor
|
119 |
+
kennel_outdoor kindergarden_classroom kiosk_outdoor kitchenette lab_classroom labyrinth_indoor labyrinth_outdoor lagoon
|
120 |
+
artificial landing landing_deck laundromat lava_flow lavatory lawn lean-to lecture_room legislative_chamber levee
|
121 |
+
library_outdoor lido_deck_indoor lift_bridge lighthouse limousine_interior liquor_store_indoor liquor_store_outdoor
|
122 |
+
loading_dock lobby lock_chamber loft lookout_station_indoor lookout_station_outdoor lumberyard_indoor
|
123 |
+
lumberyard_outdoor machine_shop manhole mansion manufactured_home market_indoor marsh martial_arts_gym mastaba
|
124 |
+
maternity_ward mausoleum medina menhir mesa mess_hall mezzanine military_hospital military_hut military_tent mine
|
125 |
+
mineshaft mini_golf_course_indoor mini_golf_course_outdoor mission dry water mobile_home monastery_indoor
|
126 |
+
monastery_outdoor moon_bounce moor morgue mosque_indoor mosque_outdoor motel mountain mountain_path mountain_road
|
127 |
+
movie_theater_indoor movie_theater_outdoor mudflat museum_indoor museum_outdoor music_store music_studio misc
|
128 |
+
natural_history_museum naval_base newsroom newsstand_indoor newsstand_outdoor nightclub nuclear_power_plant_indoor
|
129 |
+
nuclear_power_plant_outdoor nunnery nursery nursing_home oasis oast_house observatory_indoor observatory_outdoor
|
130 |
+
observatory_post ocean office_building office_cubicles oil_refinery_indoor oil_refinery_outdoor oilrig operating_room
|
131 |
+
optician organ_loft_interior orlop_deck ossuary outcropping outhouse_indoor outhouse_outdoor overpass oyster_bar
|
132 |
+
oyster_farm acropolis aircraft_carrier_object amphitheater_indoor archipelago questionable assembly_hall assembly_plant
|
133 |
+
awning_deck back_porch backdrop backroom backstage_outdoor backstairs_indoor backwoods ballet balustrade barbeque
|
134 |
+
basin_outdoor bath_indoor bath_outdoor bathhouse_outdoor battlefield bay booth_outdoor bottomland breakfast_table
|
135 |
+
bric-a-brac brooklet bubble_chamber buffet bulkhead bunk_bed bypass byroad cabin_cruiser cargo_helicopter cellar
|
136 |
+
chair_lift cocktail_lounge corner country_house country_road customhouse dance_floor deck-house_boat_deck_house
|
137 |
+
deck-house_deck_house dining_area diving_board embrasure entranceway_indoor entranceway_outdoor entryway_outdoor
|
138 |
+
estaminet farm_building farmhouse feed_bunk field_house field_tent_indoor field_tent_outdoor fire_trench fireplace
|
139 |
+
flashflood flatlet floating_dock flood_plain flowerbed flume_indoor flying_buttress foothill forecourt foreshore
|
140 |
+
front_porch garden gas_well glen grape_arbor grove guardroom guesthouse gymnasium_outdoor head_shop hen_yard hillock
|
141 |
+
housing_estate housing_project howdah inlet insane_asylum outside juke_joint jungle kraal laboratorywet landing_strip
|
142 |
+
layby lean-to_tent loge loggia_outdoor lower_deck luggage_van mansard meadow meat_house megalith mens_store_outdoor
|
143 |
+
mental_institution_indoor mental_institution_outdoor military_headquarters millpond millrace natural_spring
|
144 |
+
nursing_home_outdoor observation_station open-hearth_furnace operating_table outbuilding palestra parkway patio_indoor
|
145 |
+
pavement pawnshop_outdoor pinetum piste_road pizzeria_outdoor powder_room pumping_station reception_room rest_stop
|
146 |
+
retaining_wall rift_valley road rock_garden rotisserie safari_park salon saloon sanatorium science_laboratory scrubland
|
147 |
+
scullery seaside semidesert shelter shelter_deck shelter_tent shore shrubbery sidewalk snack_bar snowbank stage_set
|
148 |
+
stall stateroom store streetcar_track student_center study_hall sugar_refinery sunroom supply_chamber t-bar_lift
|
149 |
+
tannery teahouse threshing_floor ticket_window_indoor tidal_basin tidal_river tiltyard tollgate tomb tract_housing
|
150 |
+
trellis truck_stop upper_balcony vestibule vinery walkway war_room washroom water_fountain water_gate waterscape
|
151 |
+
waterway wetland widows_walk_indoor windstorm packaging_plant pagoda paper_mill park parking_garage_indoor
|
152 |
+
parking_garage_outdoor parking_lot parlor particle_accelerator party_tent_indoor party_tent_outdoor pasture pavilion
|
153 |
+
pawnshop pedestrian_overpass_indoor penalty_box pet_shop pharmacy physics_laboratory piano_store picnic_area pier
|
154 |
+
pig_farm pilothouse_indoor pilothouse_outdoor pitchers_mound pizzeria planetarium_indoor planetarium_outdoor
|
155 |
+
plantation_house playground playroom plaza podium_indoor podium_outdoor police_station pond pontoon_bridge poop_deck
|
156 |
+
porch portico portrait_studio postern power_plant_outdoor print_shop priory promenade promenade_deck pub_indoor
|
157 |
+
pub_outdoor pulpit putting_green quadrangle quicksand quonset_hut_indoor racecourse raceway raft railroad_track
|
158 |
+
railway_yard rainforest ramp ranch ranch_house reading_room reception recreation_room rectory recycling_plant_indoor
|
159 |
+
refectory repair_shop residential_neighborhood resort rest_area restaurant restaurant_kitchen restaurant_patio
|
160 |
+
restroom_indoor restroom_outdoor revolving_door riding_arena river road_cut rock_arch roller_skating_rink_indoor
|
161 |
+
roller_skating_rink_outdoor rolling_mill roof roof_garden root_cellar rope_bridge roundabout roundhouse rubble ruin
|
162 |
+
runway sacristy salt_plain sand_trap sandbar sauna savanna sawmill schoolhouse schoolyard science_museum scriptorium
|
163 |
+
sea_cliff seawall security_check_point server_room sewer sewing_room shed shipping_room shipyard_outdoor shoe_shop
|
164 |
+
shopping_mall_indoor shopping_mall_outdoor shower shower_room shrine signal_box sinkhole ski_jump ski_lodge ski_resort
|
165 |
+
ski_slope sky skywalk_indoor skywalk_outdoor slum snowfield massage_room mineral_bath spillway sporting_goods_store
|
166 |
+
squash_court stable baseball stadium_outdoor stage_indoor stage_outdoor staircase starting_gate steam_plant_outdoor
|
167 |
+
steel_mill_indoor storage_room storm_cellar street strip_mall strip_mine student_residence submarine_interior sun_deck
|
168 |
+
sushi_bar swamp swimming_hole swimming_pool_indoor synagogue_indoor synagogue_outdoor taxistand taxiway tea_garden
|
169 |
+
tearoom teashop television_room east_asia mesoamerican south_asia western tennis_court_indoor tennis_court_outdoor
|
170 |
+
tent_outdoor terrace_farm indoor_round indoor_seats theater_outdoor thriftshop throne_room ticket_booth
|
171 |
+
tobacco_shop_indoor toll_plaza tollbooth topiary_garden tower town_house toyshop track_outdoor trading_floor
|
172 |
+
trailer_park train_interior train_station_outdoor station tree_farm tree_house trench trestle_bridge tundra rail_indoor
|
173 |
+
rail_outdoor road_indoor road_outdoor turkish_bath ocean_deep ocean_shallow utility_room valley van_interior
|
174 |
+
vegetable_garden velodrome_indoor velodrome_outdoor ventilation_shaft veranda vestry veterinarians_office videostore
|
175 |
+
village vineyard volcano volleyball_court_indoor volleyball_court_outdoor voting_booth waiting_room walk_in_freezer
|
176 |
+
warehouse_indoor warehouse_outdoor washhouse_indoor washhouse_outdoor watchtower water_mill water_park water_tower
|
177 |
+
water_treatment_plant_indoor water_treatment_plant_outdoor block cascade cataract fan plunge watering_hole weighbridge
|
178 |
+
wet_bar wharf wheat_field whispering_gallery widows_walk_interior windmill window_seat barrel_storage winery
|
179 |
+
witness_stand woodland workroom workshop wrestling_ring_indoor wrestling_ring_outdoor yard youth_hostel zen_garden
|
180 |
+
ziggurat zoo forklift hollow hutment pueblo vat perfume_shop steel_mill_outdoor orchestra_pit bridle_path lyceum
|
181 |
+
one-way_street parade_ground pump_room recycling_plant_outdoor chuck_wagon
|
182 |
+
"""
|
183 |
+
_SCENE_CATEGORIES = _SCENE_CATEGORIES.strip().split()
|
184 |
+
|
185 |
+
|
186 |
+
class SceneParse150(datasets.GeneratorBasedBuilder):
|
187 |
+
"""MIT Scene Parsing Benchmark dataset."""
|
188 |
+
|
189 |
+
VERSION = datasets.Version("1.0.0")
|
190 |
+
|
191 |
+
BUILDER_CONFIGS = [
|
192 |
+
datasets.BuilderConfig(name="scene_parsing", version=VERSION, description="The scene parsing variant."),
|
193 |
+
datasets.BuilderConfig(
|
194 |
+
name="instance_segmentation", version=VERSION, description="The instance segmentation variant."
|
195 |
+
),
|
196 |
+
]
|
197 |
+
|
198 |
+
DEFAULT_CONFIG_NAME = "scene_parsing"
|
199 |
+
|
200 |
+
def _info(self):
|
201 |
+
if self.config.name == "scene_parsing":
|
202 |
+
features = datasets.Features(
|
203 |
+
{
|
204 |
+
"image": datasets.Image(),
|
205 |
+
"annotation": datasets.Image(),
|
206 |
+
"scene_category": datasets.ClassLabel(names=_SCENE_CATEGORIES),
|
207 |
+
}
|
208 |
+
)
|
209 |
+
else:
|
210 |
+
features = datasets.Features(
|
211 |
+
{
|
212 |
+
"image": datasets.Image(),
|
213 |
+
"annotation": datasets.Image(),
|
214 |
+
}
|
215 |
+
)
|
216 |
+
return datasets.DatasetInfo(
|
217 |
+
description=_DESCRIPTION,
|
218 |
+
features=features,
|
219 |
+
homepage=_HOMEPAGE,
|
220 |
+
license=_LICENSE,
|
221 |
+
citation=_CITATION,
|
222 |
+
)
|
223 |
+
|
224 |
+
def _split_generators(self, dl_manager):
|
225 |
+
urls = _URLS[self.config.name]
|
226 |
+
|
227 |
+
if self.config.name == "scene_parsing":
|
228 |
+
data_dirs = dl_manager.download_and_extract(urls)
|
229 |
+
train_data = val_data = os.path.join(data_dirs["train/val"], "ADEChallengeData2016")
|
230 |
+
test_data = os.path.join(data_dirs["test"], "release_test")
|
231 |
+
else:
|
232 |
+
data_dirs = dl_manager.download(urls)
|
233 |
+
train_data = dl_manager.iter_archive(data_dirs["images"]), dl_manager.iter_archive(
|
234 |
+
data_dirs["annotations"]
|
235 |
+
)
|
236 |
+
val_data = dl_manager.iter_archive(data_dirs["images"]), dl_manager.iter_archive(data_dirs["annotations"])
|
237 |
+
test_data = dl_manager.iter_archive(data_dirs["test"])
|
238 |
+
return [
|
239 |
+
datasets.SplitGenerator(
|
240 |
+
name=datasets.Split.TRAIN,
|
241 |
+
gen_kwargs={
|
242 |
+
"data": train_data,
|
243 |
+
"split": "training",
|
244 |
+
},
|
245 |
+
),
|
246 |
+
datasets.SplitGenerator(
|
247 |
+
name=datasets.Split.TEST,
|
248 |
+
gen_kwargs={"data": test_data, "split": "testing"},
|
249 |
+
),
|
250 |
+
datasets.SplitGenerator(
|
251 |
+
name=datasets.Split.VALIDATION,
|
252 |
+
gen_kwargs={
|
253 |
+
"data": val_data,
|
254 |
+
"split": "validation",
|
255 |
+
},
|
256 |
+
),
|
257 |
+
]
|
258 |
+
|
259 |
+
def _generate_examples(self, data, split):
|
260 |
+
if self.config.name == "scene_parsing":
|
261 |
+
if split == "testing":
|
262 |
+
image_dir = os.path.join(data, split)
|
263 |
+
for idx, image_file in enumerate(os.listdir(image_dir)):
|
264 |
+
yield idx, {
|
265 |
+
"image": os.path.join(image_dir, image_file),
|
266 |
+
"annotation": None,
|
267 |
+
"scene_category": None,
|
268 |
+
}
|
269 |
+
else:
|
270 |
+
image_id2cat = pd.read_csv(
|
271 |
+
os.path.join(data, "sceneCategories.txt"), sep=" ", names=["image_id", "scene_category"]
|
272 |
+
)
|
273 |
+
image_id2cat = image_id2cat.set_index("image_id")
|
274 |
+
images_dir = os.path.join(data, "images", split)
|
275 |
+
annotations_dir = os.path.join(data, "annotations", split)
|
276 |
+
for idx, image_file in enumerate(os.listdir(images_dir)):
|
277 |
+
image_id = image_file.split(".")[0]
|
278 |
+
yield idx, {
|
279 |
+
"image": os.path.join(images_dir, image_file),
|
280 |
+
"annotation": os.path.join(annotations_dir, image_id + ".json"),
|
281 |
+
"scene_category": image_id2cat.loc[image_id, "scene_category"],
|
282 |
+
}
|
283 |
+
else:
|
284 |
+
if split == "testing":
|
285 |
+
for idx, (path, file) in enumerate(data):
|
286 |
+
if path.endswith(".jpg"):
|
287 |
+
yield idx, {
|
288 |
+
"image": {"path": path, "bytes": file.read()},
|
289 |
+
"annotation": None,
|
290 |
+
}
|
291 |
+
else:
|
292 |
+
images, annotations = data
|
293 |
+
image_id2annot = {}
|
294 |
+
# loads the annotations for the split into RAM (less than 100 MB) to support streaming
|
295 |
+
for path_annot, file_annot in annotations:
|
296 |
+
if split in path_annot and path_annot.endswith(".json"):
|
297 |
+
image_id = os.path.basename(path_annot).split(".")[0]
|
298 |
+
image_id2annot[image_id] = (path_annot, file_annot.read())
|
299 |
+
for idx, (path_img, file_img) in enumerate(images):
|
300 |
+
if split in path_img and path_img.endswith(".jpg"):
|
301 |
+
image_id = os.path.basename(path_img).split(".")[0]
|
302 |
+
path_annot, bytes_annot = image_id2annot[image_id]
|
303 |
+
yield idx, {
|
304 |
+
"image": {"path": path_img, "bytes": file_img.read()},
|
305 |
+
"annotation": {"path": path_annot, "bytes": bytes_annot},
|
306 |
}
|