"""Download the COCO 2017 images referenced by the unified PACO-LVIS records. PACO-LVIS annotations are distributed without images. Each record stores the COCO file name (image_path = datasets/COCO//.jpg) and the official COCO URL (source_image_metadata.coco_url). This tool fetches only the referenced images, skips files that already exist, and checks each download decodes to the recorded width and height. python code/tools/fetch_coco_images.py --splits val # 2,410 images python code/tools/fetch_coco_images.py # all 57,643 images (~9 GB) Alternatively download train2017.zip and val2017.zip from https://cocodataset.org/#download and extract them into datasets/COCO/ (about 19 GB, includes images PACO does not use). """ import argparse from concurrent.futures import ThreadPoolExecutor, as_completed import json from pathlib import Path import sys import time import urllib.request from PIL import Image, ImageOps from tqdm import tqdm ROOT = Path(__file__).resolve().parents[2] SPLITS = ('train', 'val', 'test') def wanted(root, splits): for split in splits: with (root / 'datasets/unified/PACO-LVIS' / (split + '.jsonl')).open(encoding='utf-8') as stream: for line in stream: record = json.loads(line) yield (record['image_path'], record['source_image_metadata']['coco_url'], record['width'], record['height']) def download(root, path, url, width, height, attempts=3): target = root / path if target.is_file(): return 'present' target.parent.mkdir(parents=True, exist_ok=True) partial = target.with_suffix('.part') for attempt in range(attempts): try: # images.cocodataset.org has no valid HTTPS certificate; use the recorded URL as is. # Each download is then checked to decode at the annotated size. with urllib.request.urlopen(url, timeout=60) as response: partial.write_bytes(response.read()) with Image.open(partial) as image: if ImageOps.exif_transpose(image).size != (width, height): raise ValueError(f'{path}: size differs from annotation') partial.rename(target) return 'downloaded' except Exception: partial.unlink(missing_ok=True) if attempt == attempts - 1: raise time.sleep(2 ** attempt) def main(): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('--root', type=Path, default=ROOT) parser.add_argument('--splits', nargs='+', choices=SPLITS, default=list(SPLITS)) parser.add_argument('--workers', type=int, default=16) args = parser.parse_args() root = args.root.resolve() jobs = list(wanted(root, args.splits)) counts, failures = {'present': 0, 'downloaded': 0}, [] with ThreadPoolExecutor(args.workers) as pool: futures = {pool.submit(download, root, *job): job[0] for job in jobs} for future in tqdm(as_completed(futures), total=len(futures), desc='COCO images', mininterval=3, ascii=True): try: counts[future.result()] += 1 except Exception as error: # report every failure; never silently skip failures.append(f'{futures[future]}: {error}') print(json.dumps({'requested': len(jobs), **counts, 'failed': len(failures)}, indent=2)) for failure in failures: print('FAILED', failure, file=sys.stderr) raise SystemExit(1 if failures else 0) if __name__ == '__main__': main()