{"cells":[{"metadata":{"trusted":true,"_uuid":"11f094394a458730b20de5be576878e059e5456e"},"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\nfrom imgaug import augmenters as iaa\nfrom tqdm import tqdm\nimport pandas as pd \nimport glob\nfrom PIL import Image","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"7c069177892057f4bcb531f5f1bb4b3993252ed2"},"cell_type":"code","source":"DATA_DIR = '/kaggle/input/airbus-ship-detection'\n#DATA_DIR = '/kaggle/input'\n# Directory to save logs and trained model\nROOT_DIR = '/kaggle/working'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"18f34f305259cedba7367b0e9300a7364d53d800"},"cell_type":"code","source":"!git clone https://www.github.com/matterport/Mask_RCNN.git\nos.chdir('Mask_RCNN')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1fd0720734349e1c4652ddd0ca3ae4eb7170ecfa"},"cell_type":"code","source":"# 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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"4c63672b8667cace1722cefbe92fe9a97f9e1f92"},"cell_type":"code","source":"# The following parameters have been selected to reduce running time for demonstration purposes \n# These are not optimal \n\nclass DetectorConfig(Config):    \n    # Give the configuration a recognizable name  \n    NAME = 'airbus'\n    \n    GPU_COUNT = 1\n    #IMAGES_PER_GPU = 9\n    IMAGES_PER_GPU = 8\n    \n    #BACKBONE = 'resnet50'\n    BACKBONE = 'resnet50'\n    \n    NUM_CLASSES = 2  # background and ship classes\n    \n    IMAGE_MIN_DIM = 384\n    IMAGE_MAX_DIM = 384\n    RPN_ANCHOR_SCALES = (8, 16, 32, 64)\n    TRAIN_ROIS_PER_IMAGE = 64\n    MAX_GT_INSTANCES = 14\n    DETECTION_MAX_INSTANCES = 10\n    DETECTION_MIN_CONFIDENCE = 0.95\n    DETECTION_NMS_THRESHOLD = 0.0\n\n    STEPS_PER_EPOCH = 15\n    VALIDATION_STEPS = 10\n    \n    ## balance out losses\n    LOSS_WEIGHTS = {\n        \"rpn_class_loss\": 20.0,\n        \"rpn_bbox_loss\": 0.8,\n        \"mrcnn_class_loss\": 6.0,\n        \"mrcnn_bbox_loss\": 1.0,\n        \"mrcnn_mask_loss\": 1.2\n    }\n\nconfig = DetectorConfig()\nconfig.display()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1052e92579dc5bfe8b10907836557c33a5dc9367"},"cell_type":"code","source":"import os\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nfrom skimage.io import imread\nfrom skimage.transform import resize\nimport matplotlib.pyplot as plt\nfrom matplotlib.cm import get_cmap\nfrom skimage.segmentation import mark_boundaries\nfrom skimage.util import montage\nfrom skimage.morphology import binary_opening, disk, label\nimport gc; gc.enable()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a972f1a3e96b5812984e880261542350d003d50b"},"cell_type":"code","source":"mytest_dir = '/kaggle/input/manual-test'\nmytest_names = [f for f in os.listdir(mytest_dir)]","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"from keras.models import model_from_json,load_model\nmodel = modellib.MaskRCNN(mode='training', config=config, model_dir=ROOT_DIR)\nclass 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)\nmodel.load_weights('/kaggle/input/finalmodel/mask_rcnn_airbus_0022.h5',by_name=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"9f1bf73b1f1c8b02f6775463df2b6c9775e320b5"},"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","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"test1 = imread('/kaggle/input/manual-test/test_image1.jpg')\n#test1 = resize(test1,(384,384,3))\nsize1 = test1.shape[0]\n_ = plt.imshow(test1)\nsize1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"d7971624b26142f3ba7336ed19a3b70094ecfab1"},"cell_type":"code","source":"fig = plt.figure(figsize=(10, 100))\n\nfor i in range(20):\n\n    image = imread(os.path.join('/kaggle/input/manual-test', mytest_names[i]))\n    plt.subplot(20, 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    plt.imshow(image)\n    plt.subplot(20, 2, 2*i + 2)\n    results = model.detect([image]) #, verbose=1)\n    r = results[0]\n    visualize.display_instances(image, r['rois'], r['masks'], r['class_ids'], \n                                'ship', r['scores'], \n                                colors=get_colors_for_class_ids(r['class_ids']), ax=fig.axes[-1])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"6ea86dd993456b907325ba36dffe641ff1fa0cb8"},"cell_type":"code","source":"for name in mytest_names:\n    image = imread(os.path.join('/kaggle/input/manual-test', name))\n    results = model.detect([image])\n    fig,ax = plt.subplots(1,1,figsize=(10,10))\n    r = results[0]\n    visualize.display_instances(image, r['rois'], r['masks'], r['class_ids'], \n                                'ship', r['scores'], \n                                colors=get_colors_for_class_ids(r['class_ids']),ax=ax)\n    plt.savefig(os.path.join(ROOT_DIR, name))\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"8224f84dfc6f7af6c270dbb2ad959e4b544ace67"},"cell_type":"code","source":"!rm -rf /kaggle/working/Mask_RCNN","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}