| | 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_SMALL" |
| | HF_VERSION = "1.0.0" |
| |
|
| | |
| | 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_full_name = "chicken-re-id-all-visibility" |
| |
|
| |
|
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| |
|
| | |
| |
|
| |
|
| | ontologies = { |
| | "v1_240507": |
| | {'tools': [{'classifications': [{'instructions': 'coop', |
| | 'options': [{'label': '10'}, |
| | {'label': '1'}, |
| | {'label': '2'}, |
| | {'label': '3'}, |
| | {'label': '4'}, |
| | {'label': '5'}, |
| | {'label': '6'}, |
| | {'label': '7'}, |
| | {'label': '8'}, |
| | {'label': '9'}, |
| | {'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 list({tool["name"] for tool in self.ontology["tools"]} - {"background"}) |
| |
|
| | result = set() |
| | 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.update({option["label"] for option in classification["options"] if not (drop_unkown and option["label"] == "Unknown")}) |
| | 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) |
| |
|
| | |
| | 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_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, |
| | |
| | ]: |
| | 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, |
| | ) |
| | ) |
| | |
| | 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)) |
| |
|
| | |
| | if self.config.name in [ |
| | re_id_full_name, |
| | re_id_best_name |
| | ]: |
| | from sklearn.model_selection import train_test_split |
| |
|
| | |
| | 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 |
| | ]) |
| | |
| | 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: |
| | |
| | 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" |
| | |
| | |
| | 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")) |
| | |
| | |
| | assert len(instance_masks) == len(instance_crops) and len(instance_masks) > 0 |
| |
|
| | |
| | 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, |
| | |
| | ]: |
| | for image_id, example in self._generate_all(**kwargs): |
| | for instance in example[INSTANCES]: |
| | |
| | |
| | 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], |
| | } |
| |
|
| |
|
| |
|
| |
|
| |
|