{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.10","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":52279,"databundleVersionId":5822112,"sourceType":"competition"}],"dockerImageVersionId":30497,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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":"2024-01-13T08:24:40.619846Z","iopub.execute_input":"2024-01-13T08:24:40.620664Z","iopub.status.idle":"2024-01-13T08:24:42.040137Z","shell.execute_reply.started":"2024-01-13T08:24:40.620626Z","shell.execute_reply":"2024-01-13T08:24:42.038656Z"},"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":"2024-01-13T08:24:42.042654Z","iopub.execute_input":"2024-01-13T08:24:42.043122Z","iopub.status.idle":"2024-01-13T08:24:42.560855Z","shell.execute_reply.started":"2024-01-13T08:24:42.043080Z","shell.execute_reply":"2024-01-13T08:24:42.559644Z"},"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":"2024-01-13T08:24:42.562972Z","iopub.execute_input":"2024-01-13T08:24:42.563756Z","iopub.status.idle":"2024-01-13T08:24:47.629226Z","shell.execute_reply.started":"2024-01-13T08:24:42.563710Z","shell.execute_reply":"2024-01-13T08:24:47.628043Z"},"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":"2024-01-13T08:24:47.631747Z","iopub.execute_input":"2024-01-13T08:24:47.632448Z","iopub.status.idle":"2024-01-13T08:24:47.700279Z","shell.execute_reply.started":"2024-01-13T08:24:47.632415Z","shell.execute_reply":"2024-01-13T08:24:47.698277Z"},"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":"2024-01-13T08:24:47.701914Z","iopub.execute_input":"2024-01-13T08:24:47.702465Z","iopub.status.idle":"2024-01-13T08:24:47.716409Z","shell.execute_reply.started":"2024-01-13T08:24:47.702435Z","shell.execute_reply":"2024-01-13T08:24:47.715177Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_annotated_image(tiles_dicts[0])","metadata":{"execution":{"iopub.status.busy":"2024-01-13T08:24:47.718229Z","iopub.execute_input":"2024-01-13T08:24:47.718657Z","iopub.status.idle":"2024-01-13T08:24:48.194077Z","shell.execute_reply.started":"2024-01-13T08:24:47.718607Z","shell.execute_reply":"2024-01-13T08:24:48.192805Z"},"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":"2024-01-13T08:24:48.195903Z","iopub.execute_input":"2024-01-13T08:24:48.196310Z","iopub.status.idle":"2024-01-13T08:24:48.203517Z","shell.execute_reply.started":"2024-01-13T08:24:48.196276Z","shell.execute_reply":"2024-01-13T08:24:48.202384Z"},"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":"2024-01-13T08:24:48.205404Z","iopub.execute_input":"2024-01-13T08:24:48.206230Z","iopub.status.idle":"2024-01-13T08:24:48.520809Z","shell.execute_reply.started":"2024-01-13T08:24:48.206190Z","shell.execute_reply":"2024-01-13T08:24:48.519716Z"},"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":"2024-01-13T08:24:48.522278Z","iopub.execute_input":"2024-01-13T08:24:48.522630Z","iopub.status.idle":"2024-01-13T08:24:48.831159Z","shell.execute_reply.started":"2024-01-13T08:24:48.522601Z","shell.execute_reply":"2024-01-13T08:24:48.830041Z"},"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":"2024-01-13T08:24:48.835010Z","iopub.execute_input":"2024-01-13T08:24:48.835588Z","iopub.status.idle":"2024-01-13T08:24:49.134370Z","shell.execute_reply.started":"2024-01-13T08:24:48.835545Z","shell.execute_reply":"2024-01-13T08:24:49.133242Z"},"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":"2024-01-13T08:24:49.136085Z","iopub.execute_input":"2024-01-13T08:24:49.136630Z","iopub.status.idle":"2024-01-13T08:24:49.150212Z","shell.execute_reply.started":"2024-01-13T08:24:49.136587Z","shell.execute_reply":"2024-01-13T08:24:49.148540Z"},"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":"2024-01-13T08:24:49.152037Z","iopub.execute_input":"2024-01-13T08:24:49.152947Z","iopub.status.idle":"2024-01-13T08:26:33.244740Z","shell.execute_reply.started":"2024-01-13T08:24:49.152908Z","shell.execute_reply":"2024-01-13T08:26:33.243939Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}