{"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-07-10T04:40:30.537643Z","iopub.execute_input":"2023-07-10T04:40:30.538423Z","iopub.status.idle":"2023-07-10T04:40:32.067013Z","shell.execute_reply.started":"2023-07-10T04:40:30.538382Z","shell.execute_reply":"2023-07-10T04:40:32.065828Z"},"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-07-10T04:40:32.069438Z","iopub.execute_input":"2023-07-10T04:40:32.069922Z","iopub.status.idle":"2023-07-10T04:40:32.447258Z","shell.execute_reply.started":"2023-07-10T04:40:32.069874Z","shell.execute_reply":"2023-07-10T04:40:32.446153Z"},"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-07-10T04:40:32.454434Z","iopub.execute_input":"2023-07-10T04:40:32.454909Z","iopub.status.idle":"2023-07-10T04:40:37.558568Z","shell.execute_reply.started":"2023-07-10T04:40:32.454869Z","shell.execute_reply":"2023-07-10T04:40:37.557390Z"},"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-07-10T04:40:37.560273Z","iopub.execute_input":"2023-07-10T04:40:37.560642Z","iopub.status.idle":"2023-07-10T04:40:37.626165Z","shell.execute_reply.started":"2023-07-10T04:40:37.560609Z","shell.execute_reply":"2023-07-10T04:40:37.624871Z"},"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-07-10T04:40:37.627502Z","iopub.execute_input":"2023-07-10T04:40:37.627864Z","iopub.status.idle":"2023-07-10T04:40:37.642945Z","shell.execute_reply.started":"2023-07-10T04:40:37.627795Z","shell.execute_reply":"2023-07-10T04:40:37.641567Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_annotated_image(tiles_dicts[0])","metadata":{"execution":{"iopub.status.busy":"2023-07-10T04:40:37.644689Z","iopub.execute_input":"2023-07-10T04:40:37.645845Z","iopub.status.idle":"2023-07-10T04:40:38.119113Z","shell.execute_reply.started":"2023-07-10T04:40:37.645780Z","shell.execute_reply":"2023-07-10T04:40:38.118195Z"},"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-07-10T04:40:38.120465Z","iopub.execute_input":"2023-07-10T04:40:38.121058Z","iopub.status.idle":"2023-07-10T04:40:38.126497Z","shell.execute_reply.started":"2023-07-10T04:40:38.121025Z","shell.execute_reply":"2023-07-10T04:40:38.125723Z"},"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-07-10T04:40:38.127853Z","iopub.execute_input":"2023-07-10T04:40:38.128401Z","iopub.status.idle":"2023-07-10T04:40:38.429544Z","shell.execute_reply.started":"2023-07-10T04:40:38.128372Z","shell.execute_reply":"2023-07-10T04:40:38.428061Z"},"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-07-10T04:40:38.432792Z","iopub.execute_input":"2023-07-10T04:40:38.433256Z","iopub.status.idle":"2023-07-10T04:40:38.744157Z","shell.execute_reply.started":"2023-07-10T04:40:38.433224Z","shell.execute_reply":"2023-07-10T04:40:38.742989Z"},"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-07-10T04:40:38.745828Z","iopub.execute_input":"2023-07-10T04:40:38.746165Z","iopub.status.idle":"2023-07-10T04:40:39.045429Z","shell.execute_reply.started":"2023-07-10T04:40:38.746135Z","shell.execute_reply":"2023-07-10T04:40:39.044285Z"},"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-07-10T04:40:39.047127Z","iopub.execute_input":"2023-07-10T04:40:39.048023Z","iopub.status.idle":"2023-07-10T04:40:39.059501Z","shell.execute_reply.started":"2023-07-10T04:40:39.047990Z","shell.execute_reply":"2023-07-10T04:40:39.058398Z"},"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-07-10T04:40:39.061429Z","iopub.execute_input":"2023-07-10T04:40:39.061764Z","iopub.status.idle":"2023-07-10T04:42:13.964333Z","shell.execute_reply.started":"2023-07-10T04:40:39.061737Z","shell.execute_reply":"2023-07-10T04:42:13.963089Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}