File size: 21,650 Bytes
e4cef19 181f840 e4cef19 181f840 e4cef19 181f840 e4cef19 9bc2273 e4cef19 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 |
from pathlib import Path
from typing import Set
from datasets import DatasetBuilder, GeneratorBasedBuilder, DatasetInfo, Features, Image, ClassLabel, Array3D, DownloadManager, SplitGenerator, BuilderConfig, Version
import numpy as np
import datasets
VERSION = "v1_240507"
HF_VERSION = "1.0.0"
# Available Dataset View Names
full_dataset_name = "full-dataset"
semantic_segmentation_name = "semantic-segmentation"
instance_segmentation_name = "instance-segmentation"
animal_category_anomoalies_name = "animal-category-anomalies"
re_id_best_name = "chicken-re-id-best-visibility"
#re_id_good_name = "chicken-re-id-good-visibility"
#re_id_bad_name = "chicken-re-id-bad-visibility"
re_id_full_name = "chicken-re-id-all-visibility"
# Example usage
# from datasets import load_dataset
# dataset = datasets.load_dataset(
# "dariakern/Chicks4FreeID",
# "chicken-re-id-best-visibility",
# as_supervised=True,
# trust_remote_code=True
# )
##### ONTOLOTGY ######
ontologies = {
"v1_240507":
{'tools': [{'classifications': [{'instructions': 'coop',
'options': [{'label': '1'},
{'label': '2'},
{'label': '3'},
{'label': '4'},
{'label': '5'},
{'label': '6'},
{'label': '7'},
{'label': '8'},
{'label': '9'},
{'label': '10'},
{'label': '11'},],
'required': True,
'type': 'radio'},
{'instructions': 'identity',
'options': [{'label': 'Beate'},
{'label': 'Borghild'},
{'label': 'Eleonore'},
{'label': 'Mona'},
{'label': 'Henriette'},
{'label': 'Margit'},
{'label': 'Millie'},
{'label': 'Sigrun'},
{'label': 'Kristina'},
{'label': 'Unknown'},
{'label': 'Tina'},
{'label': 'Gretel'},
{'label': 'Lena'},
{'label': 'Yolkoono'},
{'label': 'Skimmy'},
{'label': 'Mavi'},
{'label': 'Mirmir'},
{'label': 'Nugget'},
{'label': 'Fernanda'},
{'label': 'Isolde'},
{'label': 'Mechthild'},
{'label': 'Brunhilde'},
{'label': 'Spiderman'},
{'label': 'Brownie'},
{'label': 'Camy'},
{'label': 'Samy'},
{'label': 'Yin'},
{'label': 'Yuriko'},
{'label': 'Renate'},
{'label': 'Regina'},
{'label': 'Monika'},
{'label': 'Heidi'},
{'label': 'Erna'},
{'label': 'Marina'},
{'label': 'Kathrin'},
{'label': 'Isabella'},
{'label': 'Amalia'},
{'label': 'Edeltraut'},
{'label': 'Erdmute'},
{'label': 'Oktavia'},
{'label': 'Siglinde'},
{'label': 'Ulrike'},
{'label': 'Hermine'},
{'label': 'Matilda'},
{'label': 'Chantal'},
{'label': 'Chayenne'},
{'label': 'Jaqueline'},
{'label': 'Mandy'},
{'label': 'Henny'},
{'label': 'Shady'},
{'label': 'Shorty'}],
'required': True,
'type': 'radio'},
{'instructions': 'visibility',
'options': [{'label': 'best'},
{'label': 'good'},
{'label': 'bad'}],
'required': True,
'type': 'radio'}],
'color': '#1e1cff',
'name': 'chicken',
'required': False,
'tool': 'superpixel'},
{'color': '#FF34FF',
'name': 'background',
'required': False,
'tool': 'superpixel'},
{'classifications': [{'instructions': 'coop',
'options': [{'label': '1'},
{'label': '2'},
{'label': '3'},
{'label': '4'},
{'label': '5'},
{'label': '6'},
{'label': '7'},
{'label': '8'},
{'label': '9'},
{'label': '10'},
{'label': '11'}],
'required': True,
'type': 'radio'},
{'instructions': 'identity',
'options': [{'label': 'Evelyn'},
{'label': 'Marley'}],
'required': True,
'type': 'radio'},
{'instructions': 'visibility',
'options': [{'label': 'best'},
{'label': 'good'},
{'label': 'bad'}],
'required': True,
'type': 'radio'}],
'color': '#FF4A46',
'name': 'duck',
'required': False,
'tool': 'superpixel'},
{'classifications': [{'instructions': 'coop',
'options': [{'label': '1'},
{'label': '2'},
{'label': '3'},
{'label': '4'},
{'label': '5'},
{'label': '6'},
{'label': '7'},
{'label': '8'},
{'label': '9'},
{'label': '10'},
{'label': '11'}],
'required': True,
'type': 'radio'},
{'instructions': 'identity',
'options': [{'label': 'Elvis'},
{'label': 'Jackson'}],
'required': True,
'type': 'radio'},
{'instructions': 'visibility',
'options': [{'label': 'best'},
{'label': 'good'},
{'label': 'bad'}],
'required': True,
'type': 'radio'}],
'color': '#ff0000',
'name': 'rooster',
'required': False,
'tool': 'superpixel'}]}
}
ontologies["v1_240507_SMALL"] = ontologies["v1_240507"]
class Ontology:
ontology: dict = None
def __init__(self, version_name: str):
self.ontology: dict = ontologies[version_name]
def names(self, class_name, tool_name=None, drop_unkown=False):
"""
Returns a list of all possible names for a given category (accross all tools)
"""
if class_name == "animal_category":
return sorted(list({tool["name"] for tool in self.ontology["tools"]} - {"background"}))
result = []
for tool in self.ontology["tools"]:
if "classifications" in tool:
for classification in tool["classifications"]:
if classification["instructions"] == class_name and (tool_name is None or tool_name == tool["name"]):
result.extend([option["label"] for option in classification["options"] if not (drop_unkown and option["label"] == "Unknown") and option["label"] not in result])
return list(result)
def get_color_map(self):
"""
Returns a dictionary mapping class names to their respective colors
"""
return {tool["name"]: tool["color"] for tool in self.ontology["tools"]}
ontology = Ontology(VERSION)
# Feature Names
IMAGE = "image"
image_feature = {IMAGE: Image()}
SEGMENTATION_MAKS = "segmentation_mask"
segmentation_mask_feature = {SEGMENTATION_MAKS: Image()}
INSTANCE_MASK = "instance_mask"
instance_mask_feature = {INSTANCE_MASK: Image()}
CROP = "crop"
crop_feature = {CROP: Image()}
ID = "identity"
identity_feature = {ID: ClassLabel(names=ontology.names(ID))}
chicken_only_identitiy_feature = {ID: ClassLabel(names=ontology.names(ID, "chicken", drop_unkown=True))}
VISIBILITY = "visibility"
visibility_feature = {VISIBILITY: ClassLabel(names=ontology.names(VISIBILITY))}
COOP = "coop"
coop_feature = {COOP: ClassLabel(names=ontology.names(COOP))}
CATEGORY = "animal_category"
animal_category_feature = {CATEGORY: ClassLabel(names=ontology.names(CATEGORY))}
INSTANCES = "instances"
instance_features = {
**crop_feature,
**instance_mask_feature,
**identity_feature,
**visibility_feature,
**animal_category_feature,
}
all_features = {
**image_feature,
**segmentation_mask_feature,
**coop_feature,
INSTANCES: [instance_features],
}
def name_to_dict(filename: str):
"""
Converts a filename to a dictionary object by splitting the filename by underscores and using the even indices as keys and the odd indices as values.
"""
return {filename.split('_')[i]: filename.split('_')[i + 1] for i in range(0, len(filename.split('_')) - 1, 2)}
class ChicksDataset(GeneratorBasedBuilder):
BUILDER_CONFIGS = [
BuilderConfig(name=full_dataset_name, version=Version(HF_VERSION), description="The complete dataset including all features and image types. Includes all coops, visibility ratings, identities, and animal categories, as well as segmentation masks and instance masks."),
BuilderConfig(name=semantic_segmentation_name, version=Version(HF_VERSION), description="Includes images and color-coded segmentation masks."),
BuilderConfig(name=instance_segmentation_name, version=Version(HF_VERSION), description="Includes images and a corresponding sequence of binary instance segmentation masks for each instance on the image."),
BuilderConfig(name=animal_category_anomoalies_name, version=Version(HF_VERSION), description="Includes images of mostly chicken, but also some roosters and ducks, which make up the anomalies in the dataset."),
BuilderConfig(name=re_id_best_name, version=Version(HF_VERSION), description="Includes crops of chickens which have the best visibility rating for re-identification."),
#BuilderConfig(name=re_id_good_name, version=Version(HF_VERSION), description="Includes crops of chickens which have neither the best nor the worst visibility rating for re-identification."),
#BuilderConfig(name=re_id_bad_name, version=Version(HF_VERSION), description="Includes crops of chickens which have the worst (bad) visibility rating for re-identification."),
BuilderConfig(name=re_id_full_name, version=Version(HF_VERSION), description="Includes crops of chickens with all visibilities for re-identification without any filtering on visibility rating."),
]
def _info(self, *args, **kwargs):
if self.config.name == full_dataset_name:
return DatasetInfo(
features=Features(all_features),
)
elif self.config.name in [
re_id_full_name, re_id_best_name,
# re_id_good_name, re_id_bad_name
]:
return DatasetInfo(
features=Features({
**crop_feature,
**chicken_only_identitiy_feature,
}),
supervised_keys=(
CROP,
ID,
),
)
elif self.config.name == semantic_segmentation_name:
return DatasetInfo(
features=Features({
**image_feature,
**segmentation_mask_feature,
}),
supervised_keys=(
IMAGE,
SEGMENTATION_MAKS,
)
)
elif self.config.name == instance_segmentation_name:
return DatasetInfo(
features=Features({
**image_feature,
INSTANCES: [instance_mask_feature],
}),
supervised_keys=(
IMAGE,
INSTANCES, # TODO use nested reference to instance_mask_feature
)
)
elif self.config.name == animal_category_anomoalies_name:
return DatasetInfo(
features=Features({
**crop_feature,
**animal_category_feature,
}),
supervised_keys=(
CROP,
CATEGORY
)
)
def _split_generators(self, dl_manager: DownloadManager):
URL = f"https://huggingface.co/datasets/dariakern/Chicks4FreeID/resolve/main/{VERSION}.zip?download=true"
base_path = Path(dl_manager.download_and_extract(URL))
# Only offer train test split for chicken-re-id task
if self.config.name in [
re_id_full_name,
re_id_best_name
]:
from sklearn.model_selection import train_test_split
# all crop files (only chicken, remove unknowns)
all_crops = sorted([
crop_file
for crop_file
in base_path.rglob(f"**/{VERSION}/reId/chicken/**/*crop_*.png")
if "Unknown" not in crop_file.parts
])
# all identity targets (labels)
identities = [name_to_dict(crop.stem)[ID] for crop in all_crops]
if VERSION == "v1_240507_SMALL":
train_crops, test_crops = all_crops, all_crops
else:
# Splitting the dataset into train and test using stratified train_test_split
train_crops, test_crops, _, _ = train_test_split(
all_crops, identities, test_size=0.2, stratify=identities, shuffle=True, random_state=42
)
return [
SplitGenerator(
gen_kwargs={"base_path": base_path, "split": set(train_crops)},
name=datasets.Split.TRAIN,
),
SplitGenerator(
gen_kwargs={"base_path": base_path, "split": set(test_crops)},
name=datasets.Split.TEST,
)
]
else:
return [
SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={"base_path": base_path, "split": None})
]
def _generate_all(self, base_path: Path, split: Set[Path]=None):
"""
Generates all examples for the dataset, including all features.
Args:
base_path (Path): The base path to the dataset
split (Set[Path]): The paths to all instance crops to include in the current dataset
"""
img_dir = base_path / f"{VERSION}/images"
mask_dir = base_path / f"{VERSION}/masks"
reid_dir = base_path / f"{VERSION}/reId"
# Collecting images, segmentation masks, and instance masks
for img_file in img_dir.iterdir():
image_id = img_file.stem
image_path = img_file
segmentation_mask_path = mask_dir / f"{image_id}_segmentationMask.png"
instance_masks = list(mask_dir.rglob(f"{image_id}_instanceMask_*.png"))
instance_crops = list(reid_dir.rglob(f"**/{image_id}_crop_*.png"))
# Check if all crops have a corresponding instance mask
assert len(instance_masks) == len(instance_crops) and len(instance_masks) > 0
# Remove any instance_crops that are not in crops_split
if split is not None:
instance_crops = [crop for crop in instance_crops if crop in split]
instance_data = []
infos = {}
for instance_mask_path, crop_path in zip(instance_masks, instance_crops):
infos = name_to_dict(crop_path.stem)
instance_data.append({
INSTANCE_MASK: str(instance_mask_path),
CROP: str(crop_path),
VISIBILITY: infos[VISIBILITY],
ID: infos[ID],
CATEGORY: crop_path.relative_to(reid_dir).parts[0],
})
if instance_data:
yield image_id, {
IMAGE: str(image_path),
SEGMENTATION_MAKS: str(segmentation_mask_path),
COOP: infos[COOP],
INSTANCES: instance_data,
}
def _generate_examples(self, **kwargs):
if self.config.name in [full_dataset_name]:
yield from self._generate_all(**kwargs)
elif self.config.name == semantic_segmentation_name:
for image_id, example in self._generate_all(**kwargs):
yield image_id, {
IMAGE: example[IMAGE],
SEGMENTATION_MAKS: example[SEGMENTATION_MAKS],
}
elif self.config.name == instance_segmentation_name:
for image_id, example in self._generate_all(**kwargs):
yield image_id, {
IMAGE: example[IMAGE],
INSTANCES: [
{
INSTANCE_MASK: instance[INSTANCE_MASK]
}
for instance in example[INSTANCES]
]
}
elif self.config.name == animal_category_anomoalies_name:
for image_id, example in self._generate_all(**kwargs):
for instance in example[INSTANCES]:
instance_id = Path(instance[CROP]).stem
yield instance_id, {
CROP: instance[CROP],
CATEGORY: instance[CATEGORY],
}
elif self.config.name in [
re_id_best_name, re_id_full_name,
# re_id_good_name, re_id_bad_name
]:
for image_id, example in self._generate_all(**kwargs):
for instance in example[INSTANCES]:
# Conditions for filtering
use_all = self.config.name == re_id_full_name
selected_visibility = instance[VISIBILITY] == self.config.name.split("-")[-2]
if use_all or selected_visibility:
instance_id = Path(instance[CROP]).stem
yield instance_id, {
CROP: instance[CROP],
ID: instance[ID],
}
|