{"cells":[{"metadata":{"trusted":true,"_uuid":"8326bde60bd176981d52cb6951d670cd064a6aca"},"cell_type":"code","source":"import os\nimport cv2\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{"scrolled":true,"trusted":true,"_uuid":"b7d8ee00d52de397696a786172049ac2c10aff9b"},"cell_type":"code","source":"ship_dir = '../input'\ntrain_image_dir = os.path.join(ship_dir, 'train')\ntest_image_dir = os.path.join(ship_dir, 'test')\nboundaries = pd.read_csv(os.path.join(ship_dir, 'train_ship_segmentations.csv'))\nboundaries.head()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"e03a269d21a784116d9b38aa189806226bf76468"},"cell_type":"markdown","source":"### Check how many images has ships and how many not"},{"metadata":{"trusted":true,"_uuid":"bc71e3deec17a7605a87719b4f3f4ab900163d7c"},"cell_type":"code","source":"not_empty = pd.notna(boundaries.EncodedPixels)\nprint(\"{} images(has ships) with {} masks\".format(boundaries[not_empty].ImageId.nunique(), not_empty.sum()))\nprint('{} images(with no ships) in {} total images'.format((~not_empty).sum(), boundaries.ImageId.nunique()))","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"6f3ce0a2eab2b46aa578d914c803183acb3c43f3"},"cell_type":"markdown","source":"### Get image paths"},{"metadata":{"trusted":true,"_uuid":"0fc850f27037dc218c90def16596362c796935e1"},"cell_type":"code","source":"# GET IMAGE PATHS\nimage_paths = []\nfor root, dirs, files in os.walk(train_image_dir):\n    for imgname in files:\n        image_paths.append(os.path.join(root, imgname))\nprint(len(image_paths), \"Images found\")\nprint(\"Sample image path:\", image_paths[0])","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"cee02e5e75c37bcff4199871f4bf64601f857454"},"cell_type":"markdown","source":"### Some parameters"},{"metadata":{"trusted":true,"_uuid":"41fa04b509063751562d6a230ab9c6e4e4e04318"},"cell_type":"code","source":"# PARAMETERS\nMASK_SHAPE = (768, 768)\nSAMPLE_SIZE = 20","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"22c33be1d6b28e0531ed1a5ead2382e54b3aa2cd"},"cell_type":"markdown","source":"### Convert RLE to Masks"},{"metadata":{"trusted":true,"_uuid":"b6c49b51675f25e45f647e46da227f2412b3c36f"},"cell_type":"code","source":"# Boundaries to MASK per image\ndef rle_to_mask_per_image(boundaries):\n    mask_dict = {}\n    for (imgID, rle) in boundaries.itertuples(index=False):\n        \n        # add new key\n        if imgID not in mask_dict.keys():\n            mask_dict[imgID] = []\n        else:\n            pass\n        \n        # Create empty mask\n        _mask = np.zeros(MASK_SHAPE, dtype=np.uint8)\n        \n        # create mask from boundaries\n        if str(rle) == 'nan':\n            mask_dict[imgID].append(_mask)\n        else:\n            rle = rle.split(' ')\n            for i in range(0, len(rle)-1, 2):\n                _mask = _mask.flatten()\n                # whiten given pixels\n                _mask[int(rle[i]): int(rle[i])+int(rle[i+1])] = 255\n            mask_dict[imgID].append(_mask.reshape(MASK_SHAPE))\n    \n    # merge masks into one mask of single image\n    mask_per_image_dict = {}        \n    for key in mask_dict.keys():\n        # Empty mask for joining all masks\n        mastermask = np.zeros(MASK_SHAPE, dtype=np.uint8)\n        for mask in mask_dict[key]:\n            mastermask |= mask.T\n        mask_per_image_dict[key] = mastermask\n    return mask_per_image_dict","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"c8ecd75861f5f0927637d23b331604511a6aee5d"},"cell_type":"markdown","source":"## Visualization"},{"metadata":{"trusted":true,"_uuid":"e87ec205843079a47ca43a4b543b34c5870427e1"},"cell_type":"code","source":"# GET SAMPLE IMAGES AND MASKS\nsample_masks_dict = rle_to_mask_per_image(boundaries.head(SAMPLE_SIZE))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"b6fcbe5ead6a7f48b742367499b3dec5c3563ccb"},"cell_type":"code","source":"# SHARPEN IMAGES\nkernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]])\ndef sharpen(img):\n    return cv2.filter2D(img, -1, kernel)","execution_count":null,"outputs":[]},{"metadata":{"scrolled":false,"trusted":true,"_uuid":"330a81a8afb1802407697455f70a7deb8523d984"},"cell_type":"code","source":"for key in sample_masks_dict.keys():\n    plt.figure(figsize=(15,20))\n    plt.subplot(1,2,1)\n    plt.axis('off')\n    plt.title(\"Image\")\n    img = plt.imread(os.path.join(train_image_dir, key))\n    # Make image sharp if needed\n    #img = sharpen(img)\n    plt.imshow(img)\n    plt.subplot(1,2,2)\n    plt.axis('off')\n    plt.title(\"Mask\")\n    plt.imshow(sample_masks_dict[key], cmap='gray')\n    plt.show()\n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"02b8e3e2bfc0d5cdd61dc0f02b0e7af83d4e4501"},"cell_type":"code","source":"","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}