{"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":"I couldn't find a notebook using the new mmdet version 3.0.0, so I made one myself. Please let me know if there are any mistakes!\n\ntraining notebook is [here](https://www.kaggle.com/code/andtaichi/hubmap-mmdet-ver3-0-0-training).","metadata":{}},{"cell_type":"code","source":"!pip install -qqq /kaggle/input/mmdet3-wheels-ando/addict-2.4.0-py3-none-any.whl\n!pip install -qqq /kaggle/input/mmdet3-wheels-ando/mmengine-0.7.3-py3-none-any.whl\n!pip install -qqq /kaggle/input/mmdet3-wheels-ando/mmcv-2.0.0-cp310-cp310-linux_x86_64.whl\n!pip install -qqq /kaggle/input/pycocotools-206/wheels/pycocotools-2.0.6-cp310-cp310-linux_x86_64.whl\n!pip install -qqq /kaggle/input/mmdet3-wheels-ando/terminaltables-3.1.10-py2.py3-none-any.whl\n!pip install -qqq /kaggle/input/mmdet3-wheels-ando/mmdet-3.0.0-py3-none-any.whl","metadata":{"execution":{"iopub.status.busy":"2023-06-27T06:56:38.666177Z","iopub.execute_input":"2023-06-27T06:56:38.666436Z","iopub.status.idle":"2023-06-27T06:59:49.769113Z","shell.execute_reply.started":"2023-06-27T06:56:38.666412Z","shell.execute_reply":"2023-06-27T06:59:49.767839Z"},"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-06-27T06:59:49.771777Z","iopub.execute_input":"2023-06-27T06:59:49.772416Z","iopub.status.idle":"2023-06-27T06:59:49.788893Z","shell.execute_reply.started":"2023-06-27T06:59:49.772372Z","shell.execute_reply":"2023-06-27T06:59:49.787826Z"},"jupyter":{"source_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport os","metadata":{"execution":{"iopub.status.busy":"2023-06-27T06:59:49.790509Z","iopub.execute_input":"2023-06-27T06:59:49.790922Z","iopub.status.idle":"2023-06-27T06:59:49.801952Z","shell.execute_reply.started":"2023-06-27T06:59:49.790890Z","shell.execute_reply":"2023-06-27T06:59:49.800918Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import 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\n\n\nprint(mmdet.__version__)\nprint(mmcv.__version__)\nprint(mmengine.__version__)","metadata":{"id":"-V-93RXwT5UW","outputId":"74770888-ad8e-4148-cdd7-97ddd0aadc6f","execution":{"iopub.status.busy":"2023-06-27T06:59:49.806447Z","iopub.execute_input":"2023-06-27T06:59:49.806727Z","iopub.status.idle":"2023-06-27T06:59:55.613722Z","shell.execute_reply.started":"2023-06-27T06:59:49.806699Z","shell.execute_reply":"2023-06-27T06:59:55.612754Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%mkdir work_dir_test\n\ncfg = Config.fromfile(\"/kaggle/input/hubmap-exp001-ando/work_dir/custom_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')\nrunner = Runner.from_cfg(cfg)","metadata":{"id":"RQ5Dk2ZZeh6r","outputId":"ec542c97-8e19-438e-aaa4-8d5c9830f23d","execution":{"iopub.status.busy":"2023-06-27T06:59:55.615320Z","iopub.execute_input":"2023-06-27T06:59:55.615929Z","iopub.status.idle":"2023-06-27T07:00:03.605004Z","shell.execute_reply.started":"2023-06-27T06:59:55.615896Z","shell.execute_reply":"2023-06-27T07:00:03.603997Z"},"collapsed":true,"jupyter":{"outputs_hidden":true},"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-06-27T07:00:03.606614Z","iopub.execute_input":"2023-06-27T07:00:03.606967Z","iopub.status.idle":"2023-06-27T07:00:03.624955Z","shell.execute_reply.started":"2023-06-27T07:00:03.606929Z","shell.execute_reply":"2023-06-27T07:00:03.624079Z"},"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/hubmap-exp001-ando/work_dir/epoch_12.pth\"\n\nmodel = init_detector(cfg, checkpoint=checkpoint_file, device=\"cuda:0\")\nnew_result = inference_detector(model, imgs=path_list)\nprint(new_result)","metadata":{"execution":{"iopub.status.busy":"2023-06-27T07:00:03.628273Z","iopub.execute_input":"2023-06-27T07:00:03.628793Z","iopub.status.idle":"2023-06-27T07:00:14.708320Z","shell.execute_reply.started":"2023-06-27T07:00:03.628759Z","shell.execute_reply":"2023-06-27T07:00:14.707449Z"},"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"visualizer_now = Visualizer.get_current_instance()\n\nvisualizer_now.dataset_meta = model.dataset_meta\nvisualizer_now.set_image(img)\nvisualizer_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)\nvisualizer_now.show()","metadata":{"execution":{"iopub.status.busy":"2023-06-27T07:00:14.712456Z","iopub.execute_input":"2023-06-27T07:00:14.714815Z","iopub.status.idle":"2023-06-27T07:00:15.617484Z","shell.execute_reply.started":"2023-06-27T07:00:14.714781Z","shell.execute_reply":"2023-06-27T07:00:15.616645Z"},"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    # print(id, shape, height, width, scores, masks.shape)\n\n    pred_strings = []\n    for score, mask in zip(scores, masks):\n        pred_strings.append(\" \".join([\"0\", str(score), encode_binary_mask(mask).decode()]))\n    ids.append(id)\n    heights.append(height)\n    widths.append(width)\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-06-27T07:00:15.618463Z","iopub.execute_input":"2023-06-27T07:00:15.618775Z","iopub.status.idle":"2023-06-27T07:00:15.659912Z","shell.execute_reply.started":"2023-06-27T07:00:15.618747Z","shell.execute_reply":"2023-06-27T07:00:15.658814Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub","metadata":{"execution":{"iopub.status.busy":"2023-06-27T07:00:15.663343Z","iopub.execute_input":"2023-06-27T07:00:15.663651Z","iopub.status.idle":"2023-06-27T07:00:15.676004Z","shell.execute_reply.started":"2023-06-27T07:00:15.663625Z","shell.execute_reply":"2023-06-27T07:00:15.675135Z"},"trusted":true},"execution_count":null,"outputs":[]}]}