File size: 1,858 Bytes
92b4fa8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Read frame WebDatasets using each dataset's manifest."""
import json
import io
from pathlib import Path

import numpy as np
from PIL import Image
import webdataset as wds


def decode_sample(sample):
    result = dict(sample)
    meta = json.loads(sample['json'])
    result['json'] = meta
    for modality, field in meta['components'].items():
        if field is None:
            continue
        data = io.BytesIO(sample[field])
        if field.endswith('.npy'):
            result[field] = np.load(data, allow_pickle=False)
        elif modality == 'depth':
            # Generic RGB image decoding would destroy 16-bit depth precision.
            with Image.open(data) as image:
                result[field] = np.array(image)
        else:
            with Image.open(data) as image:
                result[field] = image.convert('RGB')
    return result


def dataset(directory, split='train', decode=True):
    directory = Path(directory)
    manifest = json.loads((directory / 'manifest.json').read_text())
    if manifest['status'] != 'complete':
        raise RuntimeError(f'Dataset is not complete: {manifest["status"]}')
    shards = [str(directory / s['path']) for s in manifest['shards']
              if s['path'].split('/')[1] == split]
    if not shards:
        raise ValueError(f'No shards for split {split!r}')
    result = wds.WebDataset(shards, shardshuffle=False)
    return result.map(decode_sample) if decode else result


if __name__ == '__main__':
    import argparse
    p = argparse.ArgumentParser()
    p.add_argument('directory')
    p.add_argument('--split', default='train')
    args = p.parse_args()
    sample = next(iter(dataset(args.directory, args.split)))
    meta = sample['json']
    print('Fields:', list(sample))
    print('Dataset:', meta['dataset'], 'scene:', meta['scene_id'], 'frame:', meta['frame_id'])