{"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 Making Dataset for Instance Segentation","metadata":{}},{"cell_type":"markdown","source":"## import libraries and metadata","metadata":{}},{"cell_type":"code","source":"import os\nimport json\nfrom PIL import Image\nfrom collections import Counter\n\nimport numpy as np\nimport pandas as pd\nimport plotly.express as px\nimport plotly.graph_objects as go\nimport tifffile as tiff\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\n\nimport cv2","metadata":{"execution":{"iopub.status.busy":"2023-06-08T03:42:26.383882Z","iopub.execute_input":"2023-06-08T03:42:26.384756Z","iopub.status.idle":"2023-06-08T03:42:26.391090Z","shell.execute_reply.started":"2023-06-08T03:42:26.384711Z","shell.execute_reply":"2023-06-08T03:42:26.389993Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with open('/kaggle/input/hubmap-hacking-the-human-vasculature/polygons.jsonl', 'r') as json_file:\n    json_list = list(json_file)","metadata":{"execution":{"iopub.status.busy":"2023-06-08T03:19:51.557520Z","iopub.execute_input":"2023-06-08T03:19:51.557862Z","iopub.status.idle":"2023-06-08T03:19:51.930642Z","shell.execute_reply.started":"2023-06-08T03:19:51.557837Z","shell.execute_reply":"2023-06-08T03:19:51.929687Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tiles_dicts = []\nfor json_str in json_list:\n    tiles_dicts.append(json.loads(json_str))","metadata":{"execution":{"iopub.status.busy":"2023-06-08T03:19:51.931901Z","iopub.execute_input":"2023-06-08T03:19:51.932771Z","iopub.status.idle":"2023-06-08T03:19:55.167621Z","shell.execute_reply.started":"2023-06-08T03:19:51.932738Z","shell.execute_reply":"2023-06-08T03:19:55.166585Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tile_meta_df = pd.read_csv(\"/kaggle/input/hubmap-hacking-the-human-vasculature/tile_meta.csv\")\ntile_meta_df","metadata":{"execution":{"iopub.status.busy":"2023-06-08T03:36:03.578876Z","iopub.execute_input":"2023-06-08T03:36:03.579232Z","iopub.status.idle":"2023-06-08T03:36:03.599640Z","shell.execute_reply.started":"2023-06-08T03:36:03.579207Z","shell.execute_reply":"2023-06-08T03:36:03.598709Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## visualize code from [[EDA] ❤️HuBMAP-HHV ~ Interactive annotations📊](https://www.kaggle.com/code/leonidkulyk/eda-hubmap-hhv-interactive-annotations/notebook)","metadata":{}},{"cell_type":"code","source":"def get_cartesian_coords(coords, img_height):\n    coords_array = np.array(coords).squeeze()\n    xs = coords_array[:, 0]\n    ys = -coords_array[:, 1] + img_height\n    \n    return xs, ys\n\ndef plot_annotated_image(image_dict, scale_factor: int = 1.0) -> None:\n    #array = tiff.imread(CFG.img_path_template.format(image_dict[\"id\"]))\n    array = tiff.imread(f'/kaggle/input/hubmap-hacking-the-human-vasculature/train/{image_dict[\"id\"]}.tif')\n    \n    img_example = Image.fromarray(array)\n    annotations = image_dict[\"annotations\"]\n    \n    # create figure\n    fig = go.Figure()\n\n    # constants\n    img_width = img_example.size[0]\n    img_height = img_example.size[1]\n    \n\n    # add invisible scatter trace\n    fig.add_trace(\n        go.Scatter(\n            x=[0, img_width],\n            y=[0, img_height],\n            mode=\"markers\",\n            marker_opacity=0\n        )\n    )\n\n    # configure axes\n    fig.update_xaxes(\n        visible=False,\n        range=[0, img_width]\n    )\n\n    fig.update_yaxes(\n        visible=False,\n        range=[0, img_height],\n        # the scaleanchor attribute ensures that the aspect ratio stays constant\n        scaleanchor=\"x\"\n    )\n\n    # add image\n    fig.add_layout_image(dict(\n        x=0,\n        sizex=img_width,\n        y=img_height,\n        sizey=img_height,\n        xref=\"x\", yref=\"y\",\n        opacity=1.0,\n        layer=\"below\",\n        sizing=\"stretch\",\n        source=img_example\n    ))\n    \n    # add polygons\n    for annotation in annotations:\n        name = annotation[\"type\"]\n        xs, ys = get_cartesian_coords(annotation[\"coordinates\"], img_height)\n        fig.add_trace(go.Scatter(\n            x=xs, y=ys, fill=\"toself\",\n            name=name,\n            hovertemplate=\"%{name}\",\n            mode='lines'\n        ))\n\n    # configure other layout\n    fig.update_layout(\n        width=img_width * scale_factor,\n        height=img_height * scale_factor,\n        margin={\"l\": 0, \"r\": 0, \"t\": 0, \"b\": 0},\n        showlegend=False\n    )\n\n    # disable the autosize on double click because it adds unwanted margins around the image\n    # and finally show figure\n    fig.show(config={'doubleClick': 'reset'})","metadata":{"execution":{"iopub.status.busy":"2023-06-08T03:19:55.204127Z","iopub.execute_input":"2023-06-08T03:19:55.204571Z","iopub.status.idle":"2023-06-08T03:19:55.219687Z","shell.execute_reply.started":"2023-06-08T03:19:55.204536Z","shell.execute_reply":"2023-06-08T03:19:55.218619Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_annotated_image(tiles_dicts[0])","metadata":{"execution":{"iopub.status.busy":"2023-06-08T03:19:55.221398Z","iopub.execute_input":"2023-06-08T03:19:55.221714Z","iopub.status.idle":"2023-06-08T03:19:55.634705Z","shell.execute_reply.started":"2023-06-08T03:19:55.221692Z","shell.execute_reply":"2023-06-08T03:19:55.632183Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## make sample annotation for Instance Segmentation","metadata":{}},{"cell_type":"code","source":"len(tiles_dicts)","metadata":{"execution":{"iopub.status.busy":"2023-06-08T03:20:04.318407Z","iopub.execute_input":"2023-06-08T03:20:04.318721Z","iopub.status.idle":"2023-06-08T03:20:04.325904Z","shell.execute_reply.started":"2023-06-08T03:20:04.318697Z","shell.execute_reply":"2023-06-08T03:20:04.324244Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mask = np.zeros((512, 512), dtype=np.float32)\nfor annot in tiles_dicts[0]['annotations']:\n    cords = annot['coordinates']\n    if annot['type'] == \"blood_vessel\":\n        for cd in cords:\n            rr, cc = np.array([i[1] for i in cd]), np.asarray([i[0] for i in cd])\n            mask[rr, cc] = 1\n            \nplt.imshow(mask)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-06-08T03:22:32.659074Z","iopub.execute_input":"2023-06-08T03:22:32.659404Z","iopub.status.idle":"2023-06-08T03:22:32.848683Z","shell.execute_reply.started":"2023-06-08T03:22:32.659382Z","shell.execute_reply":"2023-06-08T03:22:32.847596Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"contours,_ = cv2.findContours((mask*255).astype(np.uint8), 1, 2)\nzero_img = np.zeros([mask.shape[0], mask.shape[1], 3], dtype=\"uint8\")\n\nfor p in contours:\n    cv2.fillPoly(zero_img, [p], (255, 255, 255))\n    \nplt.imshow(zero_img)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-06-08T03:23:25.792835Z","iopub.execute_input":"2023-06-08T03:23:25.793199Z","iopub.status.idle":"2023-06-08T03:23:26.001976Z","shell.execute_reply.started":"2023-06-08T03:23:25.793170Z","shell.execute_reply":"2023-06-08T03:23:26.001068Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from copy import deepcopy\ncontours, hierarchy = cv2.findContours(mask.astype(\"uint8\"), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\nimg_with_area = zero_img\nprint(img_with_area.shape)\n\nprint(len(contours))\n        \nfor i in range(len(contours)):\n    if cv2.contourArea(contours[i]) > (mask.shape[0] * mask.shape[1]) * 0.0001:\n        cv2.fillPoly(img_with_area, [contours[i][:,0,:]], (255-4*(i+1),255-4*(i+1),255-4*(i+1)), lineType=cv2.LINE_8, shift=0)\n        \nplt.imshow(img_with_area)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-06-08T03:25:08.619681Z","iopub.execute_input":"2023-06-08T03:25:08.620004Z","iopub.status.idle":"2023-06-08T03:25:08.790308Z","shell.execute_reply.started":"2023-06-08T03:25:08.619977Z","shell.execute_reply":"2023-06-08T03:25:08.789647Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## functionalize","metadata":{}},{"cell_type":"code","source":"def make_seg_mask(tiles_dict):\n    mask = np.zeros((512, 512), dtype=np.float32)\n    for annot in tiles_dict['annotations']:\n        cords = annot['coordinates']\n        if annot['type'] == \"blood_vessel\":\n            for cd in cords:\n                rr, cc = np.array([i[1] for i in cd]), np.asarray([i[0] for i in cd])\n                mask[rr, cc] = 1\n                \n    contours,_ = cv2.findContours((mask*255).astype(np.uint8), 1, 2)\n    zero_img = np.zeros([mask.shape[0], mask.shape[1], 3], dtype=\"uint8\")\n\n    for p in contours:\n        cv2.fillPoly(zero_img, [p], (255, 255, 255))\n\n    contours, hierarchy = cv2.findContours(mask.astype(\"uint8\"), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\n    img_with_area = zero_img\n\n    for i in range(len(contours)):\n        cv2.fillPoly(img_with_area, [contours[i][:,0,:]], (255-4*(i+1),255-4*(i+1),255-4*(i+1)), lineType=cv2.LINE_8, shift=0)\n            \n    return img_with_area    ","metadata":{"execution":{"iopub.status.busy":"2023-06-08T03:50:07.650148Z","iopub.execute_input":"2023-06-08T03:50:07.650507Z","iopub.status.idle":"2023-06-08T03:50:07.659016Z","shell.execute_reply.started":"2023-06-08T03:50:07.650480Z","shell.execute_reply":"2023-06-08T03:50:07.658173Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"os.makedirs('train/image', exist_ok=True)\nos.makedirs('train/mask', exist_ok=True)\n\nfor i, tldc in enumerate(tqdm(tiles_dicts)):\n    array = tiff.imread(f'/kaggle/input/hubmap-hacking-the-human-vasculature/train/{tldc[\"id\"]}.tif')\n    img_example = Image.fromarray(array)\n    img = np.array(img_example)\n    mask = make_seg_mask(tldc)\n    \n    if np.sum(mask)>0:\n\n        cv2.imwrite(f'train/image/{tldc[\"id\"]}.png', img)\n        cv2.imwrite(f'train/mask/{tldc[\"id\"]}_mask.png', mask)\n    ","metadata":{"execution":{"iopub.status.busy":"2023-06-08T03:57:13.193321Z","iopub.execute_input":"2023-06-08T03:57:13.193663Z","iopub.status.idle":"2023-06-08T03:58:08.358501Z","shell.execute_reply.started":"2023-06-08T03:57:13.193639Z","shell.execute_reply":"2023-06-08T03:58:08.357265Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}