{"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":"# References and Resources \n* Detectron2 Infer Notebook: [ https://www.kaggle.com/slawekbiel/positive-score-with-detectron-3-3-inference ]\n* Ensemble prediction Notebook : [ https://www.kaggle.com/ammarnassanalhajali/ensemble-nms-detectron2-inference ]\n* Detecttron Intro : [ https://towardsdatascience.com/detectron2-the-basic-end-to-end-tutorial-5ac90e2f90e3 ]\n* Another Detectron Intro: [ https://medium.com/@hirotoschwert/digging-into-detectron-2-47b2e794fabd ]\n* Inference using cellpose pretrained : [ https://www.kaggle.com/slawekbiel/cellpose-inference-307-lb ]\n* Watershed Transform Paper : [ https://arxiv.org/pdf/1611.08303.pdf ]\n","metadata":{}},{"cell_type":"markdown","source":"**Training Notebook :** \n* [ https://www.kaggle.com/virajkadam/sartorius-cell-segmentation-using-detectron2-tr ]","metadata":{}},{"cell_type":"markdown","source":"# Note:\n* As we are required to use a notebook without Internet for submission, I will detectron2 files downloaded at [ https://www.kaggle.com/slawekbiel/detectron-05 ] for installing detectron.\n* I have referred to mainly these fantastic notebook : 1: [ https://www.kaggle.com/slawekbiel/positive-score-with-detectron-3-3-inference/notebook ], 2) [ https://www.kaggle.com/ammarnassanalhajali/ensemble-nms-detectron2-inference ]","metadata":{}},{"cell_type":"markdown","source":"**Offline Install Detectron**","metadata":{}},{"cell_type":"code","source":"import os\nimport shutil","metadata":{"execution":{"iopub.status.busy":"2021-12-28T16:50:08.374924Z","iopub.execute_input":"2021-12-28T16:50:08.379140Z","iopub.status.idle":"2021-12-28T16:50:08.414169Z","shell.execute_reply.started":"2021-12-28T16:50:08.378925Z","shell.execute_reply":"2021-12-28T16:50:08.413457Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# pytorch\nimport torch, torchvision\nprint(torch.__version__)\nif  torch.cuda.is_available():\n    print('GPU \\n')\n    !nvidia-smi","metadata":{"execution":{"iopub.status.busy":"2021-12-28T16:50:08.418649Z","iopub.execute_input":"2021-12-28T16:50:08.418851Z","iopub.status.idle":"2021-12-28T16:50:11.024768Z","shell.execute_reply.started":"2021-12-28T16:50:08.418826Z","shell.execute_reply":"2021-12-28T16:50:11.023970Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# os.mkdir('detectron2')\nshutil.copytree('../input/detectron-05','detectron2')","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2021-12-28T16:50:11.028252Z","iopub.execute_input":"2021-12-28T16:50:11.028462Z","iopub.status.idle":"2021-12-28T16:50:17.338754Z","shell.execute_reply.started":"2021-12-28T16:50:11.028434Z","shell.execute_reply":"2021-12-28T16:50:17.338089Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install ./detectron2/whls/pycocotools-2.0.2/dist/pycocotools-2.0.2.tar --no-index --find-links ./detectron2/whls -q\n!pip install ./detectron2/whls/fvcore-0.1.5.post20211019/fvcore-0.1.5.post20211019 --no-index --find-links ./detectron2/whls -q\n!pip install ./detectron2/whls/antlr4-python3-runtime-4.8/antlr4-python3-runtime-4.8 --no-index --find-links ./detectron2/whls -q\n!pip install ./detectron2/whls/detectron2-0.5/detectron2 --no-index --find-links ./detectron2/whls -q","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2021-12-28T16:50:17.339885Z","iopub.execute_input":"2021-12-28T16:50:17.340128Z","iopub.status.idle":"2021-12-28T16:53:33.641685Z","shell.execute_reply.started":"2021-12-28T16:50:17.340094Z","shell.execute_reply":"2021-12-28T16:53:33.640806Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#remove copied files for detectron installation\nshutil.rmtree('detectron2')","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2021-12-28T16:53:33.644202Z","iopub.execute_input":"2021-12-28T16:53:33.644509Z","iopub.status.idle":"2021-12-28T16:53:33.728680Z","shell.execute_reply.started":"2021-12-28T16:53:33.644469Z","shell.execute_reply":"2021-12-28T16:53:33.727975Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### ","metadata":{}},{"cell_type":"markdown","source":"# Imports","metadata":{}},{"cell_type":"code","source":"#general\nimport pandas as pd \nimport numpy as np \nimport matplotlib.pyplot as plt \nimport seaborn as sns\nfrom PIL import Image\nimport cv2\nfrom pathlib import Path\nfrom fastcore.all import *\n\n# detectron\nimport detectron2\nimport torch\nfrom detectron2 import model_zoo\nfrom detectron2.engine import DefaultPredictor\nfrom detectron2.config import get_cfg\n","metadata":{"execution":{"iopub.status.busy":"2021-12-28T16:53:33.729730Z","iopub.execute_input":"2021-12-28T16:53:33.731492Z","iopub.status.idle":"2021-12-28T16:53:35.074983Z","shell.execute_reply.started":"2021-12-28T16:53:33.731462Z","shell.execute_reply":"2021-12-28T16:53:35.074290Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Data dir ","metadata":{}},{"cell_type":"code","source":"train = pd.read_csv('../input/sartorius-cell-instance-segmentation/train.csv')\n\n# path to competiton directory\ncomp_dir = Path('../input/sartorius-cell-instance-segmentation')\n\n\n\n# get test names \ntest_paths = (comp_dir/'test').ls()\n\nprint('Test Images Paths  \\n',test_paths)","metadata":{"execution":{"iopub.status.busy":"2021-12-28T16:53:35.076101Z","iopub.execute_input":"2021-12-28T16:53:35.076617Z","iopub.status.idle":"2021-12-28T16:53:35.606759Z","shell.execute_reply.started":"2021-12-28T16:53:35.076575Z","shell.execute_reply":"2021-12-28T16:53:35.605316Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Simple EDA on Training Data","metadata":{}},{"cell_type":"markdown","source":"**Class prevalence in Images**","metadata":{}},{"cell_type":"code","source":"plt.figure(figsize=(10,8))\n\n\nsns.countplot(data=train,x='cell_type')\nplt.title('Instance of each Class')\nplt.xlabel('Cell Type')\nplt.ylabel('Cell Instance Count')\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2021-12-28T16:53:35.607941Z","iopub.execute_input":"2021-12-28T16:53:35.608187Z","iopub.status.idle":"2021-12-28T16:53:35.887643Z","shell.execute_reply.started":"2021-12-28T16:53:35.608150Z","shell.execute_reply":"2021-12-28T16:53:35.887011Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"max_an=train.groupby('id').size().sort_values(ascending=False).reset_index()\nprint('Maximum annotation in a image are with ID-{}: NUM(Annot) {}'.format(max_an.iloc[0]['id'],max_an[0][0]))","metadata":{"execution":{"iopub.status.busy":"2021-12-28T16:53:35.889011Z","iopub.execute_input":"2021-12-28T16:53:35.889275Z","iopub.status.idle":"2021-12-28T16:53:35.905834Z","shell.execute_reply.started":"2021-12-28T16:53:35.889225Z","shell.execute_reply":"2021-12-28T16:53:35.904998Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('Average Annotations per Image',len(train)/train['id'].nunique())\n\nmax_an=train.groupby('id').size().sort_values(ascending=False).reset_index()\nprint('Maximum annotation in a image are with ID-{}: NUM(Annot) {}'.format(max_an.iloc[0]['id'],max_an.iloc[0][0]))\n\nprint('Min annotation in a image are with ID-{}: NUM(Annot) {}'.format(max_an.iloc[-1]['id'],max_an.iloc[-1][0]))","metadata":{"execution":{"iopub.status.busy":"2021-12-28T16:53:35.907380Z","iopub.execute_input":"2021-12-28T16:53:35.907629Z","iopub.status.idle":"2021-12-28T16:53:35.930750Z","shell.execute_reply.started":"2021-12-28T16:53:35.907595Z","shell.execute_reply":"2021-12-28T16:53:35.930086Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**We can probably use the Information here for setting thresholds**","metadata":{}},{"cell_type":"code","source":"unique_classes = train['cell_type'].unique()\n\nfor clas in unique_classes:\n    clas_df= train[train['cell_type']==clas]\n    \n    print('Average Annotations for class \"{}\" are {}'.format(clas,len(clas_df)/clas_df['id'].nunique()))\n    max_an=clas_df.groupby('id').size().sort_values(ascending=False).reset_index()\n    print('Max num of annot for {} ID-{}: NUM(Annot) {}'.format(clas,max_an.iloc[0]['id'],max_an.iloc[0][0]))\n    print('Min num of annotation for {} with ID-{}: NUM(Annot) {}'.format(clas,max_an.iloc[-1]['id'],max_an.iloc[-1][0]))\n    \n    print('-'*20,'.'*10,'-'*20)","metadata":{"execution":{"iopub.status.busy":"2021-12-28T16:53:35.933588Z","iopub.execute_input":"2021-12-28T16:53:35.933772Z","iopub.status.idle":"2021-12-28T16:53:36.001626Z","shell.execute_reply.started":"2021-12-28T16:53:35.933748Z","shell.execute_reply":"2021-12-28T16:53:36.000763Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Helper Functions","metadata":{}},{"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","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2021-12-28T16:53:36.003056Z","iopub.execute_input":"2021-12-28T16:53:36.003318Z","iopub.status.idle":"2021-12-28T16:53:36.011901Z","shell.execute_reply.started":"2021-12-28T16:53:36.003282Z","shell.execute_reply":"2021-12-28T16:53:36.011172Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load_img(path):\n    im = cv2.imread(str(path))\n    return im\n\ndef predict_masks(path,\n                  Predictor_Model, # predicted model\n                  class_thresh, # threshold for each class\n                  pixel_thresh,\n                  print_predicted_class=False): # pixel threshold for each class\n    \n    class_dict={'shsy5y':0,\n               'astro':1,\n               'cort':2}\n    \n    \n    im = load_img(path)\n    pred = Predictor_Model(im)#get prediction\n    pred_class = torch.mode(pred['instances'].pred_classes)[0] # get classes\n    \n    if print_predicted_class:\n        print(f'predicted class is {[i for i in class_dict if class_dict[i]==pred_class]}')\n    \n    take = pred['instances'].scores >= class_thresh[pred_class] # segment pixels based on what class it is from\n    pred_masks = pred['instances'].pred_masks[take]\n    pred_masks = pred_masks.cpu().numpy()\n    used = np.zeros(im.shape[:2], dtype=int) \n    \n    res = []\n    \n    for mask in pred_masks:\n        mask = mask * (1-used)\n        if mask.sum() >= pixel_thresh[pred_class]: # skip predictions with small area\n            used += mask\n            res.append(rle_encode(mask))\n            \n    return res","metadata":{"execution":{"iopub.status.busy":"2021-12-28T16:53:36.013223Z","iopub.execute_input":"2021-12-28T16:53:36.013684Z","iopub.status.idle":"2021-12-28T16:53:36.023530Z","shell.execute_reply.started":"2021-12-28T16:53:36.013639Z","shell.execute_reply":"2021-12-28T16:53:36.022736Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Load and configure trained Detectron2 Instance\n","metadata":{}},{"cell_type":"code","source":"# set params \n\n\ndetect_per_img = 1200\n\n# Individual Thresholds for each class\nclass_thresh= [.15, .45, .55]\n#pixel_thresh\npixel_thresh= [50, 80, 60]\n\n# for predictions\nids, masks=[],[]  # img ids, mask annotations\n\nimg_masks = []","metadata":{"execution":{"iopub.status.busy":"2021-12-28T17:02:40.811016Z","iopub.execute_input":"2021-12-28T17:02:40.811331Z","iopub.status.idle":"2021-12-28T17:02:40.816212Z","shell.execute_reply.started":"2021-12-28T17:02:40.811297Z","shell.execute_reply":"2021-12-28T17:02:40.815289Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**CONFIG**","metadata":{}},{"cell_type":"code","source":"#config dict\ncfg = get_cfg()\n#get model arch\ncfg.merge_from_file(model_zoo.get_config_file(\"COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml\"))\n#mask format\ncfg.INPUT.MASK_FORMAT='bitmask'\n#num of classes\ncfg.MODEL.ROI_HEADS.NUM_CLASSES = 3 \n# weights from training notebook model\ncfg.MODEL.WEIGHTS = '../input/sartorius-detectron2-model/output/model_final.pth' \n#num of detections per image\ncfg.TEST.DETECTIONS_PER_IMAGE = detect_per_img\n","metadata":{"execution":{"iopub.status.busy":"2021-12-28T17:02:51.206830Z","iopub.execute_input":"2021-12-28T17:02:51.207099Z","iopub.status.idle":"2021-12-28T17:02:51.228056Z","shell.execute_reply.started":"2021-12-28T17:02:51.207068Z","shell.execute_reply":"2021-12-28T17:02:51.227410Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Inference**","metadata":{}},{"cell_type":"code","source":"predictor = DefaultPredictor(cfg)\n\nfor i,path in enumerate(test_paths):\n    encoded_masks = predict_masks(path=path,\n                                  Predictor_Model=predictor, # predicted model\n                                  class_thresh = class_thresh, # threshold for each class\n                                  pixel_thresh = pixel_thresh,\n                                  print_predicted_class=True) # pixel threshold(area) for each class\n    \n    \n    img_masks.append(encoded_masks) # append masks for further visualization\n    for encoding in encoded_masks:\n        #save img ids\n        ids.append(path.stem)\n        # save individual encodings\n        masks.append(encoding)\n        \nprint('Number of Annotations predicted for 3 Test Images are ',len(masks))","metadata":{"execution":{"iopub.status.busy":"2021-12-28T17:02:51.856271Z","iopub.execute_input":"2021-12-28T17:02:51.856510Z","iopub.status.idle":"2021-12-28T17:02:53.670423Z","shell.execute_reply.started":"2021-12-28T17:02:51.856482Z","shell.execute_reply":"2021-12-28T17:02:53.669533Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Visualizing predictions","metadata":{}},{"cell_type":"code","source":"def show_pred(orig_img_path,predicted_mask):\n    fig,ax=plt.subplots(1,2,figsize=(16,8))\n    \n    ax[0].set_title('Original_Image')\n    ax[0].imshow(load_img(orig_img_path))\n    ax[0].axis('off')\n    \n    \n    ax[1].set_title('Predicted Mask')\n    ax[1].axis('off')\n    \n    for enc in predicted_mask:\n        decoded= rle_decode(enc)\n        ax[1].imshow(np.ma.masked_where(decoded==0, decoded))\n        \n    plt.tight_layout()\n    plt.show()\n    \n    \n    \n    \nprint('Checking first test example')\nshow_pred(test_paths[0],img_masks[0])","metadata":{"execution":{"iopub.status.busy":"2021-12-28T17:02:53.672064Z","iopub.execute_input":"2021-12-28T17:02:53.672409Z","iopub.status.idle":"2021-12-28T17:03:03.731726Z","shell.execute_reply.started":"2021-12-28T17:02:53.672369Z","shell.execute_reply":"2021-12-28T17:03:03.731085Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('Checking second test example')\nshow_pred(test_paths[1],img_masks[1])","metadata":{"execution":{"iopub.status.busy":"2021-12-28T17:03:03.733270Z","iopub.execute_input":"2021-12-28T17:03:03.733973Z","iopub.status.idle":"2021-12-28T17:03:06.496714Z","shell.execute_reply.started":"2021-12-28T17:03:03.733935Z","shell.execute_reply":"2021-12-28T17:03:06.496092Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('Checking third test example')\nshow_pred(test_paths[2],img_masks[2])","metadata":{"execution":{"iopub.status.busy":"2021-12-28T17:03:06.497957Z","iopub.execute_input":"2021-12-28T17:03:06.498564Z","iopub.status.idle":"2021-12-28T17:03:08.894102Z","shell.execute_reply.started":"2021-12-28T17:03:06.498524Z","shell.execute_reply":"2021-12-28T17:03:08.893032Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Visualizing predictions on some random train_images","metadata":{}},{"cell_type":"code","source":"im_path='../input/sartorius-cell-instance-segmentation/train/0323e81d23d9.png'\n\npred = predict_masks(path=im_path,\n                      Predictor_Model=predictor, # predicted model\n                      class_thresh = class_thresh, # threshold for each class\n                      pixel_thresh = pixel_thresh,\n                      print_predicted_class=True) # pixel threshold(area) for each class\n\n\nprint('Checking random example from train')\nshow_pred(im_path,pred)","metadata":{"execution":{"iopub.status.busy":"2021-12-28T17:03:08.896924Z","iopub.execute_input":"2021-12-28T17:03:08.897181Z","iopub.status.idle":"2021-12-28T17:03:11.280621Z","shell.execute_reply.started":"2021-12-28T17:03:08.897148Z","shell.execute_reply":"2021-12-28T17:03:11.277250Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"im_path='../input/sartorius-cell-instance-segmentation/train/0c5938ac5e3c.png'\npred = predict_masks(path=im_path,\n                      Predictor_Model=predictor, # predicted model\n                      class_thresh = class_thresh, # threshold for each class\n                      pixel_thresh = pixel_thresh,\n                      print_predicted_class=True) # pixel threshold(area) for each class\n\n\nprint('Checking random example from train')\nshow_pred(im_path,pred)","metadata":{"execution":{"iopub.status.busy":"2021-12-28T17:03:11.281886Z","iopub.execute_input":"2021-12-28T17:03:11.282589Z","iopub.status.idle":"2021-12-28T17:03:24.476475Z","shell.execute_reply.started":"2021-12-28T17:03:11.282552Z","shell.execute_reply":"2021-12-28T17:03:24.472994Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"im_path = '../input/sartorius-cell-instance-segmentation/train/17754cb5b287.png'\npred = predict_masks(path=im_path,\n                      Predictor_Model=predictor, # predicted model\n                      class_thresh = class_thresh, # threshold for each class\n                      pixel_thresh = pixel_thresh,\n                      print_predicted_class=True) # pixel threshold(area) for each class\n\n\nprint('Checking random example from train')\nshow_pred(im_path,pred)","metadata":{"execution":{"iopub.status.busy":"2021-12-28T17:03:24.477744Z","iopub.execute_input":"2021-12-28T17:03:24.478152Z","iopub.status.idle":"2021-12-28T17:03:26.516899Z","shell.execute_reply.started":"2021-12-28T17:03:24.478108Z","shell.execute_reply":"2021-12-28T17:03:26.516251Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"im_path = '../input/sartorius-cell-instance-segmentation/train/0f7d009bc5d3.png'\npred = predict_masks(path=im_path,\n                      Predictor_Model=predictor, # predicted model\n                      class_thresh = class_thresh, # threshold for each class\n                      pixel_thresh = pixel_thresh,\n                      print_predicted_class=True) # pixel threshold(area) for each class\n\n\nprint('Checking random example from train')\nshow_pred(im_path,pred)","metadata":{"execution":{"iopub.status.busy":"2021-12-28T17:03:26.518262Z","iopub.execute_input":"2021-12-28T17:03:26.518659Z","iopub.status.idle":"2021-12-28T17:03:28.899709Z","shell.execute_reply.started":"2021-12-28T17:03:26.518615Z","shell.execute_reply":"2021-12-28T17:03:28.899097Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"im_path = '../input/sartorius-cell-instance-segmentation/train/0e1e2b68fa58.png'\npred = predict_masks(path=im_path,\n                      Predictor_Model=predictor, # predicted model\n                      class_thresh = class_thresh, # threshold for each class\n                      pixel_thresh = pixel_thresh,\n                      print_predicted_class=True) # pixel threshold(area) for each class\n\n\nprint('Checking random example from train')\nshow_pred(im_path,pred)","metadata":{"execution":{"iopub.status.busy":"2021-12-28T17:03:28.900856Z","iopub.execute_input":"2021-12-28T17:03:28.901611Z","iopub.status.idle":"2021-12-28T17:03:30.991003Z","shell.execute_reply.started":"2021-12-28T17:03:28.901568Z","shell.execute_reply":"2021-12-28T17:03:30.990139Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"im_path = '../input/sartorius-cell-instance-segmentation/train/097d60b2cf71.png'\npred = predict_masks(path=im_path,\n                      Predictor_Model=predictor, # predicted model\n                      class_thresh = class_thresh, # threshold for each class\n                      pixel_thresh = pixel_thresh,\n                      print_predicted_class=True) # pixel threshold(area) for each class\n\n\nprint('Checking random example from train')\nshow_pred(im_path,pred)","metadata":{"execution":{"iopub.status.busy":"2021-12-28T17:03:30.992432Z","iopub.execute_input":"2021-12-28T17:03:30.992929Z","iopub.status.idle":"2021-12-28T17:03:33.127668Z","shell.execute_reply.started":"2021-12-28T17:03:30.992893Z","shell.execute_reply":"2021-12-28T17:03:33.127069Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"im_path = '../input/sartorius-cell-instance-segmentation/train/0cfdeeb0dded.png'\npred = predict_masks(path=im_path,\n                      Predictor_Model=predictor, # predicted model\n                      class_thresh = class_thresh, # threshold for each class\n                      pixel_thresh = pixel_thresh,\n                      print_predicted_class=True) # pixel threshold(area) for each class\n\n\nprint('Checking random example from train')\nshow_pred(im_path,pred)","metadata":{"execution":{"iopub.status.busy":"2021-12-28T17:03:33.130123Z","iopub.execute_input":"2021-12-28T17:03:33.130712Z","iopub.status.idle":"2021-12-28T17:03:35.441757Z","shell.execute_reply.started":"2021-12-28T17:03:33.130666Z","shell.execute_reply":"2021-12-28T17:03:35.440963Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"im_path ='../input/sartorius-cell-instance-segmentation/train/182c3da676bd.png'\npred = predict_masks(path=im_path,\n                      Predictor_Model=predictor, # predicted model\n                      class_thresh = class_thresh, # threshold for each class\n                      pixel_thresh = pixel_thresh,\n                      print_predicted_class=True) # pixel threshold(area) for each class\n\n\nprint('Checking random example from train')\nshow_pred(im_path,pred)","metadata":{"execution":{"iopub.status.busy":"2021-12-28T17:03:35.443256Z","iopub.execute_input":"2021-12-28T17:03:35.443525Z","iopub.status.idle":"2021-12-28T17:03:37.605728Z","shell.execute_reply.started":"2021-12-28T17:03:35.443489Z","shell.execute_reply":"2021-12-28T17:03:37.605067Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Submission","metadata":{}},{"cell_type":"code","source":"df=pd.DataFrame({'id':ids, 'predicted':masks})\ndf.to_csv('submission.csv', index=False)\n\ndf.head()","metadata":{"execution":{"iopub.status.busy":"2021-12-28T16:54:33.022975Z","iopub.execute_input":"2021-12-28T16:54:33.025683Z","iopub.status.idle":"2021-12-28T16:54:33.046858Z","shell.execute_reply.started":"2021-12-28T16:54:33.025644Z","shell.execute_reply":"2021-12-28T16:54:33.046079Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.groupby('id').size()","metadata":{"execution":{"iopub.status.busy":"2021-12-28T16:54:33.048009Z","iopub.execute_input":"2021-12-28T16:54:33.048275Z","iopub.status.idle":"2021-12-28T16:54:33.055538Z","shell.execute_reply.started":"2021-12-28T16:54:33.048223Z","shell.execute_reply":"2021-12-28T16:54:33.054843Z"},"trusted":true},"execution_count":null,"outputs":[]}]}