{"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 - Exploratory Data Analysis\n\nQuick Exploratory Data Analysis for [HuBMAP: Hacking the Kidney](https://www.kaggle.com/c/hubmap-kidney-segmentation) challenge\n\nThe HuBMAP data used in this hackathon includes 11 fresh frozen and 9 Formalin Fixed Paraffin Embedded (FFPE) PAS kidney images. Glomeruli FTU annotations exist for all 20 tissue samples; some of these will be shared for training, and others will be used to judge submissions.","metadata":{}},{"cell_type":"markdown","source":"![](https://storage.googleapis.com/kaggle-competitions/kaggle/22990/logos/header.png)","metadata":{}},{"cell_type":"markdown","source":"<a id=\"top\"></a>\n\n<div class=\"list-group\" id=\"list-tab\" role=\"tablist\">\n<h3 class=\"list-group-item list-group-item-action active\" data-toggle=\"list\" style='color:white; background:#EAA6D1; border:0' role=\"tab\" aria-controls=\"home\"><center>Quick Navigation</center></h3>\n\n* [1. Basic Data Exploration](#1)\n* [2. Image and Masks Visualizations](#2)\n* [3. Metadata Analysis](#3)","metadata":{}},{"cell_type":"code","source":"!pip install -q -U pip\n!pip install -q -U seaborn","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-12-05T14:10:27.714290Z","iopub.execute_input":"2022-12-05T14:10:27.714671Z","iopub.status.idle":"2022-12-05T14:10:46.073080Z","shell.execute_reply.started":"2022-12-05T14:10:27.714639Z","shell.execute_reply":"2022-12-05T14:10:46.072183Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"1\"></a>\n<h2 style='background:#EAA6D1; border:0; color:white'><center>Basic Data Exploration<center><h2>","metadata":{}},{"cell_type":"code","source":"import os\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sn\nimport cv2\nimport tifffile","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-12-05T14:10:46.076731Z","iopub.execute_input":"2022-12-05T14:10:46.077106Z","iopub.status.idle":"2022-12-05T14:10:46.907156Z","shell.execute_reply.started":"2022-12-05T14:10:46.077067Z","shell.execute_reply":"2022-12-05T14:10:46.906386Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"BASE_PATH = \"../input/hubmap-kidney-segmentation/\"\nTRAIN_PATH = os.path.join(BASE_PATH, \"train\")\n\nprint(os.listdir(BASE_PATH))","metadata":{"execution":{"iopub.status.busy":"2022-12-05T14:10:46.908611Z","iopub.execute_input":"2022-12-05T14:10:46.909025Z","iopub.status.idle":"2022-12-05T14:10:46.916478Z","shell.execute_reply.started":"2022-12-05T14:10:46.908989Z","shell.execute_reply":"2022-12-05T14:10:46.915487Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Train masks","metadata":{}},{"cell_type":"markdown","source":"**train.csv** contains the unique IDs for each image, as well as an RLE-encoded representation of the mask for the objects in the image. See the evaluation tab for details of the RLE encoding scheme.","metadata":{}},{"cell_type":"code","source":"df_train = pd.read_csv(\n    os.path.join(BASE_PATH, \"train.csv\")\n)\ndf_train","metadata":{"execution":{"iopub.status.busy":"2022-12-05T14:10:46.918536Z","iopub.execute_input":"2022-12-05T14:10:46.919020Z","iopub.status.idle":"2022-12-05T14:10:47.362465Z","shell.execute_reply.started":"2022-12-05T14:10:46.918983Z","shell.execute_reply":"2022-12-05T14:10:47.361492Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Submission df","metadata":{}},{"cell_type":"code","source":"df_sub = pd.read_csv(\n    os.path.join(BASE_PATH, \"sample_submission.csv\"))\ndf_sub","metadata":{"execution":{"iopub.status.busy":"2022-12-05T14:10:47.365734Z","iopub.execute_input":"2022-12-05T14:10:47.366078Z","iopub.status.idle":"2022-12-05T14:10:47.383727Z","shell.execute_reply.started":"2022-12-05T14:10:47.366040Z","shell.execute_reply":"2022-12-05T14:10:47.383011Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Number of samples","metadata":{}},{"cell_type":"code","source":"print(f\"Number of train images: {df_train.shape[0]}\")\nprint(f\"Number of test images: {df_sub.shape[0]}\")","metadata":{"execution":{"iopub.status.busy":"2022-12-05T14:10:47.387655Z","iopub.execute_input":"2022-12-05T14:10:47.388009Z","iopub.status.idle":"2022-12-05T14:10:47.396710Z","shell.execute_reply.started":"2022-12-05T14:10:47.387976Z","shell.execute_reply":"2022-12-05T14:10:47.396053Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Train and test metadata","metadata":{}},{"cell_type":"markdown","source":"**HuBMAP-20-dataset_information.csv** contains additional information (including anonymized patient data) about each image.","metadata":{}},{"cell_type":"code","source":"df_info = pd.read_csv(\n    os.path.join(BASE_PATH, \"HuBMAP-20-dataset_information.csv\")\n)\ndf_info.sample(3)","metadata":{"execution":{"iopub.status.busy":"2022-12-05T14:10:47.398312Z","iopub.execute_input":"2022-12-05T14:10:47.398718Z","iopub.status.idle":"2022-12-05T14:10:47.424862Z","shell.execute_reply.started":"2022-12-05T14:10:47.398674Z","shell.execute_reply":"2022-12-05T14:10:47.424025Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Utility functions","metadata":{}},{"cell_type":"code","source":"# https://www.kaggle.com/paulorzp/rle-functions-run-lenght-encode-decode\ndef rle2mask(mask_rle, shape):\n    '''\n    mask_rle: run-length as string formated (start length)\n    shape: (width,height) of array to return \n    Returns numpy array, 1 - mask, 0 - background\n\n    '''\n    s = mask_rle.split()\n    starts, lengths = [\n        np.asarray(x, dtype=int) for x in (s[0:][::2], s[1:][::2])\n    ]\n    starts -= 1\n    ends = starts + lengths\n    img = np.zeros(shape[0] * shape[1], dtype=np.uint8)\n    for lo, hi in zip(starts, ends):\n        img[lo : hi] = 1\n    return img.reshape(shape).T\n\n\ndef read_image(image_id, scale=None, verbose=1):\n    image = tifffile.imread(\n        os.path.join(BASE_PATH, f\"train/{image_id}.tiff\")\n    )\n    if len(image.shape) == 5:\n        image = image.squeeze().transpose(1, 2, 0)\n    \n    mask = rle2mask(\n        df_train[df_train[\"id\"] == image_id][\"encoding\"].values[0], \n        (image.shape[1], image.shape[0])\n    )\n    \n    if verbose:\n        print(f\"[{image_id}] Image shape: {image.shape}\")\n        print(f\"[{image_id}] Mask shape: {mask.shape}\")\n    \n    if scale:\n        new_size = (image.shape[1] // scale, image.shape[0] // scale)\n        image = cv2.resize(image, new_size)\n        mask = cv2.resize(mask, new_size)\n        \n        if verbose:\n            print(f\"[{image_id}] Resized Image shape: {image.shape}\")\n            print(f\"[{image_id}] Resized Mask shape: {mask.shape}\")\n        \n    return image, mask\n\n\ndef read_test_image(image_id, scale=None, verbose=1):\n    image = tifffile.imread(\n        os.path.join(BASE_PATH, f\"test/{image_id}.tiff\")\n    )\n    if len(image.shape) == 5:\n        image = image.squeeze().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\n\n\ndef plot_image_and_mask(image, mask, image_id):\n    plt.figure(figsize=(16, 10))\n    \n    plt.subplot(1, 3, 1)\n    plt.imshow(image)\n    plt.title(f\"Image {image_id}\", fontsize=18)\n    \n    plt.subplot(1, 3, 2)\n    plt.imshow(image)\n    plt.imshow(mask, cmap=\"hot\", alpha=0.5)\n    plt.title(f\"Image {image_id} + mask\", fontsize=18)    \n    \n    plt.subplot(1, 3, 3)\n    plt.imshow(mask, cmap=\"hot\")\n    plt.title(f\"Mask\", fontsize=18)    \n    \n    plt.show()\n    \n    \ndef plot_grid_image_with_mask(image, mask):\n    plt.figure(figsize=(16, 16))\n    \n    w_len = image.shape[0]\n    h_len = image.shape[1]\n    \n    min_len = min(w_len, h_len)\n    w_start = (w_len - min_len) // 2\n    h_start = (h_len - min_len) // 2\n    \n    plt.imshow(image[w_start : w_start + min_len, h_start : h_start + min_len])\n    plt.imshow(\n        mask[w_start : w_start + min_len, h_start : h_start + min_len], cmap=\"hot\", alpha=0.5,\n    )\n    plt.axis(\"off\")\n            \n    plt.show()\n    \n\ndef plot_slice_image_and_mask(image, mask, start_h, end_h, start_w, end_w):\n    plt.figure(figsize=(16, 5))\n    \n    sub_image = image[start_h:end_h, start_w:end_w, :]\n    sub_mask = mask[start_h:end_h, start_w:end_w]\n    \n    plt.subplot(1, 3, 1)\n    plt.imshow(sub_image)\n    plt.axis(\"off\")\n    \n    plt.subplot(1, 3, 2)\n    plt.imshow(sub_image)\n    plt.imshow(sub_mask, cmap=\"hot\", alpha=0.5)\n    plt.axis(\"off\")\n    \n    plt.subplot(1, 3, 3)\n    plt.imshow(sub_mask, cmap=\"hot\")\n    plt.axis(\"off\")\n    \n    plt.show()","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-12-05T14:10:47.426520Z","iopub.execute_input":"2022-12-05T14:10:47.426870Z","iopub.status.idle":"2022-12-05T14:10:47.454927Z","shell.execute_reply.started":"2022-12-05T14:10:47.426834Z","shell.execute_reply":"2022-12-05T14:10:47.453969Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"2\"></a>\n<h2 style='background:#EAA6D1; border:0; color:white'><center>Image and Masks Visualizations<center><h2>","metadata":{}},{"cell_type":"code","source":"# small_ids = [\n#     \"0486052bb\", \"095bf7a1f\", \"1e2425f28\", \"2f6ecfcdf\",\n#     \"54f2eec69\", \"aaa6a05cc\", \"cb2d976f4\", \"e79de561c\"\n# ]\nsmall_ids = [\n    \"0486052bb\"\n]\nsmall_images = []\nsmall_masks = []\n\nfor small_id in small_ids:\n    tmp_image, tmp_mask = read_image(small_id, scale=20, verbose=0)\n    small_images.append(tmp_image)\n    small_masks.append(tmp_mask)","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-12-05T14:10:47.456656Z","iopub.execute_input":"2022-12-05T14:10:47.457436Z","iopub.status.idle":"2022-12-05T14:11:08.000960Z","shell.execute_reply.started":"2022-12-05T14:10:47.457385Z","shell.execute_reply":"2022-12-05T14:11:08.000044Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Train images","metadata":{}},{"cell_type":"code","source":"plt.figure(figsize=(16, 16))\nfor ind, (tmp_id, tmp_image) in enumerate(zip(small_ids, small_images)):\n    plt.subplot(3, 3, ind + 1)\n    plt.imshow(tmp_image)\n    plt.axis(\"off\")","metadata":{"execution":{"iopub.status.busy":"2022-12-05T14:11:08.002465Z","iopub.execute_input":"2022-12-05T14:11:08.002828Z","iopub.status.idle":"2022-12-05T14:11:08.277498Z","shell.execute_reply.started":"2022-12-05T14:11:08.002775Z","shell.execute_reply":"2022-12-05T14:11:08.276539Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Train images + masks","metadata":{}},{"cell_type":"code","source":"plt.figure(figsize=(16, 16))\nfor ind, (tmp_id, tmp_image, tmp_mask) in enumerate(zip(small_ids, small_images, small_masks)):\n    plt.subplot(3, 3, ind + 1)\n    plt.imshow(tmp_image)\n    plt.imshow(tmp_mask, cmap=\"hot\", alpha=0.5)\n    plt.axis(\"off\")","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-12-05T14:11:08.278944Z","iopub.execute_input":"2022-12-05T14:11:08.279302Z","iopub.status.idle":"2022-12-05T14:11:08.640170Z","shell.execute_reply.started":"2022-12-05T14:11:08.279257Z","shell.execute_reply":"2022-12-05T14:11:08.639107Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Test images","metadata":{}},{"cell_type":"code","source":"plt.figure(figsize=(16, 11))\nfor ind, (tmp_id, tmp_image) in enumerate(zip(small_ids, small_images)):\n    plt.subplot(2, 3, ind + 1)\n    plt.imshow(tmp_image)\n    plt.axis(\"off\")","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-12-05T14:11:08.641639Z","iopub.execute_input":"2022-12-05T14:11:08.641931Z","iopub.status.idle":"2022-12-05T14:11:08.876708Z","shell.execute_reply.started":"2022-12-05T14:11:08.641894Z","shell.execute_reply":"2022-12-05T14:11:08.875794Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 0486052bb","metadata":{}},{"cell_type":"code","source":"image_id = \"0486052bb\"\nimage, mask = read_image(image_id, 2)","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-12-05T14:11:08.878390Z","iopub.execute_input":"2022-12-05T14:11:08.879080Z","iopub.status.idle":"2022-12-05T14:11:27.698516Z","shell.execute_reply.started":"2022-12-05T14:11:08.879035Z","shell.execute_reply":"2022-12-05T14:11:27.697557Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_image_and_mask(image, mask, image_id)","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-12-05T14:11:27.699660Z","iopub.execute_input":"2022-12-05T14:11:27.700002Z","iopub.status.idle":"2022-12-05T14:11:59.338730Z","shell.execute_reply.started":"2022-12-05T14:11:27.699972Z","shell.execute_reply":"2022-12-05T14:11:59.337926Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_slice_image_and_mask(image, mask, 5000, 7500, 2500, 5000)\nplot_slice_image_and_mask(image, mask, 5250, 5720, 3500, 4000)\nplot_slice_image_and_mask(image, mask, 5375, 5575, 3650, 3850)","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-12-05T14:11:59.340081Z","iopub.execute_input":"2022-12-05T14:11:59.340499Z","iopub.status.idle":"2022-12-05T14:12:01.926525Z","shell.execute_reply.started":"2022-12-05T14:11:59.340466Z","shell.execute_reply":"2022-12-05T14:12:01.925710Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_grid_image_with_mask(image, mask)","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-12-05T14:12:01.927648Z","iopub.execute_input":"2022-12-05T14:12:01.928121Z","iopub.status.idle":"2022-12-05T14:12:25.299550Z","shell.execute_reply.started":"2022-12-05T14:12:01.928084Z","shell.execute_reply":"2022-12-05T14:12:25.297915Z"},"trusted":true},"execution_count":null,"outputs":[]}]}