{"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":"# Annotate Cells\nOn this notebook, We annotate the cells by given **encoded annotation**.<br>\nBy using this, We can create **mask**.","metadata":{"_uuid":"0b96b28b-5a84-48a3-8bb9-ed8700b6aa1f","_cell_guid":"bf817c00-9def-4014-9017-56d4d0099699","jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-10-21T09:00:03.19526Z","iopub.execute_input":"2021-10-21T09:00:03.195858Z","iopub.status.idle":"2021-10-21T09:00:03.410507Z","shell.execute_reply.started":"2021-10-21T09:00:03.19572Z","shell.execute_reply":"2021-10-21T09:00:03.409484Z"}}},{"cell_type":"code","source":"!pip install pycocotools","metadata":{"execution":{"iopub.status.busy":"2021-10-30T06:37:49.616872Z","iopub.execute_input":"2021-10-30T06:37:49.617165Z","iopub.status.idle":"2021-10-30T06:38:08.588681Z","shell.execute_reply.started":"2021-10-30T06:37:49.617133Z","shell.execute_reply":"2021-10-30T06:38:08.587704Z"},"scrolled":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from pathlib import Path\nimport pandas as pd\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nimport pycocotools.mask as pyc\nfrom PIL import Image\nimport cv2\nplt.style.use('ggplot')","metadata":{"execution":{"iopub.status.busy":"2021-10-30T06:39:17.751347Z","iopub.execute_input":"2021-10-30T06:39:17.751737Z","iopub.status.idle":"2021-10-30T06:39:17.942201Z","shell.execute_reply.started":"2021-10-30T06:39:17.751690Z","shell.execute_reply":"2021-10-30T06:39:17.940811Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Some Path","metadata":{}},{"cell_type":"code","source":"train_path = Path(\"../input/sartorius-cell-instance-segmentation/train\")\ntest_path = Path(\"../input/sartorius-cell-instance-segmentation/test\")\nmeta_path = Path(\"../input/sartorius-cell-instance-segmentation/train.csv\")","metadata":{"execution":{"iopub.status.busy":"2021-10-30T06:39:32.931811Z","iopub.execute_input":"2021-10-30T06:39:32.932897Z","iopub.status.idle":"2021-10-30T06:39:32.937985Z","shell.execute_reply.started":"2021-10-30T06:39:32.932820Z","shell.execute_reply":"2021-10-30T06:39:32.936840Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Load meta-data","metadata":{}},{"cell_type":"code","source":"meta_data = pd.read_csv(str(meta_path))\nmeta_data.head()","metadata":{"execution":{"iopub.status.busy":"2021-10-30T06:39:32.959520Z","iopub.execute_input":"2021-10-30T06:39:32.959899Z","iopub.status.idle":"2021-10-30T06:39:33.616742Z","shell.execute_reply.started":"2021-10-30T06:39:32.959862Z","shell.execute_reply":"2021-10-30T06:39:33.616107Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"labels = meta_data[\"cell_type\"].drop_duplicates().tolist()\nimages_id = meta_data[\"id\"].drop_duplicates().tolist()\nprint(f\"# number of instances: {len(meta_data)}\")\nprint(f\"# number of images: {len(images_id)}\")\nprint(f\"# number of classes: {len(labels)}\")","metadata":{"execution":{"iopub.status.busy":"2021-10-30T06:39:33.618164Z","iopub.execute_input":"2021-10-30T06:39:33.618601Z","iopub.status.idle":"2021-10-30T06:39:33.634982Z","shell.execute_reply.started":"2021-10-30T06:39:33.618547Z","shell.execute_reply":"2021-10-30T06:39:33.634152Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Some function","metadata":{}},{"cell_type":"code","source":"def rle_decode(ann):\n    \"\"\"\n    decode run length encoded\n    \"\"\"\n    t= ann\n    ann = ann.split(\" \")\n    ans = []\n    i = 0\n    col = 0\n    while i<len(ann)-1:\n        pref = ann[i]\n        l = ann[i+1]\n        i+=2\n        tm = []\n        for j in range(int(l)):\n            tm.append(int(pref)+j)\n        ans+=tm\n        col+=1\n        \n    return ans\n\ndef gen_color():\n    b = np.random.randint(0,255)\n    g = np.random.randint(0,255)\n    r = np.random.randint(0,255)\n    return r,g,b","metadata":{"execution":{"iopub.status.busy":"2021-10-30T06:39:33.636396Z","iopub.execute_input":"2021-10-30T06:39:33.636694Z","iopub.status.idle":"2021-10-30T06:39:33.646166Z","shell.execute_reply.started":"2021-10-30T06:39:33.636661Z","shell.execute_reply":"2021-10-30T06:39:33.645164Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"color = {\n    \"shsy5y\": [0,255,0],\n    \"astro\": [255,0,0],\n    \"cort\": [0,0,255]\n}","metadata":{"execution":{"iopub.status.busy":"2021-10-30T06:39:34.945018Z","iopub.execute_input":"2021-10-30T06:39:34.945341Z","iopub.status.idle":"2021-10-30T06:39:34.950625Z","shell.execute_reply.started":"2021-10-30T06:39:34.945298Z","shell.execute_reply":"2021-10-30T06:39:34.949652Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.rcParams.update({'font.size': 60})\nfig, axes = plt.subplots(2,2, figsize = (200,80),gridspec_kw={'height_ratios': [1, 1]})\n\nsample_id = images_id[np.random.randint(0,len(images_id))]\ninstances = meta_data.loc[meta_data[\"id\"] == sample_id]\nh = instances[\"height\"].drop_duplicates().tolist()[0]\nw = instances[\"width\"].drop_duplicates().tolist()[0]\nim = cv2.imread(str(train_path.joinpath(f\"{sample_id}.png\")))\nvec_im = im.copy().reshape((-1,im.shape[-1]))\nbbox_im = im.copy().reshape((-1,im.shape[-1]))\nglobal_mask = np.zeros((h*w,),dtype=np.uint8)\nfor idx in range(len(instances)):\n    sample = instances.iloc[idx]\n    ann = sample.annotation\n    lb = sample.cell_type\n    poses = rle_decode(ann)\n    r,g,b = gen_color()\n    mask = np.zeros((h*w,),dtype=np.uint8)\n    for pos in poses:\n        pos-=1\n        \n        vec_im[pos,0] = b\n        vec_im[pos,1] = g\n        vec_im[pos,2] = r\n        \n        bbox_im[pos,0] = b\n        bbox_im[pos,1] = g\n        bbox_im[pos,2] = r\n        \n        mask[pos] = 1\n        global_mask[pos] = 1\n    mask = mask.reshape((h,w))\n    segmentation = pyc.encode(np.asarray(mask, order=\"F\"))\n    bbox=pyc.toBbox(segmentation)\n    x0,y0,w0,h0 = bbox\n    x0 = int(x0)\n    y0 = int(y0)\n    x1 = x0+int(w0)\n    y1 = y0+int(h0)\n    \n    bbox_im = bbox_im.reshape(im.shape)\n    bbox_im = cv2.rectangle(bbox_im,(x0,y0),(x1,y1),(b,g,r),2)\n    bbox_im = bbox_im.reshape((-1,im.shape[-1]))\n    \nannotated_im = vec_im.reshape(im.shape)\nbbox_im = bbox_im.reshape(im.shape)\nglobal_mask = global_mask.reshape((h,w))\n\naxes[0,0].imshow(im)\naxes[0,0].grid(False)\naxes[0,0].axis('off')\naxes[0,0].set_title(\"Image\")\n\naxes[0,1].imshow(annotated_im)\naxes[0,1].grid(False)\naxes[0,1].axis('off')\naxes[0,1].set_title(\"Annotation\")\n\naxes[1,0].imshow(bbox_im)\naxes[1,0].grid(False)\naxes[1,0].axis('off')\naxes[1,0].set_title(\"Bounding Box\")\n\naxes[1,1].imshow(global_mask)\naxes[1,1].grid(False)\naxes[1,1].axis('off')\naxes[1,1].set_title(\"Mask\")\n\nfig.show()","metadata":{"execution":{"iopub.status.busy":"2021-10-30T07:16:23.266241Z","iopub.execute_input":"2021-10-30T07:16:23.266587Z","iopub.status.idle":"2021-10-30T07:16:28.569007Z","shell.execute_reply.started":"2021-10-30T07:16:23.266537Z","shell.execute_reply":"2021-10-30T07:16:28.568393Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}