{"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":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nfrom PIL import Image\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\n#for dirname, _, filenames in os.walk('/kaggle/input'):\n#    for filename in filenames:\n#        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session\n\n!pip install https://github.com/CellProfiling/HPA-Cell-Segmentation/archive/master.zip","metadata":{"_uuid":"5f39f727-79f8-46ed-a035-6ae8d4da4f9f","_cell_guid":"c828f3b3-64dd-4649-9d70-01eccd0b015a","collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Get single image that blends all RGBY into RGB\n# Introduce the images as arrays. Can use the function above.\n\ndef get_blended_image(images): \n    # get rgby images for sample\n\n    # blend rgby images into single array\n    blended_array = np.stack(images[:-1], 2)\n\n    # Create PIL Image\n    blended_image = Image.fromarray( np.uint8(blended_array) )\n    return blended_image\n\ndef image_to_arrays(path):\n    \n    image_arrays = list()\n    for image in path:\n        array = np.asarray(Image.open(image))\n        image_arrays.append(array)\n        \n    return image_arrays","metadata":{"_uuid":"e1e06d71-7b02-4dc7-8dc7-ca785153af38","_cell_guid":"ce0a55b1-e6b4-47de-9e16-8015374f5ef4","collapsed":false,"scrolled":true,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import hpacellseg.cellsegmentator as cellsegmentator\nfrom hpacellseg.utils import label_cell, label_nuclei\n\nNUC_MODEL = \"../input/hpacellsegmentatormodelweights/dpn_unet_nuclei_v1.pth\"\nCELL_MODEL = \"../input/hpacellsegmentatormodelweights/dpn_unet_cell_3ch_v1.pth\"\nsegmentator = cellsegmentator.CellSegmentator(\n    NUC_MODEL,\n    CELL_MODEL,\n    scale_factor=0.25,\n    device=\"cuda\",\n    # NOTE: setting padding=True seems to solve most issues that have been encountered\n    #       during our single cell Kaggle challenge.\n    padding=False,\n    multi_channel_model=True,\n)\n\ndef get_masks(imgs, test=True):\n    try:\n        images = [[img[:, :, 0] for img in imgs], \n                  [img[:, :, 3] for img in imgs], \n                  [img[:, :, 2] for img in imgs]]\n    \n        nuc_segmentations = segmentator.pred_nuclei(images[2])\n        cell_segmentations = segmentator.pred_cells(images)\n        cell_masks = []\n        for i in tqdm(range(len(cell_segmentations)), desc='Labeling cells..'):\n            _, cell_mask = label_cell(nuc_segmentations[i], cell_segmentations[i])\n            cell_masks.append(cell_mask)\n        return cell_masks\n    except:\n        raise ValueError('Segmentation failed')","metadata":{"_uuid":"f38cfd9c-35db-4bd6-b254-c1f3061cb564","_cell_guid":"649d0b05-a952-483d-8e53-b8177e907443","collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"channels = ['_red.png', '_blue.png', '_yellow.png', '_green.png']\ntrain_label = pd.read_csv('../input/hpa-single-cell-image-classification/train.csv')\ntrain_data = '../input/hpa-single-cell-image-classification/train'\npaths = [[os.path.join(train_data, train_label.iloc[idx,0])+ channel for channel in channels] for idx in range(len(train_label))]","metadata":{"_uuid":"3db3fbe7-9a83-49df-9b51-f9d6564eea9b","_cell_guid":"f4e9a07c-6ec8-49dd-a196-ec43bec46964","collapsed":false,"scrolled":true,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image = paths[0]\narray = image_to_arrays(image)\nblended_image = get_blended_image(array)\nplt.imshow(blended_image)","metadata":{"_uuid":"d4bf722c-fb55-426c-9f10-e5aaa72b2f57","_cell_guid":"83fdd8e8-4337-47ef-b6c7-064de3d95692","collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"nuclei = array[1]\ncell = array[:-1]\ninter_step = [[i] for i in image[:-1]]\n\n# For nuclei\nnuc_segmentations = segmentator.pred_nuclei([nuclei])\n\n# For full cells\ncell_segmentations = segmentator.pred_cells(inter_step)","metadata":{"_uuid":"b7644f1c-bc21-4124-8882-6ffe108d2df0","_cell_guid":"c148f01d-e533-4e0c-af99-aea6f16deb90","collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# post-processing\nnuclei_mask, cell_mask = label_cell(nuc_segmentations[0], cell_segmentations[0])\nplt.imshow(cell_mask)","metadata":{"_uuid":"f8a20f8d-3283-4a5b-af35-0bb74cbf3820","_cell_guid":"0c497e4a-5f6a-47ff-97ca-1d1f9e676bc6","collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Unique vector of cell_mask numbers\nnumbers = set(np.ravel(cell_mask))\nnumbers.remove(0)\n\nfig = plt.figure(figsize=(25,6*len(numbers)/4))\nindex = 1\n\nfor number in numbers:\n    isolated_cell = np.where(cell_mask==number, cell_mask, 0)\n    ax = fig.add_subplot(len(numbers)//4+1, 4, index)\n    ax.set_title(number, size=20)\n    plt.imshow(isolated_cell)\n    index += 1","metadata":{"_uuid":"5ac0391a-0314-4f67-b805-077aed566fe9","_cell_guid":"79fa2bf2-1b02-4d31-adbb-d55704cc89db","collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"isolated_cell = np.where(cell_mask==1, cell_mask, 0)\nplt.imshow(isolated_cell)","metadata":{"_uuid":"43b0e874-5dee-4314-89fe-99df54ad62ad","_cell_guid":"86e21c2a-70ee-461e-bd1b-2eb3e10335bc","collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"isolated_cell = np.where(cell_mask==2, cell_mask, 0)\nplt.imshow(isolated_cell)","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}