coco_stuff / coco_stuff.py
yiqun's picture
Update coco_stuff.py
c578157 verified
raw
history blame contribute delete
14.3 kB
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset
# script contributor.
#
# 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.
# TODO: Address all TODOs and remove all explanatory comments
"""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__)
# TODO: Add BibTeX citation
# Find for instance the citation on arxiv or on the dataset repo/website
_CITATION = """\
@InProceedings{huggingface:dataset,
title = {A great new dataset},
author={huggingface, Inc.
},
year={2020}
}
"""
# TODO: Add description of the dataset here
# You can copy an official description
_DESCRIPTION = """\
This COCO-Stuff dataset is designed to load coco-stuff only & coco stuff thing.
"""
# TODO: Add a link to an official homepage for the dataset here
_HOMEPAGE = ""
# TODO: Add the licence for the dataset here if you can find it
_LICENSE = ""
# TODO: Add link to the official dataset URLs here
# The HuggingFace Datasets library doesn't host the datasets but only points
# to the original files.
# This can be an arbitrary nested dict/list of URLs
# (see below in `_split_generators` method)
_URLS = {}
VALID_SPLIT_NAMES = ("train", "val")
# TODO: Name of the dataset usually matches the script name with CamelCase
# instead of snake_case
class COCOStuffDataset(datasets.GeneratorBasedBuilder):
"""TODO: Short description of my dataset."""
VERSION = datasets.Version("0.0.1")
# This is an example of a dataset with multiple configurations.
# If you don't want/need to define several sub-sets in your dataset,
# just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes.
# If you need to make complex sub-parts in the datasets with configurable
# options
# You can create your own builder configuration class to store attribute,
# inheriting from datasets.BuilderConfig
BUILDER_CONFIG_CLASS = datasets.BuilderConfig
# You will be able to load one or the other configurations
# in the following list with
# data = datasets.load_dataset('my_dataset', 'first_domain')
# data = datasets.load_dataset('my_dataset', 'second_domain')
BUILDER_CONFIGS = [
# stuff-only
datasets.BuilderConfig(
name="stuff-only", version=VERSION, description="stuff-only."),
# thing-only
datasets.BuilderConfig(
name="thing-only", version=VERSION, description="thing-only."),
# stuff-thing
datasets.BuilderConfig(
name="stuff-thing", version=VERSION, description="stuff-thing"),
]
# It's not mandatory to have a default configuration.
# Just use one if it make sense.
DEFAULT_CONFIG_NAME = "stuff-thing"
def _info(self):
self.config: datasets.BuilderConfig
features = {
# "image": datasets.Image(),
"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(
# This is the description that will appear on the datasets page.
description=_DESCRIPTION,
# This defines the different columns of the dataset and their types
features=features,
# If there's a common (input, target) tuple from the features,
# uncomment supervised_keys line below and specify them.
# They'll be used if as_supervised=True in builder.as_dataset.
# supervised_keys=("sentence", "label"),
# Homepage of the dataset for documentation
homepage=_HOMEPAGE,
# License for the dataset if available
license=_LICENSE,
# Citation for the dataset
citation=_CITATION,
)
def _split_generators(self, dl_manager):
# TODO: This method is tasked with downloading/extracting the data and
# defining the splits depending on the configuration
# If several configurations are possible (listed in BUILDER_CONFIGS),
# the configuration selected by the user is in self.config.name
# dl_manager is a datasets.download.DownloadManager that can be used
# to download and extract URLS. It can accept any type
# or nested list/dict and will give back the same structure with
# the url replaced with path to local files.
# By default the archives will be extracted and a path to a cached
# folder where they are extracted is returned instead of the archive
# urls = _URLS[self.config.name]
# data_dir = dl_manager.download_and_extract(urls)
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
# method parameters are unpacked from `gen_kwargs` as given in
# `_split_generators`
def _generate_examples(self, split: str):
# TODO: This method handles input defined in _split_generators to
# yield (key, example) tuples from the dataset.
# The `key` is for legacy reasons (tfds) and is not important
# in itself, but must be unique for each example.
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)
# image_id_to_thing_metainfo = \
# self.build_image_id_to_metainfo(thing_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_thing_info = image_id_to_thing_metainfo[image_id]
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],
# the segmentation mask starts from 0 to label stuffs
# and things that are not `other` or `unlabelled`
"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)
# category `other` in `stuff` is `thing`
if (ann["category_id"] in catid_to_label.keys()
and ann["category_id"] != 0)
],
})
yield image_id, data