{"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":"!pip install /kaggle/input/task-hubmap/pkg/pycocotools-2.0.6-cp310-cp310-linux_x86_64.whl -q\n!pip install /kaggle/input/mmcvseg-py310/addict-2.4.0-py3-none-any.whl -q\n!pip install /kaggle/input/mmcvseg-py310/mmengine-0.7.4-py3-none-any.whl -q \n!pip install /kaggle/input/mmcvseg-py310/mmcv-2.0.1-cp310-cp310-linux_x86_64.whl -q \n!pip install /kaggle/input/task-hubmap/pkg/terminaltables-3.1.10-py2.py3-none-any.whl -q\n!pip install /kaggle/input/hubmap2023-maskrcnn/mmdet-3.0.0-py3-none-any.whl -q","metadata":{"execution":{"iopub.status.busy":"2023-07-11T12:58:32.630944Z","iopub.execute_input":"2023-07-11T12:58:32.631307Z","iopub.status.idle":"2023-07-11T13:01:44.436872Z","shell.execute_reply.started":"2023-07-11T12:58:32.631277Z","shell.execute_reply":"2023-07-11T13:01:44.435476Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 检查 Pytorch\nimport torch, torchvision\nimport mmdet, mmcv, mmengine\nfrom mmengine.config import Config\nfrom mmengine.runner import Runner\nfrom mmdet.utils import register_all_modules\nfrom mmdet.apis import init_detector, inference_detector\nfrom mmengine.visualization import Visualizer\nimport os\nimport pandas as pd\nimport cv2","metadata":{"execution":{"iopub.status.busy":"2023-07-11T13:01:50.947659Z","iopub.execute_input":"2023-07-11T13:01:50.948387Z","iopub.status.idle":"2023-07-11T13:01:50.958692Z","shell.execute_reply.started":"2023-07-11T13:01:50.948353Z","shell.execute_reply":"2023-07-11T13:01:50.957581Z"},"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\n\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 != np.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-07-11T13:01:50.960054Z","iopub.execute_input":"2023-07-11T13:01:50.960525Z","iopub.status.idle":"2023-07-11T13:01:50.974891Z","shell.execute_reply.started":"2023-07-11T13:01:50.960491Z","shell.execute_reply":"2023-07-11T13:01:50.974003Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%mkdir work_dir_test\n\ncfg = Config.fromfile(\"/kaggle/input/hubmap2023-maskrcnn/config.py\")\ncfg.work_dir = \"/kaggle/working/work_dir_test\"\nvis_backends = [dict(type='LocalVisBackend')]\ncfg.visualizer = dict(type='DetLocalVisualizer', vis_backends=vis_backends, name='visualizer')\ncfg.test_pipeline = [\n        dict(type='LoadImageFromFile', backend_args=None),\n        dict(type='Resize', scale=(1600, 1600), keep_ratio=True),\n        dict(\n            type='PackDetInputs',\n            meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape',\n                       'scale_factor'))\n    ]\nrunner = Runner.from_cfg(cfg)","metadata":{"scrolled":true,"execution":{"iopub.status.busy":"2023-07-11T13:01:50.976212Z","iopub.execute_input":"2023-07-11T13:01:50.976701Z","iopub.status.idle":"2023-07-11T13:01:58.731175Z","shell.execute_reply.started":"2023-07-11T13:01:50.976595Z","shell.execute_reply":"2023-07-11T13:01:58.730160Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"path_list = [\"/kaggle/input/hubmap-hacking-the-human-vasculature/test/\"+i for i in os.listdir(\"/kaggle/input/hubmap-hacking-the-human-vasculature/test/\")]\npath_list","metadata":{"execution":{"iopub.status.busy":"2023-07-11T13:01:58.732681Z","iopub.execute_input":"2023-07-11T13:01:58.733058Z","iopub.status.idle":"2023-07-11T13:01:58.745761Z","shell.execute_reply.started":"2023-07-11T13:01:58.733026Z","shell.execute_reply":"2023-07-11T13:01:58.744697Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#img = mmcv.imread(\"/kaggle/input/hubmap-hacking-the-human-vasculature/test/72e40acccadf.tif\")\ncheckpoint_file = \"/kaggle/input/hubmap2023-maskrcnn/epoch_19.pth\"\n\nmodel = init_detector(cfg, checkpoint=checkpoint_file, device=\"cuda:0\")\nnew_result = inference_detector(model, imgs=path_list)\n# print(new_result)","metadata":{"scrolled":true,"execution":{"iopub.status.busy":"2023-07-11T13:02:27.794715Z","iopub.execute_input":"2023-07-11T13:02:27.795819Z","iopub.status.idle":"2023-07-11T13:02:28.705671Z","shell.execute_reply.started":"2023-07-11T13:02:27.795769Z","shell.execute_reply":"2023-07-11T13:02:28.704711Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# visualizer_now = Visualizer.get_current_instance()\n\n# visualizer_now.dataset_meta = model.dataset_meta\n# visualizer_now.set_image(img)\n# visualizer_now.add_datasample(\n#     'new_result',\n#     img,\n#     data_sample=new_result[0],\n#     draw_gt=True,\n#     draw_pred=True,\n#     wait_time=0,\n#     pred_score_thr=0.5\n# )\n# visualizer_now.show()","metadata":{"execution":{"iopub.status.busy":"2023-07-11T13:02:44.039178Z","iopub.execute_input":"2023-07-11T13:02:44.039560Z","iopub.status.idle":"2023-07-11T13:02:44.047087Z","shell.execute_reply.started":"2023-07-11T13:02:44.039529Z","shell.execute_reply":"2023-07-11T13:02:44.046097Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"new_result","metadata":{"scrolled":true,"execution":{"iopub.status.busy":"2023-07-11T13:02:06.871560Z","iopub.execute_input":"2023-07-11T13:02:06.871962Z","iopub.status.idle":"2023-07-11T13:02:06.900795Z","shell.execute_reply.started":"2023-07-11T13:02:06.871908Z","shell.execute_reply":"2023-07-11T13:02:06.899880Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ids = []\nheights = []\nwidths = []\nprediction_string = []\n\nfor res in new_result:\n    pr_i = res.pred_instances\n    id = res.img_path.split(\"/\")[-1][:-4]\n    shape = new_result[0].img_shape\n    height = shape[0]\n    width = shape[1]\n\n    scores = pr_i.scores.cpu().numpy()\n    masks = pr_i.masks.cpu().numpy()\n    labels = pr_i.labels.cpu().numpy()\n    # print(id, shape, height, width, scores, masks.shape)\n\n    pred_strings = []\n    ids.append(id)\n    heights.append(height)\n    widths.append(width)\n    try:\n        for score, mask, label in zip(scores, masks, labels):\n            if label != 0 and score < 0.01:\n                continue\n            # add dilate\n            kernel = np.ones(shape=(3, 3), dtype=np.uint8)\n            mask = cv2.dilate(mask.astype(np.uint8), kernel, 3)\n            mask = mask > 0\n            pred_strings.append(\" \".join([\"0\", str(score), encode_binary_mask(mask).decode()]))\n    except:\n            pred_strings = []\n    prediction_string.append(\" \".join(pred_strings))\n\nsub = pd.DataFrame({\"id\": ids, \"height\": heights, \"width\": widths, \"prediction_string\": prediction_string})\nsub = sub.set_index(\"id\")\nsub.to_csv(\"submission.csv\")","metadata":{"execution":{"iopub.status.busy":"2023-07-11T13:02:06.903941Z","iopub.execute_input":"2023-07-11T13:02:06.904217Z","iopub.status.idle":"2023-07-11T13:02:06.985321Z","shell.execute_reply.started":"2023-07-11T13:02:06.904194Z","shell.execute_reply":"2023-07-11T13:02:06.983096Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub.iloc[0,-1]","metadata":{"execution":{"iopub.status.busy":"2023-07-11T13:02:06.986762Z","iopub.execute_input":"2023-07-11T13:02:06.987140Z","iopub.status.idle":"2023-07-11T13:02:06.994124Z","shell.execute_reply.started":"2023-07-11T13:02:06.987105Z","shell.execute_reply":"2023-07-11T13:02:06.992932Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!rm -r work_dir_test","metadata":{"execution":{"iopub.status.busy":"2023-07-11T13:02:06.995653Z","iopub.execute_input":"2023-07-11T13:02:06.996546Z","iopub.status.idle":"2023-07-11T13:02:08.004827Z","shell.execute_reply.started":"2023-07-11T13:02:06.996482Z","shell.execute_reply":"2023-07-11T13:02:08.003490Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}