Datasets:
Download create_dataset.py from shijli/voc2012: direct link, hf CLI and curl.
- Browser
- Download file 20.8 kB
-
https://huggingface.co/datasets/shijli/voc2012/resolve/main/create_dataset.py
- Command line
-
hf download hf://datasets/shijli/voc2012/create_dataset.py
-
curl -L -o create_dataset.py https://huggingface.co/datasets/shijli/voc2012/resolve/main/create_dataset.py
20.8 kB
| # coding=utf-8 | |
| # | |
| # 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. | |
| """PASCAL VOC 2012, packaged as one Hugging Face dataset with a config per task view. | |
| The point of this script is a single reusable VOC on the Hub rather than a per-project copy, so | |
| the images are packed once and the task views are configs over them: | |
| load_dataset('<user>/voc2012', 'segmentation') # 1464 train / 1449 val | |
| load_dataset('<user>/voc2012', 'segmentation_aug') # 10582 train / 1449 val (SBD masks) | |
| load_dataset('<user>/voc2012', 'detection') # 5717 train / 5823 val | |
| Masks are published as palette (mode P) PNGs whose pixel value IS the class id, with 255 marking | |
| the void border, which is the encoding VOC ships and the one every segmentation codebase already | |
| expects. That matters: several VOC mirrors on the Hub store masks as RGB, which forces every | |
| consumer to reverse the VOC colormap before the labels mean anything, and silently corrupts the | |
| labels for anyone who forgets. Masks that are already mode P are copied through byte for byte; | |
| the SBD masks, which ship as mode L with the same values, get the standard palette attached so | |
| that every config decodes the same way. | |
| VOC 2012 publishes no test labels, so there is no test split to build. | |
| Source data comes from an unpacked VOC2012 folder when one is given, and is downloaded from the | |
| official host otherwise: | |
| python create_dataset.py --repo <user>/voc2012 --voc-root ~/Data/datasets/VOC2012 --private | |
| VOC2012_ROOT=~/Data/datasets/VOC2012 python create_dataset.py --repo <user>/voc2012 | |
| Build without uploading anything, to check the result first: | |
| python create_dataset.py --dry-run --limit 20 | |
| The 'segmentation_aug' config needs a SegmentationClassAug/ directory in the VOC root, and stops | |
| with an error when it is absent. Those masks are not part of VOC: they come from SBD (Hariharan | |
| et al.), and are cited separately in that config's description. | |
| """ | |
| import argparse | |
| import io | |
| import os | |
| import xml.etree.ElementTree as ET | |
| import datasets | |
| import numpy as np | |
| from PIL import Image | |
| _VERSION = "1.0.0" | |
| _HOMEPAGE_URL = "http://host.robots.ox.ac.uk/pascal/VOC/voc2012/" | |
| _DOWNLOAD_URL = "http://host.robots.ox.ac.uk/pascal/VOC/voc2012/VOCtrainval_11-May-2012.tar" | |
| _CITATION = """\ | |
| @article{everingham2015pascal, | |
| title={The Pascal Visual Object Classes Challenge: A Retrospective}, | |
| author={Everingham, Mark and Eslami, S. M. Ali and Van Gool, Luc and | |
| Williams, Christopher K. I. and Winn, John and Zisserman, Andrew}, | |
| journal={International Journal of Computer Vision}, | |
| volume={111}, number={1}, pages={98--136}, year={2015} | |
| } | |
| """ | |
| _CITATION_SBD = """\ | |
| @inproceedings{hariharan2011semantic, | |
| title={Semantic Contours from Inverse Detectors}, | |
| author={Hariharan, Bharath and Arbelaez, Pablo and Bourdev, Lubomir and | |
| Maji, Subhransu and Malik, Jitendra}, | |
| booktitle={International Conference on Computer Vision (ICCV)}, | |
| year={2011} | |
| } | |
| """ | |
| _LICENSE = """\ | |
| The PASCAL VOC 2012 images were collected from flickr and remain under the copyright of their | |
| respective owners. They are distributed for non-commercial research and educational use only, | |
| under the terms of the VOC challenge (http://host.robots.ox.ac.uk/pascal/VOC/voc2012/). This | |
| packaging adds no rights: use it under those same terms and cite the original work. | |
| """ | |
| _DESCRIPTION = """\ | |
| PASCAL VOC 2012, packed once with a config per task view: semantic segmentation on the official | |
| 1464/1449 split, semantic segmentation on the SBD-augmented 10582/1449 split, and object | |
| detection on the 5717/5823 split. Segmentation masks are palette PNGs whose pixel value is the | |
| class id, with 255 for the void border. | |
| """ | |
| # Background is class 0 and is not an annotated category, so it heads the list and the 20 VOC | |
| # categories follow in their canonical order. 255 is the void border, which is outside this list | |
| # by construction: it marks pixels excluded from both training and scoring, not a 22nd class. | |
| _CLASSES = [ | |
| "background", | |
| "aeroplane", | |
| "bicycle", | |
| "bird", | |
| "boat", | |
| "bottle", | |
| "bus", | |
| "car", | |
| "cat", | |
| "chair", | |
| "cow", | |
| "diningtable", | |
| "dog", | |
| "horse", | |
| "motorbike", | |
| "person", | |
| "pottedplant", | |
| "sheep", | |
| "sofa", | |
| "train", | |
| "tvmonitor", | |
| ] | |
| _VOID_INDEX = 255 | |
| def voc_colormap(n=256): | |
| """ | |
| The VOC palette: the bit-shuffle that turns a class id into its display color. Used only to | |
| attach a palette to masks that arrive without one, never to read labels back out of colors. | |
| """ | |
| cmap = np.zeros((n, 3), dtype=np.uint8) | |
| for i in range(n): | |
| r = g = b = 0 | |
| c = i | |
| for j in range(8): | |
| r |= ((c >> 0) & 1) << (7 - j) | |
| g |= ((c >> 1) & 1) << (7 - j) | |
| b |= ((c >> 2) & 1) << (7 - j) | |
| c >>= 3 | |
| cmap[i] = [r, g, b] | |
| return cmap | |
| _PALETTE = voc_colormap().flatten().tolist() | |
| def read_split(root, task_dir, split): | |
| """The image ids of one split, read from the ImageSets list that names it.""" | |
| path = os.path.join(root, "ImageSets", task_dir, split + ".txt") | |
| with open(path) as f: | |
| # the detection lists carry a trailing +1/-1 label column, the segmentation lists do not | |
| return [line.split()[0] for line in f if line.strip()] | |
| def mask_value(path): | |
| """ | |
| What to hand the Image feature for a mask: the file itself when it already carries the VOC | |
| palette, so its bytes are published unchanged, and PNG bytes of a re-tagged copy when it does | |
| not. PIL opens lazily, so reading the mode here costs a header parse rather than a decode. | |
| The bytes are encoded here rather than by handing over the PIL image, because the Image | |
| feature encodes a mode P image as uncompressed TIFF: its fallback list covers 1/L/LA/RGB/RGBA | |
| and everything else goes to TIFF, which turns a 2 KB mask into a 142 KB one. Writing the PNG | |
| here keeps the mask a mask. | |
| """ | |
| with Image.open(path) as mask: | |
| if mask.mode == "P": | |
| return path | |
| # SBD masks are mode L holding the same class ids. Re-tagging the array as mode P and | |
| # attaching the VOC palette makes every config decode identically, and moves no pixel: | |
| # fromarray reads the ids straight across, and a palette is display metadata. | |
| tagged = Image.fromarray(np.array(mask.convert("L")), mode="P") | |
| tagged.putpalette(_PALETTE) | |
| encoded = io.BytesIO() | |
| tagged.save(encoded, format="PNG", optimize=True) | |
| return {"path": os.path.basename(path), "bytes": encoded.getvalue()} | |
| def parse_annotation(path): | |
| """ | |
| The objects of one detection annotation. Boxes are kept exactly as the XML gives them, which | |
| is 1-indexed and inclusive on both corners; converting here would hide that from anyone who | |
| compares against the original files. | |
| Returned as a dict of parallel lists, which is the shape a datasets Sequence of a struct | |
| stores, so a consumer reads record['objects']['bbox'] rather than iterating dicts. | |
| """ | |
| root = ET.parse(path).getroot() | |
| size = root.find("size") | |
| def field(obj, name, default=None): | |
| found = obj.find(name) | |
| return default if found is None else found.text | |
| objects = {"label": [], "bbox": [], "difficult": [], "truncated": [], "pose": []} | |
| for obj in root.findall("object"): | |
| box = obj.find("bndbox") | |
| objects["label"].append(obj.find("name").text) | |
| objects["bbox"].append([float(box.find(c).text) for c in ("xmin", "ymin", "xmax", "ymax")]) | |
| objects["difficult"].append(field(obj, "difficult", "0") == "1") | |
| objects["truncated"].append(field(obj, "truncated", "0") == "1") | |
| objects["pose"].append(field(obj, "pose", "Unspecified")) | |
| return int(size.find("width").text), int(size.find("height").text), objects | |
| class VOC2012Config(datasets.BuilderConfig): | |
| """One task view over the VOC images.""" | |
| def __init__(self, task, mask_dir=None, voc_root=None, limit=None, **kwargs): | |
| super().__init__(version=datasets.Version(_VERSION, ""), **kwargs) | |
| self.task = task | |
| self.mask_dir = mask_dir | |
| # voc_root and limit are set from the command line rather than in the config list. Being | |
| # config fields is what makes them reach the builder at all, and it puts them in the | |
| # config id, which is what keeps their builds apart: a truncated build lands in its own | |
| # cache directory and can never be served back to a full one. Doing this by patching the | |
| # split generators instead leaves a 6-row dataset sitting in the full build's cache, with | |
| # a recorded split size that agrees with itself, so the next full run reuses it and | |
| # uploads six rows. | |
| self.voc_root = voc_root | |
| self.limit = limit | |
| SEGMENTATION = "segmentation" | |
| SEGMENTATION_AUG = "segmentation_aug" | |
| DETECTION = "detection" | |
| # The split sizes VOC and SBD define. Checked against what was built before anything is pushed, | |
| # because every way a build can go wrong quietly -- a stale cache, a half-populated VOC root, a | |
| # split list read from the wrong task directory -- shows up first as the wrong number of rows. | |
| EXPECTED_SIZES = { | |
| SEGMENTATION: {"train": 1464, "validation": 1449}, | |
| SEGMENTATION_AUG: {"train": 10582, "validation": 1449}, | |
| DETECTION: {"train": 5717, "validation": 5823}, | |
| } | |
| class VOC2012(datasets.GeneratorBasedBuilder): | |
| """PASCAL VOC 2012 with one config per task view.""" | |
| BUILDER_CONFIGS = [ | |
| VOC2012Config( | |
| name=SEGMENTATION, | |
| task="segmentation", | |
| mask_dir="SegmentationClass", | |
| description=( | |
| "Semantic segmentation on the official split: 1464 train and 1449 val images with " | |
| "their VOC masks. This is the split the standard segmentation protocols evaluate on." | |
| ), | |
| ), | |
| VOC2012Config( | |
| name=SEGMENTATION_AUG, | |
| task="segmentation", | |
| mask_dir="SegmentationClassAug", | |
| description=( | |
| "Semantic segmentation on the SBD-augmented split: 10582 train images with SBD " | |
| "masks, evaluated against the same 1449 val images with their official VOC masks. " | |
| "The train masks come from SBD, not VOC: " + _CITATION_SBD | |
| ), | |
| ), | |
| VOC2012Config( | |
| name=DETECTION, | |
| task="detection", | |
| description="Object detection on the 5717 train / 5823 val split, with the VOC boxes.", | |
| ), | |
| ] | |
| DEFAULT_CONFIG_NAME = SEGMENTATION | |
| def _info(self): | |
| common = {"id": datasets.Value("string"), "image": datasets.Image()} | |
| if self.config.task == "segmentation": | |
| features = { | |
| **common, | |
| # pixel value = class id, 255 = void. The palette is for viewing only. | |
| "mask": datasets.Image(), | |
| } | |
| else: | |
| features = { | |
| **common, | |
| "width": datasets.Value("int32"), | |
| "height": datasets.Value("int32"), | |
| "objects": datasets.Sequence( | |
| { | |
| "label": datasets.ClassLabel(names=_CLASSES[1:]), | |
| "bbox": datasets.Sequence(datasets.Value("float32"), length=4), | |
| "difficult": datasets.Value("bool"), | |
| "truncated": datasets.Value("bool"), | |
| "pose": datasets.Value("string"), | |
| } | |
| ), | |
| } | |
| return datasets.DatasetInfo( | |
| description=_DESCRIPTION, | |
| features=datasets.Features(features), | |
| supervised_keys=None, | |
| license=_LICENSE, | |
| homepage=_HOMEPAGE_URL, | |
| citation=_CITATION, | |
| ) | |
| def _voc_root(self, dl_manager): | |
| """ | |
| The unpacked VOC2012 folder: the one given on the command line or in the environment, or | |
| the official archive downloaded and extracted on demand. | |
| """ | |
| root = self.config.voc_root or os.environ.get("VOC2012_ROOT") | |
| if root: | |
| root = os.path.expanduser(root) | |
| if not os.path.isdir(os.path.join(root, "JPEGImages")): | |
| raise FileNotFoundError("no JPEGImages/ under the given VOC root: %s" % root) | |
| return root | |
| extracted = dl_manager.download_and_extract(_DOWNLOAD_URL) | |
| return os.path.join(extracted, "VOCdevkit", "VOC2012") | |
| def _split_generators(self, dl_manager): | |
| root = self._voc_root(dl_manager) | |
| limit = self.config.limit | |
| if self.config.name == DETECTION: | |
| return [ | |
| datasets.SplitGenerator( | |
| name=datasets.Split.TRAIN, | |
| gen_kwargs={"root": root, "ids": read_split(root, "Main", "train")[:limit]}, | |
| ), | |
| datasets.SplitGenerator( | |
| name=datasets.Split.VALIDATION, | |
| gen_kwargs={"root": root, "ids": read_split(root, "Main", "val")[:limit]}, | |
| ), | |
| ] | |
| val_ids = read_split(root, "Segmentation", "val") | |
| official = os.path.join(root, "SegmentationClass") | |
| if self.config.name == SEGMENTATION: | |
| train_ids, train_masks = read_split(root, "Segmentation", "train"), official | |
| else: | |
| aug_dir = os.path.join(root, self.config.mask_dir) | |
| if not os.path.isdir(aug_dir): | |
| raise FileNotFoundError( | |
| "the %s config needs %s/, which is an SBD download and not part of VOC" % (SEGMENTATION_AUG, aug_dir) | |
| ) | |
| # the augmented train set is every id SBD covers that is not held out for validation | |
| held_out = set(val_ids) | |
| aug_ids = sorted(f[: -len(".png")] for f in os.listdir(aug_dir) if f.endswith(".png")) | |
| train_ids, train_masks = [i for i in aug_ids if i not in held_out], aug_dir | |
| return [ | |
| datasets.SplitGenerator( | |
| name=datasets.Split.TRAIN, gen_kwargs={"root": root, "ids": train_ids[:limit], "mask_dir": train_masks} | |
| ), | |
| # val is scored against the official VOC masks in both configs, so that a model trained | |
| # on the augmented set is still measured on the same ground truth as one that was not | |
| datasets.SplitGenerator( | |
| name=datasets.Split.VALIDATION, gen_kwargs={"root": root, "ids": val_ids[:limit], "mask_dir": official} | |
| ), | |
| ] | |
| def _generate_examples(self, root, ids, mask_dir=None): | |
| for image_id in ids: | |
| image = os.path.join(root, "JPEGImages", image_id + ".jpg") | |
| if mask_dir is not None: | |
| yield image_id, { | |
| "id": image_id, | |
| "image": image, | |
| "mask": mask_value(os.path.join(mask_dir, image_id + ".png")), | |
| } | |
| else: | |
| width, height, objects = parse_annotation(os.path.join(root, "Annotations", image_id + ".xml")) | |
| yield image_id, {"id": image_id, "image": image, "width": width, "height": height, "objects": objects} | |
| ############################## | |
| def check_segmentation(dataset, samples=8): | |
| """ | |
| Confirm the masks survived packing as labels rather than as pictures: still mode P, still | |
| holding class ids and the void marker, and still paired with the right image. Cheap enough to | |
| run on every build, and it catches the one failure that would otherwise reach the Hub silently. | |
| """ | |
| for split, split_ds in dataset.items(): | |
| for i in range(min(samples, len(split_ds))): | |
| record = split_ds[i] | |
| mask = record["mask"] | |
| values = np.unique(np.array(mask)) | |
| assert mask.mode == "P", "%s[%d]: mask is mode %s, expected P" % (split, i, mask.mode) | |
| bad = [v for v in values if v > len(_CLASSES) - 1 and v != _VOID_INDEX] | |
| assert not bad, "%s[%d]: mask holds values outside the class ids: %s" % (split, i, bad) | |
| assert mask.size == record["image"].size, "%s[%d]: mask and image differ in size" % (split, i) | |
| print(" %s: %d examples, masks check out" % (split, len(split_ds))) | |
| def parse_args(): | |
| parser = argparse.ArgumentParser("Pack PASCAL VOC 2012 as a Hugging Face dataset") | |
| parser.add_argument("--repo", type=str, default=None, help="dataset repo to push to, e.g. <user>/voc2012") | |
| parser.add_argument( | |
| "--voc-root", | |
| type=str, | |
| default=None, | |
| help="unpacked VOC2012 folder (the one holding JPEGImages). Downloads the official archive if unset", | |
| ) | |
| parser.add_argument( | |
| "--configs", | |
| type=str, | |
| nargs="+", | |
| choices=[SEGMENTATION, SEGMENTATION_AUG, DETECTION], | |
| default=[SEGMENTATION, SEGMENTATION_AUG, DETECTION], | |
| help="which configs to build", | |
| ) | |
| parser.add_argument( | |
| "--no-push-code", action="store_true", help="skip uploading this script alongside the data" | |
| ) | |
| parser.add_argument("--private", action="store_true", help="create the repo as private") | |
| parser.add_argument("--dry-run", action="store_true", help="build and verify locally, push nothing") | |
| parser.add_argument( | |
| "--limit", type=int, default=None, help="build only the first N ids of each split, for a check. Needs --dry-run" | |
| ) | |
| parser.add_argument("--cache-dir", type=str, default=None, help="where to build, defaults to the datasets cache") | |
| args = parser.parse_args() | |
| if args.repo is None and not args.dry_run: | |
| parser.error("give --repo to upload, or --dry-run to build locally") | |
| if args.limit is not None and not args.dry_run: | |
| parser.error("--limit builds a truncated dataset, which is only useful with --dry-run") | |
| return args | |
| def main(args): | |
| for config_name in args.configs: | |
| print("\n===== %s =====" % config_name) | |
| builder = VOC2012( | |
| dataset_name="voc2012", | |
| config_name=config_name, | |
| cache_dir=args.cache_dir, | |
| voc_root=args.voc_root, | |
| limit=args.limit, | |
| ) | |
| builder.download_and_prepare() | |
| dataset = builder.as_dataset() | |
| print(dataset) | |
| expected = EXPECTED_SIZES[config_name] | |
| actual = {split: len(rows) for split, rows in dataset.items()} | |
| if args.limit is None and actual != expected: | |
| raise SystemExit("refusing to push %s: expected %s, built %s" % (config_name, expected, actual)) | |
| if builder.config.task == "segmentation": | |
| check_segmentation(dataset) | |
| if args.dry_run: | |
| print("dry run: not pushing %s" % config_name) | |
| continue | |
| # the config a bare load_dataset(repo) resolves to, so the common case needs no config | |
| # name. Passed as None rather than False for the others: False actively clears the flag, | |
| # so pushing a second config would take the default away from the first. | |
| default = True if config_name == VOC2012.DEFAULT_CONFIG_NAME else None | |
| dataset.push_to_hub(args.repo, config_name=config_name, set_default=default, private=args.private) | |
| print("pushed %s to %s" % (config_name, args.repo)) | |
| if not args.dry_run and not args.no_push_code: | |
| # the script that produced the parquet, kept in the repo so the packing is reproducible | |
| # and auditable rather than something that happened once on one machine | |
| from huggingface_hub import HfApi | |
| HfApi().upload_file( | |
| path_or_fileobj=os.path.abspath(__file__), | |
| path_in_repo="create_dataset.py", | |
| repo_id=args.repo, | |
| repo_type="dataset", | |
| commit_message="Add the script that packs this dataset", | |
| ) | |
| print("pushed create_dataset.py to %s" % args.repo) | |
| if __name__ == "__main__": | |
| main(parse_args()) | |