Download create_dataset.py from shijli/davis2017: direct link, hf CLI and curl.
- Browser
- Download file 15.4 kB
-
https://huggingface.co/datasets/shijli/davis2017/resolve/main/create_dataset.py
- Command line
-
hf download hf://datasets/shijli/davis2017/create_dataset.py
-
curl -L -o create_dataset.py https://huggingface.co/datasets/shijli/davis2017/resolve/main/create_dataset.py
15.4 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. | |
| """DAVIS 2017 (semi-supervised video object segmentation), packaged as a Hugging Face dataset. | |
| One row per frame, so a split streams frame by frame and a single frame is one lookup; the rows of | |
| a video are contiguous and in frame order, and carry the video name, so a video is a groupby: | |
| load_dataset('<user>/davis2017', 'semi-supervised') # 60 train / 30 val videos, 480p | |
| Images are the official 480p JPEGs and masks the official annotation PNGs, both copied through | |
| byte for byte. Masks are palette (mode P) PNGs whose pixel value is the object id of the video | |
| (0 = background, 1..N = objects, 255 = void), which is the encoding DAVIS ships and the one its | |
| evaluation reads. Object ids are per video, not classes: object 1 of one video has nothing to do | |
| with object 1 of another. | |
| Only the trainval set is packed. The test-dev and test-challenge sets ship first-frame masks only, | |
| so they cannot be scored offline. | |
| Source data comes from an unpacked DAVIS folder when one is given, and is downloaded from the | |
| official host otherwise: | |
| python create_dataset.py --repo <user>/davis2017 --davis-root ~/Data/datasets/DAVIS --private | |
| DAVIS_ROOT=~/Data/datasets/DAVIS python create_dataset.py --repo <user>/davis2017 | |
| Build without uploading anything, to check the result first: | |
| python create_dataset.py --dry-run --limit 2 | |
| """ | |
| import argparse | |
| import glob | |
| import os | |
| import datasets | |
| import numpy as np | |
| from PIL import Image | |
| _VERSION = "1.0.0" | |
| _HOMEPAGE_URL = "https://davischallenge.org/davis2017/code.html" | |
| _DOWNLOAD_URL = "https://data.vision.ee.ethz.ch/csergi/share/davis/DAVIS-2017-trainval-480p.zip" | |
| _CITATION = """\ | |
| @article{Pont-Tuset_arXiv_2017, | |
| author = {Jordi Pont-Tuset and Federico Perazzi and Sergi Caelles and Pablo Arbel\\'aez and | |
| Alexander Sorkine-Hornung and Luc {Van Gool}}, | |
| title = {The 2017 DAVIS Challenge on Video Object Segmentation}, | |
| journal = {arXiv:1704.00675}, | |
| year = {2017} | |
| } | |
| @inproceedings{Perazzi_CVPR_2016, | |
| author = {Federico Perazzi and Jordi Pont-Tuset and Brian McWilliams and Luc {Van Gool} and | |
| Markus Gross and Alexander Sorkine-Hornung}, | |
| title = {A Benchmark Dataset and Evaluation Methodology for Video Object Segmentation}, | |
| booktitle = {The IEEE Conference on Computer Vision and Pattern Recognition (CVPR)}, | |
| year = {2016} | |
| } | |
| """ | |
| _LICENSE = """\ | |
| DAVIS 2017 is released under CC BY-NC 4.0 (https://creativecommons.org/licenses/by-nc/4.0/). The | |
| videos come from online sources listed in SOURCES.md, which keep their own terms of use. This | |
| packaging adds no rights: use it under those same terms and cite the original work. | |
| """ | |
| _DESCRIPTION = """\ | |
| DAVIS 2017 semi-supervised video object segmentation at 480p, one row per frame: the 60 train and | |
| 30 val videos of the official trainval set with their multi-object masks. Masks are palette PNGs | |
| whose pixel value is the object id within the video (0 background, 255 void). | |
| """ | |
| SEMI_SUPERVISED = "semi-supervised" | |
| # Videos and frames of the official 2017 split lists. Checked against what was built before | |
| # anything is pushed: a stale cache or a half-unpacked root shows up first as wrong counts. | |
| EXPECTED_SIZES = {SEMI_SUPERVISED: {"train": 4209, "validation": 1999}} | |
| EXPECTED_VIDEOS = {SEMI_SUPERVISED: {"train": 60, "validation": 30}} | |
| _VOID_INDEX = 255 | |
| def read_split(root, split): | |
| """The video names of one split, read from the ImageSets list that names it.""" | |
| with open(os.path.join(root, "ImageSets", "2017", split + ".txt")) as f: | |
| return [line.strip() for line in f if line.strip()] | |
| def first_frame_objects(mask_path): | |
| """Number of objects of a video: the largest id of its first-frame mask, void excluded.""" | |
| mask = np.array(Image.open(mask_path)) | |
| ids = mask[mask != _VOID_INDEX] | |
| return int(ids.max()) if ids.size else 0 | |
| class DAVIS2017Config(datasets.BuilderConfig): | |
| """One task view over the DAVIS videos.""" | |
| def __init__(self, resolution="480p", davis_root=None, limit=None, **kwargs): | |
| super().__init__(version=datasets.Version(_VERSION, ""), **kwargs) | |
| self.resolution = resolution | |
| # davis_root and limit are config fields so that they reach the builder and enter the | |
| # config id: a truncated build lands in its own cache directory and is never served back | |
| # to a full one. | |
| self.davis_root = davis_root | |
| self.limit = limit | |
| class DAVIS2017(datasets.GeneratorBasedBuilder): | |
| """DAVIS 2017, one row per frame.""" | |
| BUILDER_CONFIGS = [ | |
| DAVIS2017Config( | |
| name=SEMI_SUPERVISED, | |
| resolution="480p", | |
| description=( | |
| "Semi-supervised video object segmentation on the official trainval set at 480p, " | |
| "the resolution of the official evaluation: 60 train and 30 val videos, every frame " | |
| "with its multi-object mask. The task gives the first-frame mask and scores the rest." | |
| ), | |
| ) | |
| ] | |
| DEFAULT_CONFIG_NAME = SEMI_SUPERVISED | |
| def _info(self): | |
| features = { | |
| "id": datasets.Value("string"), # <video>/<frame file stem>, e.g. bear/00000 | |
| "video": datasets.Value("string"), | |
| "frame": datasets.Value("int32"), # 0-based index in the video | |
| "image": datasets.Image(), | |
| # pixel value = object id in the video, 0 background, 255 void. Palette for viewing only. | |
| "mask": datasets.Image(), | |
| "num_objects": datasets.Value("int32"), # objects of the video (its first-frame mask) | |
| } | |
| return datasets.DatasetInfo( | |
| description=_DESCRIPTION, | |
| features=datasets.Features(features), | |
| supervised_keys=None, | |
| license=_LICENSE, | |
| homepage=_HOMEPAGE_URL, | |
| citation=_CITATION, | |
| ) | |
| def _davis_root(self, dl_manager): | |
| """The unpacked DAVIS folder given on the command line or in the environment, or the official | |
| archive downloaded and extracted on demand.""" | |
| root = self.config.davis_root or os.environ.get("DAVIS_ROOT") | |
| if root: | |
| root = os.path.expanduser(root) | |
| if not os.path.isdir(os.path.join(root, "JPEGImages", self.config.resolution)): | |
| raise FileNotFoundError( | |
| "no JPEGImages/%s under the given DAVIS root: %s" % (self.config.resolution, root) | |
| ) | |
| return root | |
| return os.path.join(dl_manager.download_and_extract(_DOWNLOAD_URL), "DAVIS") | |
| def _split_generators(self, dl_manager): | |
| root = self._davis_root(dl_manager) | |
| limit = self.config.limit | |
| return [ | |
| datasets.SplitGenerator( | |
| name=datasets.Split.TRAIN, gen_kwargs={"root": root, "videos": read_split(root, "train")[:limit]} | |
| ), | |
| datasets.SplitGenerator( | |
| name=datasets.Split.VALIDATION, gen_kwargs={"root": root, "videos": read_split(root, "val")[:limit]} | |
| ), | |
| ] | |
| def _generate_examples(self, root, videos): | |
| res = self.config.resolution | |
| for video in videos: | |
| frames = sorted(glob.glob(os.path.join(root, "JPEGImages", res, video, "*.jpg"))) | |
| masks = sorted(glob.glob(os.path.join(root, "Annotations", res, video, "*.png"))) | |
| stems = [os.path.splitext(os.path.basename(p))[0] for p in frames] | |
| if not frames or stems != [os.path.splitext(os.path.basename(p))[0] for p in masks]: | |
| raise FileNotFoundError("%s: frames and masks do not match one to one" % video) | |
| num_objects = first_frame_objects(masks[0]) | |
| for index, (stem, image, mask) in enumerate(zip(stems, frames, masks, strict=True)): | |
| key = "%s/%s" % (video, stem) | |
| # paths, not decoded images: the Image feature then stores the file bytes unchanged | |
| yield ( | |
| key, | |
| { | |
| "id": key, | |
| "video": video, | |
| "frame": index, | |
| "image": image, | |
| "mask": mask, | |
| "num_objects": num_objects, | |
| }, | |
| ) | |
| ############################## | |
| def check_dataset(dataset, root, samples=8): | |
| """Confirm the masks survived packing as labels: mode P, ids within the video's objects (or void), | |
| paired with the right image, and byte-identical to the source files under ``root`` (when given); | |
| and that videos are whole, contiguous and in frame order.""" | |
| for split, split_ds in dataset.items(): | |
| videos = split_ds["video"] | |
| frames = split_ds["frame"] | |
| seen = [] | |
| for i, (video, frame) in enumerate(zip(videos, frames, strict=True)): | |
| if not seen or seen[-1] != video: | |
| assert video not in seen, "%s: video %s is not contiguous" % (split, video) | |
| assert frame == 0, "%s: video %s does not start at frame 0" % (split, video) | |
| seen.append(video) | |
| else: | |
| assert frame == frames[i - 1] + 1, "%s: %s is out of frame order at row %d" % (split, video, i) | |
| picks = np.linspace(0, len(split_ds) - 1, min(samples, len(split_ds))).astype(int).tolist() | |
| raw = split_ds.cast_column("mask", datasets.Image(decode=False)).cast_column( | |
| "image", datasets.Image(decode=False) | |
| ) | |
| for i in picks: | |
| record, stored = split_ds[i], raw[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 > record["num_objects"] and v != _VOID_INDEX] | |
| assert not bad, "%s[%d]: mask holds ids beyond the video's %d objects: %s" % ( | |
| split, | |
| i, | |
| record["num_objects"], | |
| bad, | |
| ) | |
| assert mask.size == record["image"].size, "%s[%d]: mask and image differ in size" % (split, i) | |
| if root is None: # built from the downloaded archive: no local files to compare with | |
| continue | |
| video, stem = record["id"].split("/") | |
| for column, sub, ext in (("image", "JPEGImages", ".jpg"), ("mask", "Annotations", ".png")): | |
| # the local build keeps file references; push_to_hub embeds those files' bytes as they are | |
| value = stored[column] | |
| data = value["bytes"] if value["bytes"] is not None else open(value["path"], "rb").read() | |
| with open(os.path.join(root, sub, "480p", video, stem + ext), "rb") as f: | |
| assert data == f.read(), "%s[%d]: %s bytes differ from the source" % (split, i, column) | |
| print(" %s: %d frames of %d videos, masks and bytes check out" % (split, len(split_ds), len(seen))) | |
| def parse_args(): | |
| parser = argparse.ArgumentParser("Pack DAVIS 2017 as a Hugging Face dataset") | |
| parser.add_argument("--repo", type=str, default=None, help="dataset repo to push to, e.g. <user>/davis2017") | |
| parser.add_argument( | |
| "--davis-root", | |
| type=str, | |
| default=None, | |
| help="unpacked DAVIS folder (the one holding JPEGImages). Downloads the official archive if unset", | |
| ) | |
| 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 videos 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): | |
| config_name = SEMI_SUPERVISED | |
| print("\n===== %s =====" % config_name) | |
| builder = DAVIS2017( | |
| dataset_name="davis2017", | |
| config_name=config_name, | |
| cache_dir=args.cache_dir, | |
| davis_root=args.davis_root, | |
| limit=args.limit, | |
| ) | |
| builder.download_and_prepare() | |
| dataset = builder.as_dataset() | |
| print(dataset) | |
| actual = {split: len(rows) for split, rows in dataset.items()} | |
| videos = {split: len(set(rows["video"])) for split, rows in dataset.items()} | |
| if args.limit is None and (actual != EXPECTED_SIZES[config_name] or videos != EXPECTED_VIDEOS[config_name]): | |
| raise SystemExit( | |
| "refusing to push: expected %s frames / %s videos, built %s / %s" | |
| % (EXPECTED_SIZES[config_name], EXPECTED_VIDEOS[config_name], actual, videos) | |
| ) | |
| root = args.davis_root or os.environ.get("DAVIS_ROOT") | |
| check_dataset(dataset, os.path.expanduser(root) if root else None) | |
| if args.dry_run: | |
| print("dry run: not pushing") | |
| return | |
| dataset.push_to_hub(args.repo, config_name=config_name, set_default=True, private=args.private) | |
| print("pushed %s to %s" % (config_name, args.repo)) | |
| from huggingface_hub import HfApi | |
| api = HfApi() | |
| if not args.no_push_code: | |
| # the script that produced the parquet, kept in the repo so the packing is reproducible | |
| api.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) | |
| sources = os.path.join(os.path.expanduser(root), "SOURCES.md") if root else None | |
| if sources and os.path.exists(sources): | |
| # where every video comes from: their terms of use apply alongside the DAVIS license | |
| api.upload_file( | |
| path_or_fileobj=sources, | |
| path_in_repo="SOURCES.md", | |
| repo_id=args.repo, | |
| repo_type="dataset", | |
| commit_message="Add the online sources of the DAVIS videos", | |
| ) | |
| print("pushed SOURCES.md to %s" % args.repo) | |
| if __name__ == "__main__": | |
| main(parse_args()) | |