File size: 2,121 Bytes
92c0cb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
90
91
92
93
from io import BytesIO

import ujson
import webdataset as wds
from PIL import Image
from tqdm import tqdm
import os
import albumentations as A
import cv2
def load_text(txt: bytes):
    return txt.decode()


def load_image(jpg):
    return Image.open(BytesIO(jpg)).convert('RGB')


load_mapping = {
    'jpg': load_image,
    'txt': load_text
}


def valid_image(img):
    return min(img.size) >= 64


def resize_img(img, max_size=224):
    width, height = img.size

    if max(width,height) > max_size:
        if width < height:
            new_height = max_size
            new_width = int(max_size * width / height)
        else:
            new_width = max_size
            new_height = int(max_size * height / width)
        img = img.resize((new_width, new_height), Image.BICUBIC)

    # Pad the image to make it square
    width, height = img.size
    new_img = Image.new("RGB", (max_size, max_size), (255, 255, 255))
    new_img.paste(img, ((max_size - width) // 2, (max_size - height) // 2))

    return new_img




def img_to_meta(img):
    width, height = img.size
    return {
        'width': width,
        'height': height
    }


def get_image(img):
    if not valid_image(img):
        return None, None

    img=resize_img(img)
    img_stream = BytesIO()
    img.save(img_stream, format='jpeg')

    img_stream.seek(0)
    return img_stream.read(), ujson.dumps(img_to_meta(img))

change_mapping = {
    'jpg': get_image
}

def func(wds_dataset_str, **kwargs):
    ds = wds.WebDataset(wds_dataset_str, shardshuffle=False).map_dict(**load_mapping).map_dict(**change_mapping).to_tuple(
        'jpg', 'txt')
    dl = wds.WebLoader(ds, batch_size=None, num_workers=48, prefetch_factor=16, **kwargs)


    writer = wds.ShardWriter('target_path/%05d.tar', 10000)
    for img, txt in tqdm(dl):
        img_str, meta = img
        if img_str is None:
            continue
        sample = {
            '__key__': f'{writer.count:08}',
            'jpg': img_str,
            'txt': txt,
            'json': meta
        }
        writer.write(sample)

if __name__ == '__main__':
    func('path_to_origin_data')