{"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":"code","source":"import os\nHOME = os.getcwd()\nprint(HOME)","metadata":{"execution":{"iopub.status.busy":"2023-06-13T04:49:08.325843Z","iopub.execute_input":"2023-06-13T04:49:08.326646Z","iopub.status.idle":"2023-06-13T04:49:08.366137Z","shell.execute_reply.started":"2023-06-13T04:49:08.326593Z","shell.execute_reply":"2023-06-13T04:49:08.364748Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!mkdir /kaggle/working/packages\n!cp -r /kaggle/input/pycocotools/* /kaggle/working/packages\nos.chdir(\"/kaggle/working/packages/pycocotools-2.0.6/\")\n!python setup.py install\n!pip install . --no-index --find-links /kaggle/working/packages/\nos.chdir(\"/kaggle/working\")","metadata":{"execution":{"iopub.status.busy":"2023-06-13T04:49:08.367942Z","iopub.execute_input":"2023-06-13T04:49:08.368527Z","iopub.status.idle":"2023-06-13T04:50:08.109156Z","shell.execute_reply.started":"2023-06-13T04:49:08.368495Z","shell.execute_reply":"2023-06-13T04:50:08.107617Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Pip install method (recommended)\n# %pip install ultralytics\n%pip install --no-index -f /kaggle/input/ultralytics-offline ultralytics\n\nimport ultralytics","metadata":{"execution":{"iopub.status.busy":"2023-06-13T04:50:08.111315Z","iopub.execute_input":"2023-06-13T04:50:08.111741Z","iopub.status.idle":"2023-06-13T04:50:36.637927Z","shell.execute_reply.started":"2023-06-13T04:50:08.111699Z","shell.execute_reply":"2023-06-13T04:50:36.636541Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import base64\nimport numpy as np\nfrom pycocotools import _mask as coco_mask\nimport typing as t\nimport zlib\nfrom ultralytics import YOLO\nfrom PIL import Image\nimport cv2\nimport pandas as pd\nimport os\nimport wandb\nfrom itertools import groupby\nfrom skimage.measure import label, regionprops","metadata":{"execution":{"iopub.status.busy":"2023-06-13T04:50:36.640796Z","iopub.execute_input":"2023-06-13T04:50:36.641637Z","iopub.status.idle":"2023-06-13T04:50:38.130475Z","shell.execute_reply.started":"2023-06-13T04:50:36.641523Z","shell.execute_reply":"2023-06-13T04:50:38.128894Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"wandb.init(mode=\"disabled\")\nultralytics.checks()\n# os.makedirs('datasets', exist_ok=True)","metadata":{"execution":{"iopub.status.busy":"2023-06-13T04:50:38.132097Z","iopub.execute_input":"2023-06-13T04:50:38.132621Z","iopub.status.idle":"2023-06-13T04:50:58.494573Z","shell.execute_reply.started":"2023-06-13T04:50:38.132576Z","shell.execute_reply":"2023-06-13T04:50:58.493419Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample = '0 1.0 eNpLj8szjjRMsTP2M0KGvmC+l5mvsS9Uxt8QFRoAAYQc3MDQH4RBJISNLIIgUWl8+hC60HUis1BFjfzQ5Yz8UG3HB0G6UVmgCIHwggOSDQC4SmN8 0 1.0 eNoLiE0wso+3N/E18jP0M/Yz9Dc0MISQ/gZA0gBOYwKQMASDIBLfCGKArxGYBca+xn7hwWkmAIVrGZI= 0 1.0 eNqLCgozTzCItzfyM/I3RIEGBiAMJox9gdJ+xj5xufYAMRQMQg== 0 1.0 eNrLDY0yiTJMtTPyN/Q3MDAwNPA3MPKzcjfyNfQ39jXyM/I18jfyNfE18Tb2DYyMMQYAJi8MKA=='","metadata":{"execution":{"iopub.status.busy":"2023-06-13T04:50:58.496296Z","iopub.execute_input":"2023-06-13T04:50:58.497063Z","iopub.status.idle":"2023-06-13T04:50:58.502311Z","shell.execute_reply.started":"2023-06-13T04:50:58.497027Z","shell.execute_reply":"2023-06-13T04:50:58.501420Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def encode_binary_mask(mask: np.ndarray) -> t.Text:\n    \"\"\"Converts a binary mask into OID challenge encoding ascii text.\"\"\"\n\n    # check input mask --\n    if mask.dtype != bool:\n        raise ValueError(\n            \"encode_binary_mask expects a binary mask, received dtype == %s\" %\n            mask.dtype)\n\n    mask = np.squeeze(mask)\n    if len(mask.shape) != 2:\n        raise ValueError(\n            \"encode_binary_mask expects a 2d mask, received shape == %s\" %\n            mask.shape)\n\n    # convert input mask to expected COCO API input --\n    mask_to_encode = mask.reshape(mask.shape[0], mask.shape[1], 1)\n    mask_to_encode = mask_to_encode.astype(np.uint8)\n    mask_to_encode = np.asfortranarray(mask_to_encode)\n\n    # RLE encode mask --\n    encoded_mask = coco_mask.encode(mask_to_encode)[0][\"counts\"]\n\n    # compress and base64 encoding --\n    binary_str = zlib.compress(encoded_mask, zlib.Z_BEST_COMPRESSION)\n    base64_str = base64.b64encode(binary_str)\n    return base64_str","metadata":{"execution":{"iopub.status.busy":"2023-06-13T04:50:58.503808Z","iopub.execute_input":"2023-06-13T04:50:58.504155Z","iopub.status.idle":"2023-06-13T04:50:58.524927Z","shell.execute_reply.started":"2023-06-13T04:50:58.504126Z","shell.execute_reply":"2023-06-13T04:50:58.523670Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from ultralytics import YOLO\nmodel = YOLO(\"/kaggle/input/human-vascular-model/Jun_12_2023_best.pt\")","metadata":{"execution":{"iopub.status.busy":"2023-06-13T04:50:58.526932Z","iopub.execute_input":"2023-06-13T04:50:58.527631Z","iopub.status.idle":"2023-06-13T04:50:59.288076Z","shell.execute_reply.started":"2023-06-13T04:50:58.527520Z","shell.execute_reply":"2023-06-13T04:50:59.286752Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# with my latest mask ultralytics v1\nall_rows = []\nresults_csv = pd.DataFrame([], columns=[\"id\",\"height\",\"width\",\"prediction_string\"])\nresults_csv.set_index(\"id\")\n\nfor dirname, _, filenames in os.walk('/kaggle/input/hubmap-hacking-the-human-vasculature/test'):\n    for filename in filenames:\n        \n        im1 = Image.open(os.path.join(dirname, filename))\n        width, height = im1.size\n        \n        row = dict()\n        row[\"id\"] = filename[:-4]\n        row[\"height\"] = height\n        row[\"width\"] = width\n        row[\"prediction_string\"] = \"\"\n        try:\n            results = model.predict(source=im1)\n            boxe_data = results[0].boxes.data.numpy()\n            mask_data = results[0].masks.data\n            \n            row[\"width\"] = results[0].orig_shape[0]\n            row[\"height\"] = results[0].orig_shape[1]\n\n            mask_data = mask_data == 1# multiple images are expected\n            mask_data = mask_data * 1\n            mask_data = mask_data.cpu().numpy()\n\n            mask_data = mask_data.astype(bool)\n            prediction_l = []\n            list_encode = []\n            \n            for i in range(boxe_data.shape[0]):\n                class_no = int(boxe_data[i][5])\n                class_conf = boxe_data[i][4]\n                class_conf = float(class_conf)\n                if class_no !=0 and class_conf < 0.80:\n                    continue\n\n                sliceImage = mask_data[i,:,:]\n                coded_len = encode_binary_mask(sliceImage).decode('utf-8')\n                # if len(coded_len) < 90:\n                list_encode.append(coded_len)\n\n            row[\"prediction_string\"] = ' '.join(['0 1.0 ' + x for x in list_encode])\n        except:\n            print(\"failed to some reason\")\n        \n        new_row = pd.DataFrame(row, index=[0])\n        results_csv = pd.concat([new_row, results_csv.loc[:]]).reset_index(drop=True)\n        # all_rows.append(row)\n\nresults_csv.to_csv(\"submission.csv\", index=False)","metadata":{"execution":{"iopub.status.busy":"2023-06-13T04:50:59.289933Z","iopub.execute_input":"2023-06-13T04:50:59.290777Z","iopub.status.idle":"2023-06-13T04:51:11.220657Z","shell.execute_reply.started":"2023-06-13T04:50:59.290737Z","shell.execute_reply":"2023-06-13T04:51:11.219155Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"results_csv.head()","metadata":{"execution":{"iopub.status.busy":"2023-06-13T04:51:11.224801Z","iopub.execute_input":"2023-06-13T04:51:11.226675Z","iopub.status.idle":"2023-06-13T04:51:11.258029Z","shell.execute_reply.started":"2023-06-13T04:51:11.226626Z","shell.execute_reply":"2023-06-13T04:51:11.256647Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"results_csv[\"prediction_string\"].values","metadata":{"execution":{"iopub.status.busy":"2023-06-13T04:51:11.259766Z","iopub.execute_input":"2023-06-13T04:51:11.260367Z","iopub.status.idle":"2023-06-13T04:51:11.272879Z","shell.execute_reply.started":"2023-06-13T04:51:11.260242Z","shell.execute_reply":"2023-06-13T04:51:11.271702Z"},"trusted":true},"execution_count":null,"outputs":[]}]}