{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Crop PANDA dataset\nHere we create images of equal size for all train/test images.\nThe current approach aims at tiling 16 relevant subimages of size 56x56 pixels into a single 224x224 compound image.\nThis notebook is based on the following public notebooks:\n* https://www.kaggle.com/wouterbulten/getting-started-with-the-panda-dataset  \n* https://www.kaggle.com/iafoss/panda-16x128x128-tiles  ","execution_count":null},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import os\n\n# There are two ways to load the data from the PANDA dataset:\n# Option 1: Load images using openslide\nimport openslide\n# Option 2: Load images using skimage (requires that tifffile is installed)\nimport skimage.io\n\n# General packages\nimport pandas as pd\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport PIL\nfrom IPython.display import Image, display\nfrom collections import Counter\nimport os\n\nimport cv2\nimport skimage.io\nfrom tqdm.notebook import tqdm\nimport zipfile","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Location of the training images\ndataDir = '/kaggle/input/prostate-cancer-grade-assessment/train_images'\ndataTestDir = '/kaggle/input/prostate-cancer-grade-assessment/test_images'\n\n# Location of training labels\ntrainLabels = pd.read_csv('/kaggle/input/prostate-cancer-grade-assessment/train.csv').set_index('image_id')\ntestDF = pd.read_csv('/kaggle/input/prostate-cancer-grade-assessment/test.csv').set_index('image_id')\n\n# Output cropped images\ncropDir = '/kaggle/working/cropped_train_images/'\ncropTestDir = '/kaggle/working/cropped_test_images/'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"if not os.path.exists(cropDir):\n    os.mkdir(cropDir)\n    \nif not os.path.exists(cropTestDir):\n    os.mkdir(cropTestDir)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"# Parameters for cropping images\ncropPx= 56\ncropN = 16\nassert np.sqrt(cropN) == round(np.sqrt(cropN))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def tile(img):\n    result = []\n    shape = img.shape\n    pad0,pad1 = (cropPx - shape[0]%cropPx)%cropPx, (cropPx - shape[1]%cropPx)%cropPx\n    img = np.pad(img,[[pad0//2,pad0-pad0//2],[pad1//2,pad1-pad1//2],[0,0]],\n                constant_values=255)\n    \n    img = img.reshape(img.shape[0]//cropPx,cropPx,img.shape[1]//cropPx,cropPx,3)\n    img = img.transpose(0,2,1,3,4).reshape(-1,cropPx,cropPx,3)\n    \n    if len(img) < cropN:\n        img = np.pad(img,[[0,cropN-len(img)],[0,0],[0,0],[0,0]],constant_values=255)\n    idxs = np.argsort(img.reshape(img.shape[0],-1).sum(-1))[:cropN]\n    img = img[idxs]\n    for i in range(len(img)):\n        result.append({'img':img[i], 'idx':i})\n    return result","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"nbCol = int(np.sqrt(cropN))\nnames = [x.split('.')[0] for x in os.listdir(dataDir)]\nfor name in tqdm(names):\n    img = skimage.io.MultiImage(os.path.join(dataDir+'/',name+'.tiff'))[-1]\n    tiles = tile(img)\n    stackImg = np.vstack([np.hstack([tiles[nbCol*col + row]['img'] for row in range(nbCol)])\n               for col in range(nbCol)])\n    cv2.imwrite(cropDir+name+'.png', stackImg)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# If notebook is running on actual test data\nif os.path.exists(dataTestDir):\n    names = [x.split('.')[0] for x in os.listdir(dataTestDir)]\n    for name in tqdm(names):\n        img = skimage.io.MultiImage(os.path.join(dataTestDir+'/',name+'.tiff'))[-1]\n        tiles = tile(img)\n        stackImg = np.vstack([np.hstack([tiles[nbCol*col + row]['img'] for row in range(nbCol)])\n                   for col in range(nbCol)])\n        cv2.imwrite(cropTestDir+name+'.png', stackImg)","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}