{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":61446,"databundleVersionId":6962461,"sourceType":"competition"}],"dockerImageVersionId":30579,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"<center style=\"border-radius:10px;\npadding: 3rem 2rem;\nborder: 3px solid #BA2525;\n\">\n<h1 style=\"color:#BA2525; \nfont-size:3.0rem;\nmargin:0;\n\">Hacking the Human Vasculature in 3D</h1>\n<h2 style=\"color:#BA2525; \nfont-size:2.0rem;\nmargin-top:1rem;\nmargin-bottom:2.5rem;\n\">MONAI + Animations</h2>\n<a href=\"https://kaggle.com/shreydan\" style=\"color: white;\nbackground-color: #BA2525;\nborder-radius: 25px;\npadding: 1rem 1.5rem;\ntext-decoration: none;\n\">@shreydan</a>\n</center>","metadata":{}},{"cell_type":"markdown","source":"# About the Competition\n<div style=\"width:100%;height:0;border-bottom: 3px solid #AD2626;margin-bottom: 1rem;\"></div>\n\nThis competition dataset comprises high-resolution 3D images of several kidneys together with 3D segmentation masks of their vasculature. \n\nTask: Create segmentation masks for the kidney datasets in the test set.\n\n\n## About the Dataset\n<div style=\"width:100%;height:0;border-bottom: 3px solid #AF3A25;margin-bottom: 1rem;\"></div>\n\nThe kidney images were obtained through Hierarchical Phase-Contrast Tomography (HiP-CT) imaging. HiP-CT is an imaging technique that obtains high-resolution (from 1.4 micrometers - 50 micrometers resolution) 3D data from ex vivo organs. \n\n#### [Nature Article: Imaging intact human organs with local resolution of cellular structures using hierarchical phase-contrast tomography](https://www.nature.com/articles/s41592-021-01317-x)\n\n##### **Article Abstract**\nImaging intact human organs from the organ to the cellular scale in three dimensions is a goal of biomedical imaging. To meet this challenge, we developed hierarchical phase-contrast tomography (HiP-CT), an X-ray phase propagation technique using the European Synchrotron Radiation Facility (ESRF)’s Extremely Brilliant Source (EBS). The spatial coherence of the ESRF-EBS combined with our beamline equipment, sample preparation and scanning developments enabled us to perform non-destructive, three-dimensional (3D) scans with hierarchically increasing resolution at any location in whole human organs. We applied HiP-CT to image five intact human organ types: brain, lung, heart, kidney and spleen. HiP-CT provided a structural overview of each whole organ followed by multiple higher-resolution volumes of interest, capturing organotypic functional units and certain individual specialized cells within intact human organs. We demonstrate the potential applications of HiP-CT through quantification and morphometry of glomeruli in an intact human kidney and identification of regional changes in the tissue architecture in a lung from a deceased donor with coronavirus disease 2019 (COVID-19).\n\n```\nWalsh, C.L., Tafforeau, P., Wagner, W.L. et al. \nImaging intact human organs with local resolution of cellular structures using hierarchical phase-contrast tomography. \nNat Methods 18, 1532–1541 (2021). \nhttps://doi.org/10.1038/s41592-021-01317-x\n```","metadata":{}},{"cell_type":"markdown","source":"# Installs & Imports\n<div style=\"width:100%;height:0;border-bottom: 3px solid #B25025;margin-bottom: 1rem;\"></div>","metadata":{}},{"cell_type":"code","source":"!pip install monai --quiet","metadata":{"execution":{"iopub.status.busy":"2023-11-12T20:07:43.472503Z","iopub.execute_input":"2023-11-12T20:07:43.472993Z","iopub.status.idle":"2023-11-12T20:07:57.061916Z","shell.execute_reply.started":"2023-11-12T20:07:43.472940Z","shell.execute_reply":"2023-11-12T20:07:57.060420Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport torch\nfrom pathlib import Path\nfrom PIL import Image\nfrom tqdm.auto import tqdm\nfrom monai.data import PILReader\nimport monai.transforms as MT\n\nfrom matplotlib import animation, rc\nrc('animation', html='jshtml')","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-11-12T20:07:57.063795Z","iopub.execute_input":"2023-11-12T20:07:57.064184Z","iopub.status.idle":"2023-11-12T20:08:44.262915Z","shell.execute_reply.started":"2023-11-12T20:07:57.064151Z","shell.execute_reply":"2023-11-12T20:08:44.261788Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Dataset & Methods\n<div style=\"width:100%;height:0;border-bottom: 3px solid #B56625;margin-bottom: 1rem;\"></div>","metadata":{}},{"cell_type":"code","source":"df = pd.read_csv('/kaggle/input/blood-vessel-segmentation/train_rles.csv')\ndf['subset']=df['id'].map(lambda x:'_'.join(x.split('_')[:-1]))\ndf.head()","metadata":{"execution":{"iopub.status.busy":"2023-11-12T20:08:44.266037Z","iopub.execute_input":"2023-11-12T20:08:44.266791Z","iopub.status.idle":"2023-11-12T20:08:45.247145Z","shell.execute_reply.started":"2023-11-12T20:08:44.266758Z","shell.execute_reply":"2023-11-12T20:08:45.245716Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df['subset'].value_counts(dropna=False)","metadata":{"execution":{"iopub.status.busy":"2023-11-12T20:08:45.248573Z","iopub.execute_input":"2023-11-12T20:08:45.248896Z","iopub.status.idle":"2023-11-12T20:08:45.263631Z","shell.execute_reply.started":"2023-11-12T20:08:45.248870Z","shell.execute_reply":"2023-11-12T20:08:45.262504Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def prepare_df(im_dir='kidney_1_dense',lb_dir='kidney_1_dense'):\n    df = pd.read_csv('/kaggle/input/blood-vessel-segmentation/train_rles.csv')\n    base_dir = Path('/kaggle/input/blood-vessel-segmentation/train')\n    subset_df = df[df.id.str.startswith(lb_dir)].reset_index(drop=True)\n    subset_df['slice_id'] = subset_df['id'].map(lambda x:x.split('_')[-1]) \n    subset_df['image'] = subset_df['slice_id'].map(lambda x: base_dir / im_dir / 'images' / f'{x}.tif')\n    subset_df['label'] = subset_df['slice_id'].map(lambda x: base_dir / lb_dir / 'labels' / f'{x}.tif')\n    return subset_df","metadata":{"execution":{"iopub.status.busy":"2023-11-12T20:08:45.265034Z","iopub.execute_input":"2023-11-12T20:08:45.266004Z","iopub.status.idle":"2023-11-12T20:08:45.273674Z","shell.execute_reply.started":"2023-11-12T20:08:45.265947Z","shell.execute_reply":"2023-11-12T20:08:45.272558Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"transforms = MT.Compose([\n    MT.LoadImageD(keys=['image','label'],reader=PILReader()),\n    MT.EnsureChannelFirstD(keys=['image','label']),\n    MT.NormalizeIntensityD(keys=['image']),\n    MT.ResizeD(keys=['image','label'],spatial_size=(384,384))\n])","metadata":{"execution":{"iopub.status.busy":"2023-11-12T20:08:45.275236Z","iopub.execute_input":"2023-11-12T20:08:45.276605Z","iopub.status.idle":"2023-11-12T20:08:45.293785Z","shell.execute_reply.started":"2023-11-12T20:08:45.276566Z","shell.execute_reply":"2023-11-12T20:08:45.292162Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def show(sample_df,idx):\n    sample = sample_df[sample_df['slice_id']==str.zfill(f'{idx}',4)]\n    sample = transforms({\n        'image':sample['image'],\n        'label':sample['label']\n    })\n    image = sample['image'].permute(1,2,0)\n    label = sample['label'].permute(1,2,0)\n    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4))\n    ax1.imshow(image,cmap='gray')\n    ax2.imshow(label,cmap='gray')\n    ax1.axis('off')\n    ax2.axis('off')\n    plt.subplots_adjust(wspace=0.05)\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2023-11-12T20:08:45.295596Z","iopub.execute_input":"2023-11-12T20:08:45.296158Z","iopub.status.idle":"2023-11-12T20:08:45.304373Z","shell.execute_reply.started":"2023-11-12T20:08:45.296121Z","shell.execute_reply":"2023-11-12T20:08:45.303366Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def animate(sample_df,id_range):\n    fig, [ax1,ax2] = plt.subplots(1,2)\n    ax1.axis('off')\n    ax2.axis('off')\n    images = []\n    for i in tqdm(id_range):\n        \n        sample = sample_df[sample_df['slice_id']==str.zfill(f'{i}',4)]\n        sample = transforms({\n            'image':sample['image'],\n            'label':sample['label']\n        })\n        image = sample['image'].permute(1,2,0)\n        label = sample['label'].permute(1,2,0)\n        im1 = ax1.imshow(image, animated=True, cmap='gray')\n        im2 = ax2.imshow(label, animated=True, cmap='gray')\n        if i==0:\n            ax1.imshow(image, cmap='gray')\n            ax2.imshow(label, cmap='gray')\n        images.append([im1,im2])\n\n\n    ani = animation.ArtistAnimation(fig, images, interval=50, blit=True,\n                                    repeat_delay=1000)\n    plt.close()\n    return ani","metadata":{"execution":{"iopub.status.busy":"2023-11-12T20:08:45.305562Z","iopub.execute_input":"2023-11-12T20:08:45.306073Z","iopub.status.idle":"2023-11-12T20:08:45.318131Z","shell.execute_reply.started":"2023-11-12T20:08:45.306042Z","shell.execute_reply":"2023-11-12T20:08:45.316813Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Kidney-1 Dense\n<div style=\"width:100%;height:0;border-bottom: 3px solid #B77D25;margin-bottom: 1rem;\"></div>\n\n> The whole of a right kidney at 50um resolution. The entire 3D arterial vascular tree has been densely segmented, down to two generations from the glomeruli (i.e. the capillary bed). Uses beamline BM05.","metadata":{}},{"cell_type":"code","source":"dense_1_df = prepare_df(im_dir='kidney_1_dense',lb_dir='kidney_1_dense')\nshow(dense_1_df,1234)","metadata":{"execution":{"iopub.status.busy":"2023-11-12T20:08:45.320944Z","iopub.execute_input":"2023-11-12T20:08:45.321338Z","iopub.status.idle":"2023-11-12T20:08:46.297331Z","shell.execute_reply.started":"2023-11-12T20:08:45.321308Z","shell.execute_reply":"2023-11-12T20:08:46.296097Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"animate(dense_1_df,id_range=range(1200,1300))","metadata":{"execution":{"iopub.status.busy":"2023-11-12T17:45:04.928948Z","iopub.execute_input":"2023-11-12T17:45:04.929328Z","iopub.status.idle":"2023-11-12T17:45:18.420209Z","shell.execute_reply.started":"2023-11-12T17:45:04.929300Z","shell.execute_reply":"2023-11-12T17:45:18.418963Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Kidney-1 VOI\n<div style=\"width:100%;height:0;border-bottom: 3px solid #BA9525;margin-bottom: 1rem;\"></div>\n\n> A high-resolution subset of kidney_1, at 5.2um resolution.","metadata":{}},{"cell_type":"code","source":"kidney_1_voi_df = prepare_df(im_dir='kidney_1_voi',lb_dir='kidney_1_voi')\nshow(kidney_1_voi_df,454)","metadata":{"execution":{"iopub.status.busy":"2023-11-12T17:45:33.130572Z","iopub.execute_input":"2023-11-12T17:45:33.130976Z","iopub.status.idle":"2023-11-12T17:45:33.905801Z","shell.execute_reply.started":"2023-11-12T17:45:33.130949Z","shell.execute_reply":"2023-11-12T17:45:33.904657Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"animate(kidney_1_voi_df,id_range=range(500,600))","metadata":{"execution":{"iopub.status.busy":"2023-11-12T17:45:39.532126Z","iopub.execute_input":"2023-11-12T17:45:39.533604Z","iopub.status.idle":"2023-11-12T17:46:01.449375Z","shell.execute_reply.started":"2023-11-12T17:45:39.533538Z","shell.execute_reply":"2023-11-12T17:46:01.448489Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Kidney-2\n<div style=\"width:100%;height:0;border-bottom: 3px solid #BDAE25;margin-bottom: 1rem;\"></div>\n\n> The whole of a kidney from another donor, at 50um resolution. Sparsely segmented (about 65%).","metadata":{}},{"cell_type":"code","source":"kidney_2_df = prepare_df(im_dir='kidney_2',lb_dir='kidney_2')\nshow(kidney_2_df,1234)","metadata":{"execution":{"iopub.status.busy":"2023-11-12T17:46:14.283367Z","iopub.execute_input":"2023-11-12T17:46:14.283731Z","iopub.status.idle":"2023-11-12T17:46:14.999915Z","shell.execute_reply.started":"2023-11-12T17:46:14.283704Z","shell.execute_reply":"2023-11-12T17:46:14.998968Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"animate(kidney_2_df,id_range=range(800,900))","metadata":{"execution":{"iopub.status.busy":"2023-11-12T17:46:19.494404Z","iopub.execute_input":"2023-11-12T17:46:19.494749Z","iopub.status.idle":"2023-11-12T17:46:34.430098Z","shell.execute_reply.started":"2023-11-12T17:46:19.494723Z","shell.execute_reply":"2023-11-12T17:46:34.429137Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Kidney-3 Dense\n<div style=\"width:100%;height:0;border-bottom: 3px solid #B8BF25;margin-bottom: 1rem;\"></div>\n\n> A portion (500 slices) of a kidney at 50.16um resolution using BM05. Densely segmented. ","metadata":{}},{"cell_type":"code","source":"kidney_3_dense_df = prepare_df(im_dir='kidney_3_sparse',lb_dir='kidney_3_dense')\nshow(kidney_3_dense_df,533)","metadata":{"execution":{"iopub.status.busy":"2023-11-12T17:50:10.184509Z","iopub.execute_input":"2023-11-12T17:50:10.184910Z","iopub.status.idle":"2023-11-12T17:50:10.797805Z","shell.execute_reply.started":"2023-11-12T17:50:10.184884Z","shell.execute_reply":"2023-11-12T17:50:10.796983Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"animate(kidney_3_dense_df,id_range=range(500,600))","metadata":{"execution":{"iopub.status.busy":"2023-11-12T17:50:35.307157Z","iopub.execute_input":"2023-11-12T17:50:35.307510Z","iopub.status.idle":"2023-11-12T17:50:55.534942Z","shell.execute_reply.started":"2023-11-12T17:50:35.307482Z","shell.execute_reply":"2023-11-12T17:50:55.533789Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Kidney-3 Sparse\n<div style=\"width:100%;height:0;border-bottom: 3px solid #A3C225;margin-bottom: 1rem;\"></div>\n\n> The remainder of the segmentation masks for kidney-3. Sparsely segmented (about 85%).","metadata":{}},{"cell_type":"code","source":"kidney_3_sparse_df = prepare_df(im_dir='kidney_3_sparse',lb_dir='kidney_3_sparse')\nshow(kidney_3_sparse_df,343)","metadata":{"execution":{"iopub.status.busy":"2023-11-12T17:51:58.907442Z","iopub.execute_input":"2023-11-12T17:51:58.907782Z","iopub.status.idle":"2023-11-12T17:51:59.652354Z","shell.execute_reply.started":"2023-11-12T17:51:58.907755Z","shell.execute_reply":"2023-11-12T17:51:59.651640Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"animate(kidney_3_sparse_df,id_range=range(300,400))","metadata":{"execution":{"iopub.status.busy":"2023-11-12T17:52:05.334429Z","iopub.execute_input":"2023-11-12T17:52:05.334819Z","iopub.status.idle":"2023-11-12T17:52:24.282343Z","shell.execute_reply.started":"2023-11-12T17:52:05.334792Z","shell.execute_reply":"2023-11-12T17:52:24.281333Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"---","metadata":{}},{"cell_type":"code","source":"def get_common_slices(df1,df2):\n    ids1 = set(df1['slice_id'])\n    ids2 = set(df2['slice_id'])\n    return list(sorted(ids1 & ids2))","metadata":{"execution":{"iopub.status.busy":"2023-11-12T18:24:31.497666Z","iopub.execute_input":"2023-11-12T18:24:31.498010Z","iopub.status.idle":"2023-11-12T18:24:31.503108Z","shell.execute_reply.started":"2023-11-12T18:24:31.497985Z","shell.execute_reply":"2023-11-12T18:24:31.502080Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def animate_common(df1,df2,ids,t1,t2):\n    fig, [ax1,ax2,ax3,ax4] = plt.subplots(1,4)\n    plt.subplots_adjust(wspace=0.2)\n    fig.set_size_inches(16,4)\n    ax1.axis('off')\n    ax2.axis('off')\n    ax3.axis('off')\n    ax4.axis('off')\n    ax1.set_title(f'{t1} image')\n    ax2.set_title(f'{t1} mask')\n    ax3.set_title(f'{t2} image')\n    ax4.set_title(f'{t2} mask')\n    for axis in [ax1,ax2,ax3,ax4]:\n        axis.title.set_size(8)\n    images = []\n    for i in tqdm(ids):\n        s1 = df1[df1['slice_id']==i]\n        s1 = transforms({\n            'image':s1['image'],\n            'label':s1['label']\n        })\n        s2 = df2[df2['slice_id']==i]\n        s2 = transforms({\n            'image':s2['image'],\n            'label':s2['label']\n        })\n        i1 = s1['image'].permute(1,2,0)\n        i2 = s2['image'].permute(1,2,0)\n        l1 = s1['label'].permute(1,2,0)\n        l2 = s2['label'].permute(1,2,0)\n        im1 = ax1.imshow(i1, animated=True, cmap='gray')\n        im2 = ax2.imshow(l1, animated=True, cmap='gray')\n        im3 = ax3.imshow(i2, animated=True, cmap='gray')\n        im4 = ax4.imshow(l2, animated=True, cmap='gray')\n        if i==0:\n            ax1.imshow(i1, cmap='gray')\n            ax2.imshow(l1, cmap='gray')\n            ax3.imshow(i2, cmap='gray')\n            ax4.imshow(l2, cmap='gray')\n        images.append([im1,im2,im3,im4])\n\n\n    ani = animation.ArtistAnimation(fig, images, interval=50, blit=True,\n                                    repeat_delay=1000)\n    plt.close()\n    return ani","metadata":{"execution":{"iopub.status.busy":"2023-11-12T18:41:21.318419Z","iopub.execute_input":"2023-11-12T18:41:21.319447Z","iopub.status.idle":"2023-11-12T18:41:21.334291Z","shell.execute_reply.started":"2023-11-12T18:41:21.319409Z","shell.execute_reply":"2023-11-12T18:41:21.333118Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Kidney-1 at multiple resolutions\n<div style=\"width:100%;height:0;border-bottom: 3px solid #8DC524;margin-bottom: 1rem;\"></div>","metadata":{}},{"cell_type":"code","source":"animate_common(\n    dense_1_df,\n    kidney_1_voi_df,\n    ids=get_common_slices(dense_1_df,kidney_1_voi_df)[400:500],\n    t1='kidney 1 dense',\n    t2='kidney 2 voi'\n)","metadata":{"execution":{"iopub.status.busy":"2023-11-12T18:41:23.148940Z","iopub.execute_input":"2023-11-12T18:41:23.150112Z","iopub.status.idle":"2023-11-12T18:41:26.142170Z","shell.execute_reply.started":"2023-11-12T18:41:23.150082Z","shell.execute_reply":"2023-11-12T18:41:26.141310Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Run-Length Encoding\n<div style=\"width:100%;height:0;border-bottom: 3px solid #B77D25;margin-bottom: 1rem;\"></div>\n\n[Wikipedia](https://en.wikipedia.org/wiki/Run-length_encoding): Run-length encoding (RLE) is a form of lossless data compression in which runs of data (sequences in which the same data value occurs in many consecutive data elements) are stored as a single data value and count, rather than as the original run.\n\n#### Example: \n\nConsider a screen containing plain black text on a solid white background. There will be many long runs of white pixels in the blank space, and many short runs of black pixels within the text. A hypothetical scan line, with B representing a black pixel and W representing white, might read as follows:\n\n    WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW \n\nWith a run-length encoding (RLE) data compression algorithm applied to the above hypothetical scan line, it can be rendered as follows:\n\n    12W1B12W3B24W1B14W \n\n\nThis can be interpreted as a sequence of twelve Ws, one B, twelve Ws, three Bs, etc., and represents the original 67 characters in only 18.\n\n#### Helper Functions were linked in the dataset description: [@paulorzp/run-length-encode-and-decode/](https://www.kaggle.com/code/paulorzp/run-length-encode-and-decode/script)\n\n### During Submission, we've to encode our segmentation masks using this image compression algorithm","metadata":{}},{"cell_type":"code","source":"def rle_encode(img):\n    '''\n    img: numpy array, 1 - mask, 0 - background\n    Returns run length as string formated\n    '''\n    pixels = img.flatten()\n    pixels = np.concatenate([[0], pixels, [0]])\n    runs = np.where(pixels[1:] != pixels[:-1])[0] + 1\n    runs[1::2] -= runs[::2]\n    return ' '.join(str(x) for x in runs)\n \ndef rle_decode(mask_rle, shape):\n    '''\n    mask_rle: run-length as string formated (start length)\n    shape: (height,width) of array to return \n    Returns numpy array, 1 - mask, 0 - background\n\n    '''\n    s = mask_rle.split()\n    starts, lengths = [np.asarray(x, dtype=int) for x in (s[0:][::2], s[1:][::2])]\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)","metadata":{"execution":{"iopub.status.busy":"2023-11-12T20:11:59.804542Z","iopub.execute_input":"2023-11-12T20:11:59.804896Z","iopub.status.idle":"2023-11-12T20:11:59.814448Z","shell.execute_reply.started":"2023-11-12T20:11:59.804869Z","shell.execute_reply":"2023-11-12T20:11:59.812786Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample = dense_1_df.iloc[1234,:]\nrle = sample['rle']\nmask = np.array(Image.open(sample['label']).convert('L'))\nprint('RLE of mask:',rle)\nprint('mask shape',mask.shape)\nplt.imshow(Image.open(sample['label']),cmap='gray')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-11-12T20:15:58.138960Z","iopub.execute_input":"2023-11-12T20:15:58.140060Z","iopub.status.idle":"2023-11-12T20:15:58.361594Z","shell.execute_reply.started":"2023-11-12T20:15:58.140018Z","shell.execute_reply":"2023-11-12T20:15:58.360533Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Let's encode the above mask","metadata":{}},{"cell_type":"code","source":"encoded_mask_rle = rle_encode(mask)\nrle == encoded_mask_rle","metadata":{"execution":{"iopub.status.busy":"2023-11-12T20:17:17.724897Z","iopub.execute_input":"2023-11-12T20:17:17.725279Z","iopub.status.idle":"2023-11-12T20:17:17.736356Z","shell.execute_reply.started":"2023-11-12T20:17:17.725252Z","shell.execute_reply":"2023-11-12T20:17:17.735122Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Is the encoding invariant to the mask size?\n\n#### Yep! It is.","metadata":{}},{"cell_type":"code","source":"reshaped_mask = mask.reshape(-1) # let's just flatten it\nencoded_rle_2 = rle_encode(reshaped_mask)\nrle == encoded_rle_2, encoded_rle_2 == encoded_mask_rle","metadata":{"execution":{"iopub.status.busy":"2023-11-12T20:20:44.333722Z","iopub.execute_input":"2023-11-12T20:20:44.334107Z","iopub.status.idle":"2023-11-12T20:20:44.347136Z","shell.execute_reply.started":"2023-11-12T20:20:44.334074Z","shell.execute_reply":"2023-11-12T20:20:44.345826Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Let's decode the generated RLE ","metadata":{}},{"cell_type":"code","source":"decoded_rle = rle_decode(encoded_mask_rle,shape=mask.shape)\nplt.imshow(decoded_rle,cmap='gray')","metadata":{"execution":{"iopub.status.busy":"2023-11-12T20:18:16.771409Z","iopub.execute_input":"2023-11-12T20:18:16.771800Z","iopub.status.idle":"2023-11-12T20:18:17.034906Z","shell.execute_reply.started":"2023-11-12T20:18:16.771769Z","shell.execute_reply":"2023-11-12T20:18:17.033410Z"},"trusted":true},"execution_count":null,"outputs":[]}]}