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')