{"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":"# Install pycocotools package\nimport os\n!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 -q . --no-index --find-links /kaggle/working/packages/\nos.chdir(\"/kaggle/working\")","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-05-25T11:45:19.434723Z","iopub.execute_input":"2023-05-25T11:45:19.435359Z","iopub.status.idle":"2023-05-25T11:46:14.558236Z","shell.execute_reply.started":"2023-05-25T11:45:19.435325Z","shell.execute_reply":"2023-05-25T11:46:14.557083Z"},"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport cv2\nimport matplotlib.pyplot as plt\n\nimport base64\nimport numpy as np\nfrom pycocotools import _mask as coco_mask\nimport typing as t\nimport zlib\n\ndef 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\n\n\ntest_path = \"/kaggle/input/hubmap-hacking-the-human-vasculature/test\"\nsample_submission = pd.read_csv('/kaggle/input/hubmap-hacking-the-human-vasculature/sample_submission.csv')\n\n# set up a black greyscale image \ntestmask1 = np.zeros((512,512), np.uint8)\ntestmask2 = np.zeros((512,512), np.uint8)\ntestmask3 = np.zeros((512,512), np.uint8)\n\n# dummy predictions - masks\nseg_instances = []\nseg_instances.append(cv2.circle(testmask1, (100,100), 50,255, cv2.FILLED))\nseg_instances.append(cv2.circle(testmask2, (400,100), 50,255, cv2.FILLED))\nseg_instances.append(cv2.line(testmask3, (100, 400), (400, 400), 255, thickness=5))\n\nids = []\nheights = []\nwidths = []\nprediction_strings = []\nfor img_name in os.listdir(test_path):\n    img = cv2.imread(f\"{test_path}/{img_name}\")\n    h, w, c = img.shape\n    \n    # after seg infer\n    pred_string = \"\"\n    for i, item in enumerate(seg_instances):\n        binmask = np.zeros((512,512), np.bool8)\n\n        binmask[item>0] = 1\n        plt.figure()\n        plt.imshow(binmask, cmap='gray', vmin=0, vmax=1)\n        encoded = encode_binary_mask(binmask)\n\n        if i == 0:\n            pred_string += f\"0 1.0 {encoded.decode('utf-8')}\"\n        else:\n            pred_string += f\" 0 1.0 {encoded.decode('utf-8')}\"\n    ids.append(img_name.split('.')[0])\n    heights.append(h)\n    widths.append(w)\n    prediction_strings.append(pred_string)\n\nplt.figure()\nplt.imshow(img)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-05-25T13:07:05.882635Z","iopub.execute_input":"2023-05-25T13:07:05.883010Z","iopub.status.idle":"2023-05-25T13:07:06.782461Z","shell.execute_reply.started":"2023-05-25T13:07:05.882980Z","shell.execute_reply":"2023-05-25T13:07:06.781672Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission = pd.DataFrame()\nsubmission['id'] = ids\nsubmission['height'] = heights\nsubmission['width'] = widths\nsubmission['prediction_string'] = prediction_strings\nsubmission = submission.set_index('id')\nsubmission.to_csv(\"submission.csv\")\nprint(submission)","metadata":{"execution":{"iopub.status.busy":"2023-05-25T13:07:10.673742Z","iopub.execute_input":"2023-05-25T13:07:10.674433Z","iopub.status.idle":"2023-05-25T13:07:10.688956Z","shell.execute_reply.started":"2023-05-25T13:07:10.674398Z","shell.execute_reply":"2023-05-25T13:07:10.687618Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"rm -rf /kaggle/working/packages","metadata":{"execution":{"iopub.status.busy":"2023-05-25T13:08:17.861488Z","iopub.execute_input":"2023-05-25T13:08:17.861884Z","iopub.status.idle":"2023-05-25T13:08:18.800014Z","shell.execute_reply.started":"2023-05-25T13:08:17.861824Z","shell.execute_reply":"2023-05-25T13:08:18.798752Z"},"trusted":true},"execution_count":null,"outputs":[]}]}