KeypointEstimation / coco_download.py
huuthientran's picture
Add files using upload-large-folder tool
f66a12f verified
Raw History Blame Contribute Delete
3.76 kB
"""Load annotation-only COCO TSVs and download original images on demand."""
import argparse
from concurrent.futures import ThreadPoolExecutor
import hashlib
import io
import json
import os
from pathlib import Path
import tempfile
from urllib.request import urlopen
from PIL import Image
class CocoKeypointsDataset:
def __init__(self, root, images, positive_only=False):
self.root, self.images = Path(root), Path(images)
index = 'train.positive.annotations.tsv.lineidx' if positive_only else 'train.annotations.tsv.lineidx'
self.offsets = [int(x) for x in (self.root / index).read_text().splitlines()]
def __len__(self):
return len(self.offsets)
def annotation(self, index):
with (self.root / 'train.annotations.tsv').open('rb') as stream:
stream.seek(self.offsets[index])
key, payload = stream.readline().split(b'\t', 1)
row = json.loads(payload)
if int(key) != row['image']['id']:
raise ValueError('Image ID mismatch')
return row
def ensure_image(self, row):
meta = row['image']
filename = meta['file_name']
if Path(filename).name != filename:
raise ValueError('Unsafe image filename')
target = self.images / 'train2017' / filename
def validate(data):
if hashlib.sha256(data).hexdigest() != meta['sha256']:
raise ValueError(f'Image checksum mismatch: {filename}')
with Image.open(io.BytesIO(data)) as im:
im.load()
if im.size != (meta['width'], meta['height']):
raise ValueError(f'Image dimensions mismatch: {filename}')
if target.exists():
validate(target.read_bytes())
return target
url = 'https://s3.amazonaws.com/images.cocodataset.org/train2017/' + filename
with urlopen(url, timeout=60) as response:
data = response.read()
validate(data)
target.parent.mkdir(parents=True, exist_ok=True)
fd, temporary = tempfile.mkstemp(prefix='.' + filename, dir=target.parent)
try:
with os.fdopen(fd, 'wb') as stream:
stream.write(data)
os.replace(temporary, target)
finally:
Path(temporary).unlink(missing_ok=True)
return target
def __getitem__(self, index):
annotation = self.annotation(index)
path = self.ensure_image(annotation)
with Image.open(path) as source:
image = source.convert('RGB')
image.info.pop('exif', None)
return {'image': image, 'annotation': annotation, 'image_path': str(path)}
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--root', type=Path, default=Path(__file__).resolve().parent / 'coco')
parser.add_argument('--images', type=Path, required=True)
parser.add_argument('--positive-only', action='store_true')
parser.add_argument('--workers', type=int, default=8)
parser.add_argument('--limit', type=int, default=0, help='0 downloads all selected images')
args = parser.parse_args()
if args.workers < 1 or args.limit < 0:
parser.error('workers must be positive and limit nonnegative')
dataset = CocoKeypointsDataset(args.root, args.images, args.positive_only)
count = min(args.limit, len(dataset)) if args.limit else len(dataset)
def download(index):
return dataset.ensure_image(dataset.annotation(index))
with ThreadPoolExecutor(max_workers=args.workers) as pool:
for i, path in enumerate(pool.map(download, range(count)), 1):
if i % 1000 == 0 or i == count:
print(f'{i}/{count} images ready', flush=True)