{"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":"import os \nimport sys\nimport random\nimport math\nimport numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nimport json\nimport pydicom\nfrom imgaug import augmenters as iaa\nfrom tqdm import tqdm\nimport pandas as pd \nimport glob\nfrom sklearn.model_selection import KFold\n\n\nDATA_DIR = '/kaggle/input'\n# Directory to save logs and trained model\nROOT_DIR = '/kaggle/working'\n\n!git clone https://www.github.com/matterport/Mask_RCNN.git\nos.chdir('Mask_RCNN')\n#!python setup.py -q install\n\n\n# Import Mask RCNN\nsys.path.append(os.path.join(ROOT_DIR, 'Mask_RCNN'))  # To find local version of the library\nfrom mrcnn.config import Config\nfrom mrcnn import utils\nimport mrcnn.model as modellib\nfrom mrcnn import visualize\nfrom mrcnn.model import log\n\n\ntrain_dicom_dir = os.path.join(DATA_DIR, 'stage_2_train_images')\ntest_dicom_dir = os.path.join(DATA_DIR, 'stage_2_test_images')\n\n!wget --quiet https://github.com/matterport/Mask_RCNN/releases/download/v2.0/mask_rcnn_coco.h5\n!ls -lh mask_rcnn_coco.h5\n\nCOCO_WEIGHTS_PATH = \"mask_rcnn_coco.h5\"","metadata":{"id":"4kjcC6QqywWl","_uuid":"40c67b3ff0fa04587dec508363308adaa3ceaf34","execution":{"iopub.status.busy":"2021-12-13T05:01:43.292256Z","iopub.execute_input":"2021-12-13T05:01:43.292659Z","iopub.status.idle":"2021-12-13T05:02:07.749882Z","shell.execute_reply.started":"2021-12-13T05:01:43.292601Z","shell.execute_reply":"2021-12-13T05:02:07.748651Z"}},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#dicom_fps is a list of the dicom image path and filenames \n#image_annotions is a dictionary of the annotations keyed by the filenames\n#parsing the dataset returns a list of the image filenames and the annotations dictionary\n\ndef get_dicom_fps(dicom_dir):\n    dicom_fps = glob.glob(dicom_dir+'/'+'*.dcm')\n    return list(set(dicom_fps))\n\ndef parse_dataset(dicom_dir, anns): \n    image_fps = get_dicom_fps(dicom_dir)\n    image_annotations = {fp: [] for fp in image_fps}\n    for index, row in anns.iterrows(): \n        fp = os.path.join(dicom_dir, row['patientId']+'.dcm')\n        image_annotations[fp].append(row)\n    return image_fps, image_annotations ","metadata":{"id":"ivqC4cnszOaM","_uuid":"778cb19865d7cc63440491aef9202b71c61e8bb2","execution":{"iopub.status.busy":"2021-12-13T05:02:07.756496Z","iopub.execute_input":"2021-12-13T05:02:07.759308Z","iopub.status.idle":"2021-12-13T05:02:07.771728Z","shell.execute_reply.started":"2021-12-13T05:02:07.759222Z","shell.execute_reply":"2021-12-13T05:02:07.770942Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# The following parameters have been selected to reduce running time for demonstration purposes \n\nclass DetectorConfig(Config):\n    \"\"\"Configuration for training pneumonia detection on the RSNA pneumonia dataset.\n    Overrides values in the base Config class.\n    \"\"\"\n    \n    # Give the configuration a recognizable name  \n    NAME = 'pneumonia'\n    \n    # Train on 1 GPU and 8 images per GPU. We can put multiple images on each\n    # GPU because the images are small. Batch size is 8 (GPUs * images/GPU).\n    GPU_COUNT = 1\n    IMAGES_PER_GPU = 8\n    \n    BACKBONE = 'resnet50'\n    \n    NUM_CLASSES = 2  # background + 1 pneumonia classes\n    \n    IMAGE_MIN_DIM = 256\n    IMAGE_MAX_DIM = 256\n    RPN_ANCHOR_SCALES = (16, 32, 64, 128)\n    TRAIN_ROIS_PER_IMAGE = 32\n    MAX_GT_INSTANCES = 4\n    DETECTION_MAX_INSTANCES = 3\n    DETECTION_MIN_CONFIDENCE = 0.78  ## match target distribution\n    DETECTION_NMS_THRESHOLD = 0.01\n\n    STEPS_PER_EPOCH = 200\n\nconfig = DetectorConfig()\nconfig.display()","metadata":{"id":"_SfzTa-1zOck","outputId":"91ae8935-bccb-4b8e-9a7e-aa690f95fd9b","_uuid":"dfcffc4eaa94a41497717851dee9f702d8a2a73b","execution":{"iopub.status.busy":"2021-12-13T05:02:07.777438Z","iopub.execute_input":"2021-12-13T05:02:07.780402Z","iopub.status.idle":"2021-12-13T05:02:07.807209Z","shell.execute_reply.started":"2021-12-13T05:02:07.780345Z","shell.execute_reply":"2021-12-13T05:02:07.806424Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class DetectorDataset(utils.Dataset):\n    \"\"\"Dataset class for training pneumonia detection on the RSNA pneumonia dataset.\n    \"\"\"\n\n    def __init__(self, image_fps, image_annotations, orig_height, orig_width):\n        super().__init__(self)\n        \n        # Add classes\n        self.add_class('pneumonia', 1, 'Lung Opacity')\n        \n        # add images \n        for i, fp in enumerate(image_fps):\n            annotations = image_annotations[fp]\n            self.add_image('pneumonia', image_id=i, path=fp, \n                           annotations=annotations, orig_height=orig_height, orig_width=orig_width)\n            \n    def image_reference(self, image_id):\n        info = self.image_info[image_id]\n        return info['path']\n\n    def load_image(self, image_id):\n        info = self.image_info[image_id]\n        fp = info['path']\n        ds = pydicom.read_file(fp)\n        image = ds.pixel_array\n        # If grayscale. Convert to RGB for consistency.\n        if len(image.shape) != 3 or image.shape[2] != 3:\n            image = np.stack((image,) * 3, -1)\n        return image\n\n    def load_mask(self, image_id):\n        info = self.image_info[image_id]\n        annotations = info['annotations']\n        count = len(annotations)\n        if count == 0:\n            mask = np.zeros((info['orig_height'], info['orig_width'], 1), dtype=np.uint8)\n            class_ids = np.zeros((1,), dtype=np.int32)\n        else:\n            mask = np.zeros((info['orig_height'], info['orig_width'], count), dtype=np.uint8)\n            class_ids = np.zeros((count,), dtype=np.int32)\n            for i, a in enumerate(annotations):\n                if a['Target'] == 1:\n                    x = int(a['x'])\n                    y = int(a['y'])\n                    w = int(a['width'])\n                    h = int(a['height'])\n                    mask_instance = mask[:, :, i].copy()\n                    cv2.rectangle(mask_instance, (x, y), (x+w, y+h), 255, -1)\n                    mask[:, :, i] = mask_instance\n                    class_ids[i] = 1\n        return mask.astype(np.bool), class_ids.astype(np.int32)","metadata":{"id":"8EBVA1M60yAj","_uuid":"52bd3ffbdde0173a363055482d675da51c2aba99","execution":{"iopub.status.busy":"2021-12-13T05:02:07.811897Z","iopub.execute_input":"2021-12-13T05:02:07.814359Z","iopub.status.idle":"2021-12-13T05:02:07.844592Z","shell.execute_reply.started":"2021-12-13T05:02:07.814303Z","shell.execute_reply":"2021-12-13T05:02:07.84334Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# training dataset\nanns = pd.read_csv(os.path.join(DATA_DIR, 'stage_2_train_labels.csv'))\nanns.head()","metadata":{"id":"EdhUEFDr0yDA","outputId":"1715a5df-a577-41fd-bf20-f1a27aadb28c","_uuid":"793b1c6c6ba4e5f0d51e130080aa799f230b5ef6","execution":{"iopub.status.busy":"2021-12-13T05:02:07.851397Z","iopub.execute_input":"2021-12-13T05:02:07.853952Z","iopub.status.idle":"2021-12-13T05:02:07.96542Z","shell.execute_reply.started":"2021-12-13T05:02:07.853895Z","shell.execute_reply":"2021-12-13T05:02:07.964447Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_fps, image_annotations = parse_dataset(train_dicom_dir, anns=anns)\nds = pydicom.read_file(image_fps[0]) # read dicom image from filepath \nimage = ds.pixel_array # get image array","metadata":{"id":"Mxz-pNbt5txY","_uuid":"7aebc88f910b232e3b8759421914a007c6ffed94","execution":{"iopub.status.busy":"2021-12-13T05:02:07.969288Z","iopub.execute_input":"2021-12-13T05:02:07.969551Z","iopub.status.idle":"2021-12-13T05:02:13.090037Z","shell.execute_reply.started":"2021-12-13T05:02:07.969503Z","shell.execute_reply":"2021-12-13T05:02:13.089286Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# show dicom fields \nds","metadata":{"id":"YPqjEIXWRhSf","_uuid":"6c386dcef041b972f6209dd19e247d547c3c349f","execution":{"iopub.status.busy":"2021-12-13T05:02:13.091934Z","iopub.execute_input":"2021-12-13T05:02:13.092326Z","iopub.status.idle":"2021-12-13T05:02:13.099849Z","shell.execute_reply.started":"2021-12-13T05:02:13.092264Z","shell.execute_reply":"2021-12-13T05:02:13.097901Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Split the data into training and validation datasets","metadata":{"id":"4FlRu8ML-ceg","_uuid":"6563bbca143e4bceb1ea850714d7b43bb1e1178d"}},{"cell_type":"code","source":"# Original DICOM image size: 1024 x 1024\nORIG_SIZE = 1024\n\nimage_fps_list = list(image_fps)\nrandom.seed(42)\nrandom.shuffle(image_fps_list)\nval_size = 1500\nimage_fps_val = image_fps_list[:val_size]\nimage_fps_train = image_fps_list[val_size:]\n\nprint(len(image_fps_train), len(image_fps_val))\n# print(image_fps_val[:6])  25184 1500","metadata":{"id":"7jByVCZt-ZOC","outputId":"f1aa267d-7530-4620-ffc5-2f7aa39083bb","_uuid":"6175c72e73639e3190e127f67783988eadced9ba","execution":{"iopub.status.busy":"2021-12-13T05:02:13.101938Z","iopub.execute_input":"2021-12-13T05:02:13.102602Z","iopub.status.idle":"2021-12-13T05:02:13.148218Z","shell.execute_reply.started":"2021-12-13T05:02:13.102549Z","shell.execute_reply":"2021-12-13T05:02:13.147165Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# prepare the training dataset\ndataset_train = DetectorDataset(image_fps_train, image_annotations, ORIG_SIZE, ORIG_SIZE)\ndataset_train.prepare()\n\n# prepare the validation dataset\ndataset_val = DetectorDataset(image_fps_val, image_annotations, ORIG_SIZE, ORIG_SIZE)\ndataset_val.prepare()\n\n# Show annotation(s) for a DICOM image \ntest_fp = random.choice(image_fps_train)\nimage_annotations[test_fp]","metadata":{"id":"jwMkhotP0yFf","_uuid":"86c3333d4dfb8b7d00ce1f401693d0df4e6254e1","execution":{"iopub.status.busy":"2021-12-13T05:02:13.150008Z","iopub.execute_input":"2021-12-13T05:02:13.150691Z","iopub.status.idle":"2021-12-13T05:02:13.242707Z","shell.execute_reply.started":"2021-12-13T05:02:13.150628Z","shell.execute_reply":"2021-12-13T05:02:13.241832Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load and display random sample and their bounding boxes\n\nclass_ids = [0]\nwhile class_ids[0] == 0:  ## look for a mask\n    image_id = random.choice(dataset_train.image_ids)\n    image_fp = dataset_train.image_reference(image_id)\n    image = dataset_train.load_image(image_id)\n    mask, class_ids = dataset_train.load_mask(image_id)\n\nprint(image.shape)\nprint(mask.shape)\n\nplt.figure(figsize=(10, 10))\nplt.subplot(1, 2, 1)\nplt.imshow(image)\nplt.axis('off')\n\nplt.subplot(1, 2, 2)\n#masked = np.zeros(image.shape[:2])\n#for i in range(mask.shape[2]):\n#    masked += image[:, :, 0] * mask[:, :, i]\n#plt.imshow(masked, cmap='gray')\nplt.imshow(image)\n\nplt.axis('off')\n\nprint(image_fp)\nprint(class_ids)","metadata":{"id":"4xwsrf9G1lHR","outputId":"a13386d3-a918-41fe-8824-13625c9d7b08","_uuid":"491b78ec96d28fcdbbf8e2d7f9320a05d64c9249","execution":{"iopub.status.busy":"2021-12-13T05:02:13.244405Z","iopub.execute_input":"2021-12-13T05:02:13.244919Z","iopub.status.idle":"2021-12-13T05:02:13.873276Z","shell.execute_reply.started":"2021-12-13T05:02:13.244711Z","shell.execute_reply":"2021-12-13T05:02:13.872355Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Image augmentation (light but constant)\naugmentation = iaa.Sequential([\n    iaa.OneOf([ ## geometric transform\n        iaa.Affine(\n            scale={\"x\": (0.98, 1.02), \"y\": (0.98, 1.04)},\n            translate_percent={\"x\": (-0.02, 0.02), \"y\": (-0.04, 0.04)},\n            rotate=(-2, 2),\n            shear=(-1, 1),\n        ),\n        iaa.PiecewiseAffine(scale=(0.001, 0.025)),\n    ]),\n    iaa.OneOf([ ## brightness or contrast\n        iaa.Multiply((0.9, 1.1)),\n        iaa.ContrastNormalization((0.9, 1.1)),\n    ]),\n    iaa.OneOf([ ## blur or sharpen\n        iaa.GaussianBlur(sigma=(0.0, 0.1)),\n        iaa.Sharpen(alpha=(0.0, 0.1)),\n    ]),\n])\n\n# test on the same image as above\nimggrid = augmentation.draw_grid(image[:, :, 0], cols=5, rows=2)\nplt.figure(figsize=(30, 12))\n_ = plt.imshow(imggrid[:, :, 0], cmap='gray')","metadata":{"id":"STZnQTE61lME","_uuid":"4ab9d6086ce611a46f189c047956c43b29783e6d","execution":{"iopub.status.busy":"2021-12-13T05:02:13.874466Z","iopub.execute_input":"2021-12-13T05:02:13.874763Z","iopub.status.idle":"2021-12-13T05:02:19.320528Z","shell.execute_reply.started":"2021-12-13T05:02:13.874702Z","shell.execute_reply":"2021-12-13T05:02:19.319769Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = modellib.MaskRCNN(mode='training', config=config, model_dir=ROOT_DIR)\n\n# Exclude the last layers because they require a matching\n# number of classes\nmodel.load_weights(COCO_WEIGHTS_PATH, by_name=True, exclude=[\n    \"mrcnn_class_logits\", \"mrcnn_bbox_fc\",\n    \"mrcnn_bbox\", \"mrcnn_mask\"])\n\nLEARNING_RATE = 0.006\n\n\n# Train Mask-RCNN Model \nimport warnings \nwarnings.filterwarnings(\"ignore\")","metadata":{"_uuid":"138d6197fc8dce9f1f8a7b5a6c27aa2069698e03","execution":{"iopub.status.busy":"2021-12-13T05:02:19.32176Z","iopub.execute_input":"2021-12-13T05:02:19.322141Z","iopub.status.idle":"2021-12-13T05:02:31.277286Z","shell.execute_reply.started":"2021-12-13T05:02:19.322098Z","shell.execute_reply":"2021-12-13T05:02:31.276351Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\nmodel.train(dataset_train, dataset_val,\n            learning_rate=LEARNING_RATE/5,\n            epochs=16,\n            layers='all',\n            augmentation=augmentation)\n\nhistory = model.keras_model.history.history\nfor k in history: history[k] = history[k] + history[k]","metadata":{"_uuid":"cf339a499519d174bcdf2311a1802f0e3acb1758","execution":{"iopub.status.busy":"2021-12-13T05:02:31.279008Z","iopub.execute_input":"2021-12-13T05:02:31.279363Z","iopub.status.idle":"2021-12-13T10:35:15.399254Z","shell.execute_reply.started":"2021-12-13T05:02:31.279297Z","shell.execute_reply":"2021-12-13T10:35:15.393404Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"epochs = range(1,len(next(iter(history.values())))+1)\npd.DataFrame(history, index=epochs)","metadata":{"_uuid":"eda9047f485f1d2e0b32b48ec2cec54a38c8535e","execution":{"iopub.status.busy":"2021-12-13T10:35:15.403058Z","iopub.execute_input":"2021-12-13T10:35:15.407293Z","iopub.status.idle":"2021-12-13T10:35:15.808962Z","shell.execute_reply.started":"2021-12-13T10:35:15.406778Z","shell.execute_reply":"2021-12-13T10:35:15.807969Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(17,5))\n\nplt.subplot(131)\nplt.plot(epochs, history[\"loss\"], label=\"Train loss\")\nplt.plot(epochs, history[\"val_loss\"], label=\"Valid loss\")\nplt.legend()\nplt.subplot(132)\nplt.plot(epochs, history[\"mrcnn_class_loss\"], label=\"Train class ce\")\nplt.plot(epochs, history[\"val_mrcnn_class_loss\"], label=\"Valid class ce\")\nplt.legend()\nplt.subplot(133)\nplt.plot(epochs, history[\"mrcnn_bbox_loss\"], label=\"Train box loss\")\nplt.plot(epochs, history[\"val_mrcnn_bbox_loss\"], label=\"Valid box loss\")\nplt.legend()\n\nplt.show()","metadata":{"_uuid":"fb3b69242b91dcc49697ff076ceeb957347372e1","execution":{"iopub.status.busy":"2021-12-13T10:35:15.813793Z","iopub.execute_input":"2021-12-13T10:35:15.814351Z","iopub.status.idle":"2021-12-13T10:35:19.711973Z","shell.execute_reply.started":"2021-12-13T10:35:15.814068Z","shell.execute_reply":"2021-12-13T10:35:19.708614Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"best_epoch = np.argmin(history[\"val_loss\"])\nprint(\"Best Epoch:\", best_epoch + 1, history[\"val_loss\"][best_epoch])","metadata":{"_uuid":"a6a00c25dfd023d27b54de963d785ca7f5f740d8","execution":{"iopub.status.busy":"2021-12-13T10:35:19.724847Z","iopub.execute_input":"2021-12-13T10:35:19.732261Z","iopub.status.idle":"2021-12-13T10:35:19.755656Z","shell.execute_reply.started":"2021-12-13T10:35:19.725362Z","shell.execute_reply":"2021-12-13T10:35:19.754102Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# select trained model \ndir_names = next(os.walk(model.model_dir))[1]\nkey = config.NAME.lower()\ndir_names = filter(lambda f: f.startswith(key), dir_names)\ndir_names = sorted(dir_names)\n\nif not dir_names:\n    import errno\n    raise FileNotFoundError(\n        errno.ENOENT,\n        \"Could not find model directory under {}\".format(self.model_dir))\n    \nfps = []\n# Pick last directory\nfor d in dir_names: \n    dir_name = os.path.join(model.model_dir, d)\n    # Find the last checkpoint\n    checkpoints = next(os.walk(dir_name))[2]\n    checkpoints = filter(lambda f: f.startswith(\"mask_rcnn\"), checkpoints)\n    checkpoints = sorted(checkpoints)\n    if not checkpoints:\n        print('No weight files in {}'.format(dir_name))\n    else:\n        checkpoint = os.path.join(dir_name, checkpoints[best_epoch])\n        fps.append(checkpoint)\n\nmodel_path = sorted(fps)[-1]\nprint('Found model {}'.format(model_path))","metadata":{"id":"eraRlzgPmmIZ","outputId":"de9e688c-ba4f-4b62-f842-dbcf00ce397c","_uuid":"db5c10d3f7da099e5751a04a6e6d49819882ecd4","execution":{"iopub.status.busy":"2021-12-13T10:35:19.759966Z","iopub.execute_input":"2021-12-13T10:35:19.773797Z","iopub.status.idle":"2021-12-13T10:35:19.870698Z","shell.execute_reply.started":"2021-12-13T10:35:19.773526Z","shell.execute_reply":"2021-12-13T10:35:19.86527Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class InferenceConfig(DetectorConfig):\n    GPU_COUNT = 1\n    IMAGES_PER_GPU = 1\n\ninference_config = InferenceConfig()\n\n# Recreate the model in inference mode\nmodel = modellib.MaskRCNN(mode='inference', \n                          config=inference_config,\n                          model_dir=ROOT_DIR)\n\n# Load trained weights (fill in path to trained weights here)\nassert model_path != \"\", \"Provide path to trained weights\"\nprint(\"Loading weights from \", model_path)\nmodel.load_weights(model_path, by_name=True)","metadata":{"id":"TgpT9AzC2Bgz","outputId":"60f5a175-4666-497d-b4e8-0bdab39a92d0","_uuid":"52138636b2ae5bf444bba808518cd8313bde65cd","execution":{"iopub.status.busy":"2021-12-13T10:35:19.873729Z","iopub.execute_input":"2021-12-13T10:35:19.874089Z","iopub.status.idle":"2021-12-13T10:36:30.373269Z","shell.execute_reply.started":"2021-12-13T10:35:19.874031Z","shell.execute_reply":"2021-12-13T10:36:30.372067Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# set color for class\ndef get_colors_for_class_ids(class_ids):\n    colors = []\n    for class_id in class_ids:\n        if class_id == 1:\n            colors.append((.941, .204, .204))\n    return colors","metadata":{"id":"9mTBig7D2BjU","_uuid":"e13c61bee23b791c61ecf1256f7512295cd4d9ab","execution":{"iopub.status.busy":"2021-12-13T10:36:30.390885Z","iopub.execute_input":"2021-12-13T10:36:30.393471Z","iopub.status.idle":"2021-12-13T10:36:30.422126Z","shell.execute_reply.started":"2021-12-13T10:36:30.392408Z","shell.execute_reply":"2021-12-13T10:36:30.416687Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Show few example of ground truth vs. predictions on the validation dataset \ndataset = dataset_val\nfig = plt.figure(figsize=(10, 30))\n\nfor i in range(6):\n\n    image_id = random.choice(dataset.image_ids)\n    \n    original_image, image_meta, gt_class_id, gt_bbox, gt_mask =\\\n        modellib.load_image_gt(dataset_val, inference_config, \n                               image_id, use_mini_mask=False)\n    \n    print(original_image.shape)\n    plt.subplot(6, 2, 2*i + 1)\n    visualize.display_instances(original_image, gt_bbox, gt_mask, gt_class_id, \n                                dataset.class_names,\n                                colors=get_colors_for_class_ids(gt_class_id), ax=fig.axes[-1])\n    \n    plt.subplot(6, 2, 2*i + 2)\n    results = model.detect([original_image]) #, verbose=1)\n    r = results[0]\n    visualize.display_instances(original_image, r['rois'], r['masks'], r['class_ids'], \n                                dataset.class_names, r['scores'], \n                                colors=get_colors_for_class_ids(r['class_ids']), ax=fig.axes[-1])","metadata":{"execution":{"iopub.status.busy":"2021-12-13T10:36:30.433855Z","iopub.execute_input":"2021-12-13T10:36:30.441629Z","iopub.status.idle":"2021-12-13T10:37:07.29581Z","shell.execute_reply.started":"2021-12-13T10:36:30.438493Z","shell.execute_reply":"2021-12-13T10:37:07.29414Z"},"trusted":true},"execution_count":null,"outputs":[]}]}