{"cells":[{"metadata":{"_uuid":"dde0af0744642f91ad6a04202d4d55c5277db422"},"cell_type":"markdown","source":"## Here is the function to convert the RLE mask to rectangle vertices. Hopefully it can help in the use transfer learning from localization models such as YOLO. Please let me know if there are quesions on this."},{"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)\nimport cv2 # image processing\nfrom skimage.io import imread\nimport matplotlib.pyplot as plt\nimport operator\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":"def rle_decode(mask_rle, mask_value=255, shape=(768,768)):\n    ## this function convert RLE encoding into image_mask\n    if type(mask_rle) == float: return None  ## My way of reading \n    \n    if type(mask_rle) == str:\n        mask_rle = [mask_rle]\n    \n    img = np.zeros(shape[0]*shape[1], dtype=np.uint8)  ## initialzing images to all 0\n    for mask in mask_rle:\n        s = mask.split()\n        starts, lengths = np.asarray(s[0::2], dtype=int)-1, np.asarray(s[1::2], dtype=int)\n        ends = starts + lengths\n        for lo, hi in zip(starts, ends):\n            img[lo:hi] = mask_value\n    return img.reshape(shape).T\n\ndef rle_to_vertices(mask_rle, return_img=False, shape=(768,768)):\n    ## This function finding out the center, length, width, angle of the RLE and return these parameters plus the image with box countour\n    if type(mask_rle) == float: return None\n    mask_img = rle_decode(mask_rle, shape=shape) # Generate masked images\n    ret, mask_img = cv2.threshold(mask_img, 127, 255, 0) \n    im2, contours, hierarchy = cv2.findContours(mask_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n    boxes = []\n    for cnt in contours:\n        rect = cv2.minAreaRect(cnt)\n        ## Storing center information so to assign ship to proper grid\n        #center_x = rect[0][1]\n        #len_x = rect[0][0]\n        #center_y = rect[1][1]\n        #len_y = rect[1][0]\n        center_x = rect[0][0]\n        center_y = rect[0][1]\n        len_x = rect[1][0]\n        len_y = rect[1][1]\n        angle = rect[2]\n        #box = cv2.boxPoints(rect)\n        #box = np.int0(box)\n        boxes.append([center_x, center_y, len_x, len_y, angle]) \n    if return_img:\n        for center_x, center_y, len_x, len_y, angle in boxes:\n            #box = cv2.boxPoints(((len_x, center_x), (len_y, center_y),angle))\n            box = cv2.boxPoints(((center_x, center_y), (len_x, len_y),angle))\n            box = np.int0(box)\n            cv2.drawContours(mask_img,[box],0,200,1)\n            #mask_img[int(center_x)-5:int(center_x)+6, int(center_y)-5:int(center_y)+6] = 200\n        return boxes, mask_img\n    else:\n        return boxes\n\ndef draw_mask(boxes, shape=(768,768)):\n    mask_img = np.zeros(shape, dtype=np.uint8)\n    if len(boxes) == 0:\n        return mask_img\n    for center_x, center_y, len_x, len_y, angle in boxes:\n        box = cv2.boxPoints(((center_x, center_y), (len_x, len_y),angle))\n        box = np.int0(box)\n        cv2.drawContours(mask_img,[box],0,200,1)\n        #mask_img[int(center_x)-5:int(center_x)+6, int(center_y)-5:int(center_y)+6] = 200\n    return mask_img","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"d4b6064e775efad68f6390e2c7391129b285f4a2"},"cell_type":"code","source":"masks = pd.read_csv('../input/train_ship_segmentations_v2.csv')\nprint(masks.shape[0], 'masks found')\nprint(masks['ImageId'].value_counts().shape[0])\nmasks['path'] = masks['ImageId'].map(lambda x: os.path.join('../input/train_v2', x))\nmasks.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"98ce33e8577275ca40eefdfc523a9984f5f2ed47"},"cell_type":"code","source":"## Show image with smallest & largest size ships alongside with masks.\n## The purpose is the test out the rle_to_vertices function.\n\nship_size_list = []\ni = 0\n\n## Finding out the size of the ships and put that into a list\nfor pixels in masks['EncodedPixels']:\n    if type(pixels) == str:\n        ship_size_list.append([i, sum([int(length) for length in pixels.split()[1::2]])])\n    i += 1\nprint('Number of ships: {}'.format(len(ship_size_list)))\nmin_index, min_value = min(ship_size_list, key=operator.itemgetter(1))\nprint('Min size of ship: {}'.format(min_value))\nprint(masks.iloc[min_index])\nmax_index, max_value = max(ship_size_list, key=operator.itemgetter(1))\nprint('Max size of ship: {}'.format(max_value))\nprint(masks.iloc[max_index])\n\nmin_pixel_list = list(masks[masks['path'] == masks.loc[min_index, 'path']]['EncodedPixels'])\nmin_mask = rle_decode(min_pixel_list)\nmin_image = imread(masks.loc[min_index, 'path'])\nprint('list length is {}'.format(len(min_pixel_list)))\nprint(min_pixel_list)\nplt.figure(figsize=(50,50))\nplt.subplot(2,2,1)\n#plt.imshow(min_mask[530:550,35:55])\nplt.imshow(min_mask)\nplt.subplot(2,2,2)\n#plt.imshow(min_image[530:550,35:55,:])\nplt.imshow(min_image)\n\nmax_pixel_list = list(masks[masks['path'] == masks.loc[max_index, 'path']]['EncodedPixels'])\nmax_mask = rle_decode(max_pixel_list)\nmax_image = imread(masks.loc[max_index, 'path'])\nprint('list length is {}'.format(len(max_pixel_list)))\n#print(min_pixel_list)\nplt.figure(figsize=(50,50))\nplt.subplot(2,2,3)\n#plt.imshow(min_mask[530:550,35:55])\nplt.imshow(max_mask)\nplt.subplot(2,2,4)\n#plt.imshow(min_image[530:550,35:55,:])\nplt.imshow(max_image)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"73d6a21aac198fa53bf85285e7833d72d65db5c7"},"cell_type":"code","source":"# Testing functions, look at the green countour of the mask. The vertices parameter can be used in training a localization model.\nvertices, img = rle_to_vertices(max_pixel_list, return_img=True)\nplt.figure(figsize=(50,50))\nplt.imshow(img)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"d8ded2b4fae490ed01e8e8acb2893317872b09be"},"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}