{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nfrom imageio import imread\nimport matplotlib.pyplot as plt\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"../input\"))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"path_train = '../input/train/'\npath_test = '../input/test/'\n\ntrain_segmentation = pd.read_csv('../input/train_ship_segmentations.csv')\ntest_segmentation = pd.read_csv('../input/test_ship_segmentations.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"35bf5863e0faf322657824f2af0145062b66b994"},"cell_type":"code","source":"# now lets check the format of our sample submission file\nsample_submission = pd.read_csv('../input/sample_submission.csv')\nsample_submission.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"cf18c726bc296e8df5a81f40204c0429816bfc88"},"cell_type":"code","source":"# referecens for two kernel\n# ref: https://www.kaggle.com/paulorzp/run-length-encode-and-decode\n# ref: https://www.kaggle.com/inversion/run-length-decoding-quick-start\n\nfrom skimage.morphology import label\ndef multi_rle_encode(img):\n    labels = label(img[:, :, 0])\n    return [rle_encode(labels==k) for k in np.unique(labels[labels>0])]\n\ndef rle_decode(mask_rle, shape=(768, 768)):\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).T  # 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.T.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\n# ref https://www.kaggle.com/kmader/baseline-u-net-model-part-1\ndef masks_as_image(in_mask_list):\n    # Take the individual ship masks and create a single mask array for all ships\n    all_masks = np.zeros((768,768))\n    for mask in img_mask:\n        all_masks += rle_decode(mask)\n    return all_masks","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"e81149c6d26ef0e62b80e4bbae85dcc80d1f5090"},"cell_type":"code","source":"# now lets do some EDA on our training data\ntrain_segmentation.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"b009db0d536b90ae6a577220fda4bb3d152bf4ac"},"cell_type":"code","source":"ImageId = '00021ddc3.jpg'\nimg = imread('../input/train/'+ImageId)\nimg_mask = train_segmentation.loc[train_segmentation['ImageId'] == ImageId, 'EncodedPixels']\nprint(img_mask)\nprint('Number os images with the same given ImageId:', len(img_mask))\nimg_mask = img_mask.tolist()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"d20c407cf8d633c56551cbe4023d976728fa5337"},"cell_type":"code","source":"# Looking at this ImageId we can see that is not a rule that in the train data the id are unique,\nall_masks_img0 = masks_as_image(img_mask)\nfig, axes = plt.subplots(nrows=1, ncols=3, figsize=(16, 16))\n\n# 'turn off' the axis for all subplots\nfor i in range(3):\n    axes[i].axis('off')\n\n# plot the original image    \naxes[0].imshow(img)\n# plot the masks of the image\naxes[1].imshow(all_masks_img0)\n# plot the image and all masks with an alpha equals 0.4\naxes[2].imshow(img)\naxes[2].imshow(all_masks_img0, alpha=0.4)\nplt.tight_layout(h_pad=0.1, w_pad=0.1)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"cddfd4c1d663ab2d5faca7ef1ac7944344c86f58"},"cell_type":"markdown","source":"### Now we must check if the encode function works"},{"metadata":{"trusted":true,"_uuid":"94fc31ea446baee167317986a57c779f12bd05d8"},"cell_type":"code","source":"fig_e, axes_e = plt.subplots(1, 2, figsize=(12,12))\naxes_e[0].axis('off')\naxes_e[1].axis('off')\naxes_e[0].set_title('Image$_0$')\naxes_e[0].imshow(all_masks_img0)\n# encode the image loaded earlier\nrle_img1 = multi_rle_encode(img)\n# read the img from the rle_img1\nimg1 = rle_decode(rle_img1)\naxes_e[1].set_title('Image$_1$')\naxes_e[1].imshow(img1)\nplt.tight_layout(h_pad=0.1, w_pad=0.1)\nplt.show()\n","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}