{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Intro\n\n* This kernel lets you efficiently convert all images from their tensor format into RGB images, then save them as 400x400 JPEGs inside two zip files (`train` and `test`).\n* Feel free to customize this kernel as you wish. You can change the shape and extension of the final output image by changing the input arguments to `convert_to_rgb` and `build_new_df`.\n\n### Notes\n\n* In a previous version (V11) of the kernel, I claimed that the `rxrx.io.load_site_as_rgb` function was inefficient, and tried to provide a faster solution. It turns out I did not input the correct argument, so it was instead fetching the images directly from Google Storage; with the correct argument, the speed was comparable. **My sincere apologies for misleading everyone.**\n\n\n### Updates\n\n* V13: Changed output image size to 400 px instead of 224.\n\n### Sources\n\n* Found out about the loading functions from this kernel: https://www.kaggle.com/jesucristo/quick-visualization-eda"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import os\nimport sys\nimport zipfile\n\nimport numpy as np\nimport pandas as pd\nimport cv2\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\nfrom PIL import Image","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Preliminary"},{"metadata":{},"cell_type":"markdown","source":"We need to also import rxrx in order to convert the tensors into images."},{"metadata":{"trusted":true},"cell_type":"code","source":"!git clone https://github.com/recursionpharma/rxrx1-utils\nsys.path.append('rxrx1-utils')\nimport rxrx.io as rio","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Will need those folders later for storing our jpegs."},{"metadata":{"trusted":true},"cell_type":"code","source":"for folder in ['train', 'test']:\n    os.makedirs(folder)\n\n!ls","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"train_df = pd.read_csv('../input/train.csv')\ntest_df = pd.read_csv('../input/test.csv')\nprint(train_df.shape)\nprint(test_df.shape)\ntrain_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.tail()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Saving as JPEG"},{"metadata":{"trusted":true},"cell_type":"code","source":"def convert_to_rgb(df, split, resize=True, new_size=400, extension='jpeg'):\n    N = df.shape[0]\n\n    for i in tqdm(range(N)):\n        code = df['id_code'][i]\n        experiment = df['experiment'][i]\n        plate = df['plate'][i]\n        well = df['well'][i]\n\n        for site in [1, 2]:\n            save_path = f'{split}/{code}_s{site}.{extension}'\n\n            im = rio.load_site_as_rgb(\n                split, experiment, plate, well, site, \n                base_path='../input/'\n            )\n            im = im.astype(np.uint8)\n            im = Image.fromarray(im)\n            \n            if resize:\n                im = im.resize((new_size, new_size), resample=Image.BILINEAR)\n            \n            im.save(save_path)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"convert_to_rgb(train_df, 'train')\nconvert_to_rgb(test_df, 'test')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Zip everything"},{"metadata":{"trusted":true},"cell_type":"code","source":"def zip_and_remove(path):\n    ziph = zipfile.ZipFile(f'{path}.zip', 'w', zipfile.ZIP_DEFLATED)\n    \n    for root, dirs, files in os.walk(path):\n        for file in tqdm(files):\n            file_path = os.path.join(root, file)\n            ziph.write(file_path)\n            os.remove(file_path)\n    \n    ziph.close()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"zip_and_remove('train')\nzip_and_remove('test')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Create new labels\n\nSince our data is now \"duplicated\" (as in, we have separated the sites), we have to also duplicate our labels."},{"metadata":{"trusted":true},"cell_type":"code","source":"def build_new_df(df, extension='jpeg'):\n    new_df = pd.concat([df, df])\n    new_df['filename'] = pd.concat([\n        df['id_code'].apply(lambda string: string + f'_s1.{extension}'),\n        df['id_code'].apply(lambda string: string + f'_s2.{extension}')\n    ])\n    \n    return new_df\n\n\nnew_train = build_new_df(train_df)\nnew_test = build_new_df(test_df)\n\nnew_train.to_csv('new_train.csv', index=False)\nnew_test.to_csv('new_test.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Remove the rxrx1 utils\n\nNeed to remove those, otherwise we will have an error when saving."},{"metadata":{"trusted":true},"cell_type":"code","source":"!rm -r rxrx1-utils","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.4","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}