{"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":"# 🦠 Cell Instance Segmentation: 🔍 interative data view\n\nFor more or future development see https://borda.github.io/kaggle_cell-inst-segm","metadata":{}},{"cell_type":"code","source":"! ls -l /kaggle/input/sartorius-cell-instance-segmentation\n# ! ls -l /kaggle/input/sartorius-cell-instance-segmentation/LIVECell_dataset_2021","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2021-10-22T09:50:21.101978Z","iopub.execute_input":"2021-10-22T09:50:21.102407Z","iopub.status.idle":"2021-10-22T09:50:21.919892Z","shell.execute_reply.started":"2021-10-22T09:50:21.102306Z","shell.execute_reply":"2021-10-22T09:50:21.918921Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Browsing the provided data/images/annotations...","metadata":{}},{"cell_type":"code","source":"import os\nimport pandas as pd\n\nPATH_DATASET = \"/kaggle/input/sartorius-cell-instance-segmentation\"\nPATH_IMAGES = os.path.join(PATH_DATASET, \"train\")\nPATH_TRAIN_CSV = os.path.join(PATH_DATASET, \"train.csv\")\n\ndf_train = pd.read_csv(PATH_TRAIN_CSV)\ndisplay(df_train.head())\ndf_train.loc[0, \"annotation\"]","metadata":{"execution":{"iopub.status.busy":"2021-10-22T09:50:21.921984Z","iopub.execute_input":"2021-10-22T09:50:21.922424Z","iopub.status.idle":"2021-10-22T09:50:22.651233Z","shell.execute_reply.started":"2021-10-22T09:50:21.922390Z","shell.execute_reply":"2021-10-22T09:50:22.650319Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Histogram of annotation per image","metadata":{}},{"cell_type":"code","source":"df_counts = df_train.groupby(['id']).size()\ndisplay(df_counts.head())\nax = df_counts.hist(bins=50, grid=True)\nax.set_xlabel(\"Annotations per image\")\nax.set_ylabel(\"Images with particular annot. count\")","metadata":{"execution":{"iopub.status.busy":"2021-10-22T09:50:22.653425Z","iopub.execute_input":"2021-10-22T09:50:22.654156Z","iopub.status.idle":"2021-10-22T09:50:23.093368Z","shell.execute_reply.started":"2021-10-22T09:50:22.654084Z","shell.execute_reply":"2021-10-22T09:50:23.092318Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Decode single annotation","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\n\ndef rle_decode(mask_rle: str, img: np.ndarray = None, img_shape: tuple = None, label: int = 1) -> np.ndarray:\n    seq = mask_rle.split()\n    starts = np.array(list(map(int, seq[0::2])))\n    lengths = np.array(list(map(int, seq[1::2])))\n    assert len(starts) == len(lengths)\n    ends = starts + lengths\n    \n    if img is None:\n        img = np.zeros((np.product(img_shape), ), dtype=np.uint16)\n    else:\n        img_shape = img.shape\n        img = img.flatten()\n    for begin, end in zip(starts, ends):\n        img[begin:end] = label\n    return img.reshape(img_shape)\n\nmask = rle_decode(df_train.loc[0, \"annotation\"], img_shape=(df_train.loc[0, \"height\"], df_train.loc[0, \"width\"]))\nmask = rle_decode(df_train.loc[1, \"annotation\"], img=mask, label=2)\n_= plt.imshow(mask)","metadata":{"execution":{"iopub.status.busy":"2021-10-22T09:50:23.095944Z","iopub.execute_input":"2021-10-22T09:50:23.096323Z","iopub.status.idle":"2021-10-22T09:50:23.389028Z","shell.execute_reply.started":"2021-10-22T09:50:23.096276Z","shell.execute_reply":"2021-10-22T09:50:23.387942Z"},"_kg_hide-output":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Create complete mask","metadata":{}},{"cell_type":"code","source":"def create_mask(df_image: pd.DataFrame) -> np.ndarray:\n    assert len(df_image[\"id\"].unique()) == 1\n    sizes = list(set((row[\"height\"], row[\"width\"]) for _, row in df_image.iterrows()))\n    assert len(sizes) == 1\n    mask = np.zeros(sizes[0], dtype=np.uint16)\n    df_image.reset_index(inplace=True)\n    for idx, row in df_image.iterrows():\n        mask = rle_decode(row[\"annotation\"], img=mask, label=idx + 1)\n    return mask\n    \n\n# print(df_train[\"sample_id\"].unique())\nmask = create_mask(df_train[df_train[\"id\"] == \"0030fd0e6378\"])\n_= plt.imshow(mask, interpolation='antialiased')","metadata":{"execution":{"iopub.status.busy":"2021-10-22T09:50:23.390824Z","iopub.execute_input":"2021-10-22T09:50:23.391068Z","iopub.status.idle":"2021-10-22T09:50:23.819767Z","shell.execute_reply.started":"2021-10-22T09:50:23.391039Z","shell.execute_reply":"2021-10-22T09:50:23.818840Z"},"_kg_hide-output":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Interactive view\n\nNote that for interative browsing you need to be in edit mode (it is not supported for saved version)","metadata":{}},{"cell_type":"code","source":"from ipywidgets import interact, SelectionSlider\n\n\ndef show_image_annot(img_name: str, df_train: pd.DataFrame, img_folder: str):\n    print(img_name)\n    df_img = df_train[df_train[\"id\"] == img_name]\n    path_img = os.path.join(img_folder, f\"{img_name}.png\")\n    img = plt.imread(path_img)\n    mask = create_mask(df_img)\n    fig, axarr = plt.subplots(ncols=3, figsize=(18, 6))\n    axarr[0].imshow(img)\n    axarr[1].imshow(img)\n    axarr[1].contour(mask, levels=np.unique(mask).tolist(), cmap=\"inferno\", linewidths=0.5)\n    axarr[2].imshow(mask, cmap=\"inferno\", interpolation='antialiased')\n    return fig\n\n\ndef interactive_show(df_train: pd.DataFrame, img_folder: str):\n    uq_images = df_train[\"id\"].unique()\n    interact(\n        lambda im: plt.show(show_image_annot(im, df_train, img_folder)),\n        im=SelectionSlider(\n            options=uq_images,\n            value=\"cc40345857dd\",  # uq_images[np.random.randint(0, len(uq_images))],\n            description='Select image:',\n            disabled=False,\n            continuous_update=False,\n            orientation='horizontal',\n            readout=True\n        ),\n    )\n\ninteractive_show(df_train, PATH_IMAGES)","metadata":{"execution":{"iopub.status.busy":"2021-10-22T09:53:11.865167Z","iopub.execute_input":"2021-10-22T09:53:11.865621Z","iopub.status.idle":"2021-10-22T09:53:17.382824Z","shell.execute_reply.started":"2021-10-22T09:53:11.865587Z","shell.execute_reply":"2021-10-22T09:53:17.381755Z"},"trusted":true},"execution_count":null,"outputs":[]}]}