{"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_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Hubmap image conversion\n\n> Convert tiff files to zarr files with scale factor\n\n***\n\n- V10: Adding test set","metadata":{}},{"cell_type":"code","source":"# Install zarr and load packages\n!pip install -qq zarr\nimport cv2, zarr, tifffile\nimport matplotlib.pyplot as plt, numpy as np, pandas as pd\nfrom pathlib import Path","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def read_image(image_id, path, scale=None, verbose=1):\n    \"Load images with ID from path\"\n    \n    try: \n        image = tifffile.imread(path/f\"train/{image_id}.tiff\")\n    except:\n        image = tifffile.imread(path/f\"test/{image_id}.tiff\")\n    \n    if len(image.shape) == 5:\n        image = image.squeeze().transpose(1, 2, 0)\n    elif image.shape[0] == 3:\n        image = image.transpose(1, 2, 0)\n    \n    if verbose:\n        print(f\"[{image_id}] Image shape: {image.shape}\")\n    \n    if scale:\n        new_size = (image.shape[1] // scale, image.shape[0] // scale)\n        image = cv2.resize(image, new_size)\n        \n        if verbose:\n            print(f\"[{image_id}] Resized Image shape: {image.shape}\")\n        \n    return image","metadata":{"_kg_hide-input":false,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Settings","metadata":{}},{"cell_type":"code","source":"scale = 2\n\npath = Path('/kaggle/input/hubmap-kidney-segmentation')\ndf_train = pd.read_csv(path/\"train.csv\")\ndf_sample = pd.read_csv(path/\"sample_submission.csv\")\ng_out = zarr.group(f'/kaggle/working/images_scale{scale}')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Loop over images","metadata":{}},{"cell_type":"code","source":"for idx in df_sample['id'].tolist()+df_train['id'].tolist():\n    img = read_image(idx, path, scale=scale)\n    g_out[idx] = img\n    print(g_out[idx].info)\n    shape = g_out[idx].shape\n    \n    plt.imshow(cv2.resize(img, dsize=(512, 512*shape[0]//shape[1])))\n    plt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}