| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| """TODO: Add a description here.""" |
|
|
|
|
| import json |
| import logging |
| import os.path as osp |
| from pycocotools import mask as mask_utils |
|
|
| import datasets |
|
|
| logger = logging.getLogger(__name__) |
|
|
|
|
| |
| |
| _CITATION = """\ |
| @InProceedings{huggingface:dataset, |
| title = {A great new dataset}, |
| author={huggingface, Inc. |
| }, |
| year={2020} |
| } |
| """ |
|
|
| |
| |
| _DESCRIPTION = """\ |
| This COCO-Stuff dataset is designed to load coco-stuff only & coco stuff thing. |
| """ |
|
|
| |
| _HOMEPAGE = "" |
|
|
| |
| _LICENSE = "" |
|
|
| |
| |
| |
| |
| |
| _URLS = {} |
|
|
|
|
| VALID_SPLIT_NAMES = ("train", "val") |
|
|
|
|
| |
| |
| class COCOStuffDataset(datasets.GeneratorBasedBuilder): |
| """TODO: Short description of my dataset.""" |
|
|
| VERSION = datasets.Version("0.0.1") |
|
|
| |
| |
| |
|
|
| |
| |
| |
| |
| BUILDER_CONFIG_CLASS = datasets.BuilderConfig |
|
|
| |
| |
| |
| |
| BUILDER_CONFIGS = [ |
| |
| datasets.BuilderConfig( |
| name="stuff-only", version=VERSION, description="stuff-only."), |
| |
| datasets.BuilderConfig( |
| name="thing-only", version=VERSION, description="thing-only."), |
| |
| datasets.BuilderConfig( |
| name="stuff-thing", version=VERSION, description="stuff-thing"), |
| ] |
|
|
| |
| |
| DEFAULT_CONFIG_NAME = "stuff-thing" |
|
|
| def _info(self): |
| self.config: datasets.BuilderConfig |
| features = { |
| |
| "image_id": datasets.Value("int32"), |
| "file_name": datasets.Value("string"), |
| "image_path": datasets.Value("string"), |
| "mask_path": datasets.Value("string"), |
| "height": datasets.Value("int32"), |
| "width": datasets.Value("int32"), |
| "coco_url": datasets.Value("string"), |
| "objects": [ |
| { |
| "object_id": datasets.Value("string"), |
| "bbox": [datasets.Value("float")], |
| "x": datasets.Value("float"), |
| "y": datasets.Value("float"), |
| "w": datasets.Value("float"), |
| "h": datasets.Value("float"), |
| "category_id": datasets.Value("int32"), |
| "category": datasets.Value("string"), |
| "segmentation": {"counts": datasets.Value("string"), |
| "size": [datasets.Value("int32")], |
| "path": datasets.Value("string"), |
| "index": datasets.Value("int32")}, |
| } |
| ], |
| } |
| features = datasets.Features(features) |
| return datasets.DatasetInfo( |
| |
| description=_DESCRIPTION, |
| |
| features=features, |
| |
| |
| |
| |
| |
| homepage=_HOMEPAGE, |
| |
| license=_LICENSE, |
| |
| citation=_CITATION, |
| ) |
|
|
| def _split_generators(self, dl_manager): |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| splits = [] |
| split_names = ("train", "val") |
| for split in split_names: |
| splits.append(datasets.SplitGenerator( |
| name=datasets.NamedSplit(split), |
| gen_kwargs={"split": split}, |
| )) |
| return splits |
|
|
| def build_image_id_to_annotation_list_indices(self, stuff_json: dict): |
| msg = "Building mapping for image_id to annotation list indices ..." |
| logger.info(msg) |
| image_id_to_ann_ids: dict[int, list[int]] = {} |
| for idx, ann in enumerate(stuff_json["annotations"]): |
| img_id = ann["image_id"] |
| if img_id not in image_id_to_ann_ids: |
| image_id_to_ann_ids[img_id] = [] |
| image_id_to_ann_ids[img_id].append(idx) |
| logger.info("DONE.") |
| return image_id_to_ann_ids |
|
|
| def build_image_id_to_metainfo(self, stuff_json: dict): |
| msg = "Building mapping for image_id to metainfo ..." |
| logger.info(msg) |
| image_id_to_metainfo = {} |
| for img in stuff_json["images"]: |
| image_id_to_metainfo[img["id"]] = img |
| logger.info("DONE.") |
| return image_id_to_metainfo |
|
|
| def load_json(self, json_path: str): |
| with open(json_path, "r") as f: |
| return json.load(f) |
|
|
| def load_label_file(self, label_path: str): |
| with open(label_path, "r") as f: |
| contents = f.read().split("\n") |
| contents = list(filter(lambda x: len(x) > 0, contents)) |
| catid_label_pairs = [line.split(': ') for line in contents] |
| catid_to_label = { |
| int(catid): label for catid, label in catid_label_pairs |
| } |
| catid_to_label[183] = "other" |
| return catid_to_label |
|
|
| def _prepare_from_image_info( |
| self, image_info: dict, img_dir: str, ann_dir: str, split: str): |
| metainfo = {} |
| metainfo["image_path"] = osp.join( |
| img_dir, f"{split}2017", image_info["file_name"]) |
| metainfo["mask_path"] = osp.join( |
| ann_dir, f"{split}2017", |
| image_info["file_name"]).replace(".jpg", ".png") |
| metainfo["height"] = image_info['height'] |
| metainfo["width"] = image_info['width'] |
| metainfo["coco_url"] = image_info['coco_url'] |
| metainfo["file_name"] = image_info["file_name"] |
| if not osp.exists(metainfo["image_path"]): |
| raise FileNotFoundError( |
| f"Image file not found: {metainfo['image_path']}") |
| if not osp.exists(metainfo["mask_path"]): |
| raise FileNotFoundError( |
| f"Mask file not found: {metainfo['mask_path']}") |
| return metainfo |
|
|
| |
| |
| def _generate_examples(self, split: str): |
| |
| |
| |
| |
| data_root = self.config.data_dir |
| catid_to_label = self.load_label_file( |
| osp.join(data_root, "labels.txt")) |
| img_dir = osp.join(data_root, "images") |
| ann_dir = osp.join(data_root, "annotations") |
| stuff_json_path = osp.join( |
| data_root, f"stuff_{split}2017.json") |
| thing_json_path = osp.join( |
| data_root, f"annotations/instances_{split}2017.json") |
| stuff_metainfo = self.load_json(stuff_json_path) |
| thing_metainfo = self.load_json(thing_json_path) |
|
|
| image_id_to_stuff_anno_list_indices = \ |
| self.build_image_id_to_annotation_list_indices(stuff_metainfo) |
| image_id_to_thing_anno_list_indices = \ |
| self.build_image_id_to_annotation_list_indices(thing_metainfo) |
| image_id_to_stuff_metainfo = \ |
| self.build_image_id_to_metainfo(stuff_metainfo) |
| |
| |
| stuff_image_ids = set(image_id_to_stuff_anno_list_indices.keys()) |
| thing_image_ids = set(image_id_to_thing_anno_list_indices.keys()) |
| all_image_ids = stuff_image_ids.union(thing_image_ids) |
|
|
| for image_id in all_image_ids: |
| |
| image_stuff_info = image_id_to_stuff_metainfo[image_id] |
| data = self._prepare_from_image_info( |
| image_stuff_info, img_dir, ann_dir, split) |
|
|
| stuff_annos = [] |
| stuff_anno_indices = [] |
| stuff_path_list = [] |
| stuff_segms = [] |
| if image_id in image_id_to_stuff_anno_list_indices: |
| stuff_anno_indices = image_id_to_stuff_anno_list_indices[ |
| image_id] |
| stuff_annos = [stuff_metainfo["annotations"][idx] |
| for idx in stuff_anno_indices] |
| stuff_path_list = [stuff_json_path] * len(stuff_annos) |
| stuff_segms = [ann["segmentation"] for ann in stuff_annos] |
| thing_annos = [] |
| thing_anno_indices = [] |
| thing_path_list = [] |
| thing_segms = [] |
| if image_id in image_id_to_thing_anno_list_indices: |
| thing_anno_indices = image_id_to_thing_anno_list_indices[ |
| image_id] |
| thing_annos = [thing_metainfo["annotations"][idx] |
| for idx in thing_anno_indices] |
| thing_path_list = [thing_json_path] * len(thing_annos) |
| thing_segms = [ann["segmentation"] for ann in thing_annos] |
| thing_segms = [ |
| mask_utils.frPyObjects(segm, data["height"], data["width"]) |
| for segm in thing_segms] |
| thing_segms = [ |
| mask_utils.merge(segm, intersect=False) |
| if isinstance(segm, list) else segm |
| for segm in thing_segms] |
|
|
| annos = [] |
| anno_ids = [] |
| json_path_list = [] |
| segms = [] |
| if self.config.name in ("stuff-only", "stuff-thing"): |
| annos += stuff_annos |
| anno_ids += stuff_anno_indices |
| json_path_list += stuff_path_list |
| segms += stuff_segms |
| if self.config.name in ("thing-only", "stuff-thing"): |
| annos += thing_annos |
| anno_ids += thing_anno_indices |
| json_path_list += thing_path_list |
| segms += thing_segms |
| counts = [ |
| segm["counts"].decode() |
| if isinstance(segm["counts"], bytes) else segm["counts"] |
| for segm in segms] |
| data.update({ |
| "image_id": image_id, |
| "objects": [ |
| { |
| "object_id": ann["id"], |
| "bbox": ann["bbox"][:], |
| "x": ann["bbox"][0], |
| "y": ann["bbox"][1], |
| "w": ann["bbox"][2], |
| "h": ann["bbox"][3], |
| |
| |
| "category_id": ann["category_id"] - 1, |
| "category": catid_to_label[ann["category_id"]], |
| "segmentation": { |
| "path": json_path_list[idx], |
| "index": anno_ids[idx], |
| "counts": counts[idx], |
| "size": segms[idx]["size"], |
| }, |
| } |
| for idx, ann in enumerate(annos) |
| |
| if (ann["category_id"] in catid_to_label.keys() |
| and ann["category_id"] != 0) |
| ], |
| }) |
| yield image_id, data |
|
|