File size: 3,764 Bytes
f66a12f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
"""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)