{"cells":[{"metadata":{"_cell_guid":"be3b4b59-a5a0-44f9-83f3-bf721420bcb4","_uuid":"1f0ed939b10c8db4906d7189d95b0683a6a9f305"},"cell_type":"markdown","source":"This is how we can visualize the ground-truth results from stage1_test solution.\n\nThis kernel is build based on the visualization function in the [Mask-RCNN](https://github.com/matterport/Mask_RCNN)\n\nCurrently, we cannot run it online because I cannot import the stage1_solution.csv file. You just download the notebook and the stage1_solution.csv and change the file location in the line `df=pd.read_csv('../input/stage1_solution.csv')`\n\n**Update**: Now, we can visualize the result\n"},{"metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","trusted":true},"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport os\nimport cv2\nimport matplotlib.pyplot as plt\nimport random\nimport itertools\nimport colorsys\nimport numpy as np\nfrom skimage.measure import find_contours\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport matplotlib.lines as lines\nfrom matplotlib.patches import Polygon\nimport IPython.display\n%matplotlib inline\n\nprint(os.listdir(\"../input\"))\n","execution_count":18,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","collapsed":true,"trusted":true},"cell_type":"code","source":"def random_colors(N, bright=True):\n    \"\"\"\n    Generate random colors.\n    To get visually distinct colors, generate them in HSV space then\n    convert to RGB.\n    \"\"\"\n    brightness = 1.0 if bright else 0.7\n    hsv = [(i / N, 1, brightness) for i in range(N)]\n    colors = list(map(lambda c: colorsys.hsv_to_rgb(*c), hsv))\n    random.shuffle(colors)\n    return colors\n\ndef apply_mask(image, mask, color, alpha=0.5):\n    \"\"\"Apply the given mask to the image.\n    \"\"\"\n    for c in range(3):\n        image[:, :, c] = np.where(mask == 1,\n                                  image[:, :, c] *\n                                  (1 - alpha) + alpha * color[c] * 255,\n                                  image[:, :, c])\n    return image","execution_count":19,"outputs":[]},{"metadata":{"_cell_guid":"0c8fd30a-0e76-4fbe-af78-ab6d8cf381fa","_uuid":"cc4ddfc73c19ec059e1d51ebbc1556a6399b8efb","collapsed":true,"trusted":true},"cell_type":"code","source":"def display_instances_mask(image, masks, figsize=(64, 64), ax=None):\n    \"\"\"\n    boxes: [num_instance, (y1, x1, y2, x2, class_id)] in image coordinates.\n    masks: [height, width, num_instances]\n    class_ids: [num_instances]\n    class_names: list of class names of the dataset\n    scores: (optional) confidence scores for each box\n    figsize: (optional) the size of the image.\n    \"\"\"\n    # Number of instances\n    N = masks.shape[2]\n    print (masks.shape)\n\n    if not ax:\n        _, ax = plt.subplots(1, figsize=figsize)\n\n    # Generate random colors\n    colors = random_colors(N)\n\n    # Show area outside image boundaries.\n    height, width = image.shape[:2]\n    ax.set_ylim(height + 10, -10)\n    ax.set_xlim(-10, width + 10)\n    ax.axis('off')\n    ax.set_title('Ground-truth')\n\n    masked_image = image.astype(np.uint32).copy()\n    for i in range(N):\n        color = colors[i]\n        # Mask\n        mask = masks[:, :, i]\n        masked_image = apply_mask(masked_image, mask, color)\n        # Mask Polygon\n        # Pad to ensure proper polygons for masks that touch image edges.\n        padded_mask = np.zeros(\n            (mask.shape[0] + 2, mask.shape[1] + 2), dtype=np.uint8)\n        padded_mask[1:-1, 1:-1] = mask\n        contours = find_contours(padded_mask, 0.5)\n        for verts in contours:\n        # Subtract the padding and flip (y, x) to (x, y)\n            verts = np.fliplr(verts) - 1\n            p = Polygon(verts, facecolor=\"none\", edgecolor=color)\n            ax.add_patch(p)\n    ax.imshow(masked_image.astype(np.uint8))\n    plt.show()","execution_count":20,"outputs":[]},{"metadata":{"_cell_guid":"03498292-fbe0-4578-a40e-9d2122d014a6","_uuid":"eb1cd4cee3ee79057ee2a30910d40cbfaac251af","collapsed":true,"trusted":true},"cell_type":"code","source":"def rle_decode(mask_rle, shape):\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[1]*shape[0], dtype=np.uint8)\n    for lo, hi in zip(starts, ends):\n        img[lo:hi] = 1\n    return img.reshape((shape[1], shape[0])).T","execution_count":21,"outputs":[]},{"metadata":{"_cell_guid":"684ff021-532b-4196-a1b7-72a31746c2b1","_uuid":"be90815c4da9932628db709ef2155f54eb00195a","collapsed":true,"trusted":true},"cell_type":"code","source":"def read_image_masks(df, image_id, plot=False):\n    image = cv2.imread('../input/data-science-bowl-2018/stage1_test/' + image_id + '/images/' + image_id + '.png')\n    shape = image.shape[:2]\n    masks=[]\n    #print (image_id)\n    for rle in df[df.ImageId == image_id].EncodedPixels:\n        try:\n            decoded_result = rle_decode(rle, shape)\n            masks.append(decoded_result)\n        except Exception as e:\n            print(e)\n            print(image_id)\n            print('---')\n    masks = np.stack(masks, axis=-1)\n    return image, masks","execution_count":22,"outputs":[]},{"metadata":{"_cell_guid":"2e449556-0535-4358-b545-67b52df2daaf","_uuid":"53a634f7e2663acf37564b22b4989ac2839dc648","trusted":true},"cell_type":"code","source":"df=pd.read_csv('../input/stage1-test-solution/stage1_solution.csv')\ndf.head()","execution_count":23,"outputs":[]},{"metadata":{"_cell_guid":"551f80db-7ed3-4d58-9999-bae09b0e4a11","_uuid":"52dc4645d092e7043c93c6c31f8f7b80a7137b4e","collapsed":true,"trusted":true},"cell_type":"code","source":"def get_ax(rows=1, cols=1, size=8):\n    \"\"\"Return a Matplotlib Axes array to be used in\n    all visualizations in the notebook. Provide a\n    central point to control graph sizes.\n\n    Change the default size attribute to control the size\n    of rendered images\n    \"\"\"\n    _, ax = plt.subplots(rows, cols, figsize=(size * cols, size * rows))\n    return ax\n","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"a206556a-2611-4268-993d-5307e30aa376","_uuid":"2c2a561f03003520b4d90045e47842752a7c0c6d","trusted":true},"cell_type":"code","source":"for image_id in df.ImageId.unique()[0:len(df.ImageId.unique())]:\n    image,masks=read_image_masks(df,image_id)    \n    display_instances_mask(image,masks, ax=get_ax())  ","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.6.4"}},"nbformat":4,"nbformat_minor":1}