{"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":"This notebook is based on Slawek Biel's notebook (https://www.kaggle.com/slawekbiel/positive-score-with-detectron-3-3-inference)","metadata":{}},{"cell_type":"markdown","source":"#### Version history\n* V1 - test the model_best_5.pth\n* V2 - test the model_best_4.pth\n* V3 - test the model_final_6.pth\n* V4 - test the model_final_5.pth","metadata":{}},{"cell_type":"markdown","source":"## Inference and Submission\nAfter training the model ,we can inference with our trained models.","metadata":{}},{"cell_type":"markdown","source":"#### Install detectron 2","metadata":{}},{"cell_type":"code","source":"!pip install ../input/detectron-05/whls/pycocotools-2.0.2/dist/pycocotools-2.0.2.tar --no-index --find-links ../input/detectron-05/whls \n!pip install ../input/detectron-05/whls/fvcore-0.1.5.post20211019/fvcore-0.1.5.post20211019 --no-index --find-links ../input/detectron-05/whls \n!pip install ../input/detectron-05/whls/antlr4-python3-runtime-4.8/antlr4-python3-runtime-4.8 --no-index --find-links ../input/detectron-05/whls \n!pip install ../input/detectron-05/whls/detectron2-0.5/detectron2 --no-index --find-links ../input/detectron-05/whls ","metadata":{"_kg_hide-input":true,"_kg_hide-output":true,"execution":{"iopub.status.busy":"2021-12-18T12:07:01.209828Z","iopub.execute_input":"2021-12-18T12:07:01.210113Z","iopub.status.idle":"2021-12-18T12:10:04.172722Z","shell.execute_reply.started":"2021-12-18T12:07:01.210084Z","shell.execute_reply":"2021-12-18T12:10:04.171893Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import detectron2\nimport torch\nfrom detectron2 import model_zoo\nfrom detectron2.engine import DefaultPredictor\nfrom detectron2.config import get_cfg\nfrom PIL import Image\nimport cv2\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom fastcore.all import *","metadata":{"execution":{"iopub.status.busy":"2021-12-18T12:10:04.175561Z","iopub.execute_input":"2021-12-18T12:10:04.176012Z","iopub.status.idle":"2021-12-18T12:10:04.182786Z","shell.execute_reply.started":"2021-12-18T12:10:04.175973Z","shell.execute_reply":"2021-12-18T12:10:04.181063Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### Input dataset","metadata":{}},{"cell_type":"code","source":"dataDir=Path('../input/sartorius-cell-instance-segmentation')","metadata":{"execution":{"iopub.status.busy":"2021-12-18T12:10:04.185658Z","iopub.execute_input":"2021-12-18T12:10:04.185955Z","iopub.status.idle":"2021-12-18T12:10:04.197466Z","shell.execute_reply.started":"2021-12-18T12:10:04.185924Z","shell.execute_reply":"2021-12-18T12:10:04.196651Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# From https://www.kaggle.com/stainsby/fast-tested-rle\ndef rle_decode(mask_rle, shape=(520, 704)):\n    '''\n    mask_rle: run-length as string formated (start length)\n    shape: (height,width) of array to return \n    Returns numpy array, 1 - mask, 0 - background\n\n    '''\n    s = mask_rle.split()\n    starts, lengths = [np.asarray(x, dtype=int) for x in (s[0:][::2], s[1:][::2])]\n    starts -= 1\n    ends = starts + lengths\n    img = np.zeros(shape[0]*shape[1], dtype=np.uint8)\n    for lo, hi in zip(starts, ends):\n        img[lo:hi] = 1\n    return img.reshape(shape)  # Needed to align to RLE direction\n\ndef rle_encode(img):\n    '''\n    img: numpy array, 1 - mask, 0 - background\n    Returns run length as string formated\n    '''\n    pixels = img.flatten()\n    pixels = np.concatenate([[0], pixels, [0]])\n    runs = np.where(pixels[1:] != pixels[:-1])[0] + 1\n    runs[1::2] -= runs[::2]\n    return ' '.join(str(x) for x in runs)\n\ndef get_masks(fn, predictor):\n    im = cv2.imread(str(fn))\n    pred = predictor(im)\n    pred_class = torch.mode(pred['instances'].pred_classes)[0]\n    take = pred['instances'].scores >= THRESHOLDS[pred_class]\n    pred_masks = pred['instances'].pred_masks[take]\n    pred_masks = pred_masks.cpu().numpy()\n    res = []\n    used = np.zeros(im.shape[:2], dtype=int)\n    for mask in pred_masks:\n        mask = mask * (1-used)\n        if mask.sum() >= MIN_PIXELS[pred_class]: # skip predictions with small area\n            used += mask\n            res.append(rle_encode(mask))\n    return res","metadata":{"execution":{"iopub.status.busy":"2021-12-18T12:10:04.199904Z","iopub.execute_input":"2021-12-18T12:10:04.200573Z","iopub.status.idle":"2021-12-18T12:10:04.213708Z","shell.execute_reply.started":"2021-12-18T12:10:04.200537Z","shell.execute_reply":"2021-12-18T12:10:04.212991Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ids, masks=[],[]\ntest_names = (dataDir/'test').ls()","metadata":{"execution":{"iopub.status.busy":"2021-12-18T12:10:04.215239Z","iopub.execute_input":"2021-12-18T12:10:04.215847Z","iopub.status.idle":"2021-12-18T12:10:04.225806Z","shell.execute_reply.started":"2021-12-18T12:10:04.215809Z","shell.execute_reply":"2021-12-18T12:10:04.225032Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### Initiate a Predictor from the trained models","metadata":{}},{"cell_type":"code","source":"cfg = get_cfg()\ncfg.merge_from_file(model_zoo.get_config_file(\"COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml\"))\ncfg.INPUT.MASK_FORMAT='bitmask'\ncfg.MODEL.ROI_HEADS.NUM_CLASSES = 3 \ncfg.MODEL.WEIGHTS = os.path.join('../input/gyy-sartoriusmodels', \"model_final_4.pth\")  \ncfg.TEST.DETECTIONS_PER_IMAGE = 1000\npredictor = DefaultPredictor(cfg)\nTHRESHOLDS = [.15, .35, .55]\nMIN_PIXELS = [75, 150, 75]","metadata":{"execution":{"iopub.status.busy":"2021-12-19T03:13:38.200068Z","iopub.execute_input":"2021-12-19T03:13:38.200798Z","iopub.status.idle":"2021-12-19T03:13:38.286281Z","shell.execute_reply.started":"2021-12-19T03:13:38.2007Z","shell.execute_reply":"2021-12-19T03:13:38.285097Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### Look whether the outputs on a sample test file are correct or not","metadata":{}},{"cell_type":"code","source":"i=1\nencoded_masks = get_masks(test_names[i], predictor)","metadata":{"execution":{"iopub.status.busy":"2021-12-18T12:11:50.656698Z","iopub.execute_input":"2021-12-18T12:11:50.657241Z","iopub.status.idle":"2021-12-18T12:11:50.977218Z","shell.execute_reply.started":"2021-12-18T12:11:50.657206Z","shell.execute_reply":"2021-12-18T12:11:50.976476Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"_, axs = plt.subplots(1,2, figsize=(40,15))\naxs[1].imshow(cv2.imread(str(test_names[i])))\nfor enc in encoded_masks:\n    dec = rle_decode(enc)\n    axs[0].imshow(np.ma.masked_where(dec==0, dec))","metadata":{"execution":{"iopub.status.busy":"2021-12-18T12:11:52.974492Z","iopub.execute_input":"2021-12-18T12:11:52.976635Z","iopub.status.idle":"2021-12-18T12:12:07.747899Z","shell.execute_reply.started":"2021-12-18T12:11:52.976598Z","shell.execute_reply":"2021-12-18T12:12:07.74718Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### Generate masks for all the test files and create a submission","metadata":{}},{"cell_type":"code","source":"for fn in test_names:\n    encoded_masks = get_masks(fn, predictor)\n    for enc in encoded_masks:\n        ids.append(fn.stem)\n        masks.append(enc)","metadata":{"execution":{"iopub.status.busy":"2021-12-18T12:12:23.955012Z","iopub.execute_input":"2021-12-18T12:12:23.955267Z","iopub.status.idle":"2021-12-18T12:12:25.078848Z","shell.execute_reply.started":"2021-12-18T12:12:23.95524Z","shell.execute_reply":"2021-12-18T12:12:25.078111Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### Create the submission.csv","metadata":{}},{"cell_type":"code","source":"pd.DataFrame({'id':ids, 'predicted':masks}).to_csv('submission.csv', index=False)\npd.read_csv('submission.csv').head()","metadata":{"execution":{"iopub.status.busy":"2021-12-18T12:12:27.089579Z","iopub.execute_input":"2021-12-18T12:12:27.090269Z","iopub.status.idle":"2021-12-18T12:12:27.111088Z","shell.execute_reply.started":"2021-12-18T12:12:27.090233Z","shell.execute_reply":"2021-12-18T12:12:27.110405Z"},"trusted":true},"execution_count":null,"outputs":[]}]}