{"cells":[{"metadata":{},"cell_type":"markdown","source":"This code resizes \"test\" and \"train\" images based on their longer sides found under PATH into DEST with the same directory hierarchy.\nYou can give multiple sizes to create in one run as demonstrated in the commented line.\nThe code is based on fastai's [script](https://github.com/fastai/imagenet-fast/blob/master/scripts/resize.py)."},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"from PIL import Image\nfrom pathlib import Path\nfrom concurrent.futures import ProcessPoolExecutor\nimport multiprocessing\ncpus = multiprocessing.cpu_count()\ncpus = min(48,cpus-1)\n\nds_path = Path('/media/nofreewill/Datasets_nvme/kaggle/bms-molecular-translation')\nPATH = ds_path\nDEST = ds_path/'resized'\n#szs = (224, 512, 1024, )\nszs = (224, )\n\ndef resize_img(im, fn, sz):\n    new_fn = DEST/str(sz)/fn.relative_to(PATH)\n    new_fn.parent.mkdir(parents=True, exist_ok=True)\n    w,h = im.size\n    ratio = max(h/sz,w/sz)\n    im = im.resize((int(w/ratio), int(h/ratio)), resample=Image.BICUBIC)\n    im.save(new_fn)\n\ndef resizes(fn):\n    im = Image.open(fn)\n    for sz in szs: resize_img(im, fn, sz)\n\ndef resize_imgs(p):\n    files = p.rglob('**/*.png')\n    with ProcessPoolExecutor(cpus) as e: e.map(resizes, files)\n\n\nfor ds in ('test','train'): resize_imgs(PATH/ds)","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}