zooblastlbz commited on
Commit
92c0cb6
1 Parent(s): 4bb8a4b

Create resize.py

Browse files
Files changed (1) hide show
  1. resize.py +93 -0
resize.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from io import BytesIO
2
+
3
+ import ujson
4
+ import webdataset as wds
5
+ from PIL import Image
6
+ from tqdm import tqdm
7
+ import os
8
+ import albumentations as A
9
+ import cv2
10
+ def load_text(txt: bytes):
11
+ return txt.decode()
12
+
13
+
14
+ def load_image(jpg):
15
+ return Image.open(BytesIO(jpg)).convert('RGB')
16
+
17
+
18
+ load_mapping = {
19
+ 'jpg': load_image,
20
+ 'txt': load_text
21
+ }
22
+
23
+
24
+ def valid_image(img):
25
+ return min(img.size) >= 64
26
+
27
+
28
+ def resize_img(img, max_size=224):
29
+ width, height = img.size
30
+
31
+ if max(width,height) > max_size:
32
+ if width < height:
33
+ new_height = max_size
34
+ new_width = int(max_size * width / height)
35
+ else:
36
+ new_width = max_size
37
+ new_height = int(max_size * height / width)
38
+ img = img.resize((new_width, new_height), Image.BICUBIC)
39
+
40
+ # Pad the image to make it square
41
+ width, height = img.size
42
+ new_img = Image.new("RGB", (max_size, max_size), (255, 255, 255))
43
+ new_img.paste(img, ((max_size - width) // 2, (max_size - height) // 2))
44
+
45
+ return new_img
46
+
47
+
48
+
49
+
50
+ def img_to_meta(img):
51
+ width, height = img.size
52
+ return {
53
+ 'width': width,
54
+ 'height': height
55
+ }
56
+
57
+
58
+ def get_image(img):
59
+ if not valid_image(img):
60
+ return None, None
61
+
62
+ img=resize_img(img)
63
+ img_stream = BytesIO()
64
+ img.save(img_stream, format='jpeg')
65
+
66
+ img_stream.seek(0)
67
+ return img_stream.read(), ujson.dumps(img_to_meta(img))
68
+
69
+ change_mapping = {
70
+ 'jpg': get_image
71
+ }
72
+
73
+ def func(wds_dataset_str, **kwargs):
74
+ ds = wds.WebDataset(wds_dataset_str, shardshuffle=False).map_dict(**load_mapping).map_dict(**change_mapping).to_tuple(
75
+ 'jpg', 'txt')
76
+ dl = wds.WebLoader(ds, batch_size=None, num_workers=48, prefetch_factor=16, **kwargs)
77
+
78
+
79
+ writer = wds.ShardWriter('target_path/%05d.tar', 10000)
80
+ for img, txt in tqdm(dl):
81
+ img_str, meta = img
82
+ if img_str is None:
83
+ continue
84
+ sample = {
85
+ '__key__': f'{writer.count:08}',
86
+ 'jpg': img_str,
87
+ 'txt': txt,
88
+ 'json': meta
89
+ }
90
+ writer.write(sample)
91
+
92
+ if __name__ == '__main__':
93
+ func('path_to_origin_data')