{"cells":[{"metadata":{"trusted":true,"_uuid":"f206911ead9cbfed51400c34a40d70f1e806ac19"},"cell_type":"code","source":"import numpy as np\n\n\ndef rle2bbox(rle, shape):\n    '''\n    rle: run-length encoded image mask, as string\n    shape: (height, width) of image on which RLE was produced\n    Returns (x0, y0, x1, y1) tuple describing the bounding box of the rle mask\n    \n    Note on image vs np.array dimensions:\n    \n        np.array implies the `[y, x]` indexing order in terms of image dimensions,\n        so the variable on `shape[0]` is `y`, and the variable on the `shape[1]` is `x`,\n        hence the result would be correct (x0,y0,x1,y1) in terms of image dimensions\n        for RLE-encoded indices of np.array (which are produced by widely used kernels\n        and are used in most kaggle competitions datasets)\n    '''\n    \n    a = np.fromiter(rle.split(), dtype=np.uint)\n    a = a.reshape((-1, 2))  # an array of (start, length) pairs\n    a[:,0] -= 1  # `start` is 1-indexed\n    \n    y0 = a[:,0] % shape[0]\n    y1 = y0 + a[:,1]\n    if np.any(y1 > shape[0]):\n        # got `y` overrun, meaning that there are a pixels in mask on 0 and shape[0] position\n        y0 = 0\n        y1 = shape[0]\n    else:\n        y0 = np.min(y0)\n        y1 = np.max(y1)\n    \n    x0 = a[:,0] // shape[0]\n    x1 = (a[:,0] + a[:,1]) // shape[0]\n    x0 = np.min(x0)\n    x1 = np.max(x1)\n    \n    if x1 > shape[1]:\n        # just went out of the image dimensions\n        raise ValueError(\"invalid RLE or image dimensions: x1=%d > shape[1]=%d\" % (\n            x1, shape[1]\n        ))\n\n    return x0, y0, x1, y1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"81b46d8cc5aa0f9c6c3a7785514eaed0c5040331","scrolled":false},"cell_type":"code","source":"import pandas as pd\n\nfrom PIL import Image, ImageDraw\nfrom IPython.display import display\n\ndf = pd.read_csv('../input/train_ship_segmentations_v2.csv', nrows=5)\nfor _, image_filename, encoded_pixels in df[~df.EncodedPixels.isnull()].itertuples():\n    image = Image.open('../input/train_v2/' + image_filename)\n    draw = ImageDraw.Draw(image)\n    draw.rectangle(rle2bbox(encoded_pixels, (image.height, image.width)))\n    display(image)","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}