{"cells":[{"metadata":{"_uuid":"5c1eb3a9cd9c9177f6b6b66d4fc25be05ccdfd1a"},"cell_type":"markdown","source":"   # Airbus Ship Detection Load data\nPedro Diamel Marrero Fernandez"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"collapsed":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 os\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport cv2\n\nmatplotlib.style.use('fivethirtyeight')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"bbfdca8f17944929f66a69b890603524df77ecf8","collapsed":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"3d2ea93fcce10d7fbffa6147ec54768184431010"},"cell_type":"code","source":"path = \"../input\"\nimage_path = os.path.join(path, 'train')\nfile_masks = pd.read_csv(os.path.join(path , 'train_ship_segmentations.csv'))\nimg_ids = file_masks.groupby('ImageId').size().reset_index(name='counts')\n\nfile_data = dict(zip(img_ids['ImageId'], [[] for x in range(0, len(img_ids))] ));\nfor i,code in  file_masks.values:\n    file_data[i].append(code)\n\ndata =  [(i.split('.')[0],\n        os.path.join(image_path,'{}'.format(i)),\n        code,\n        ) for i,code in  file_data.items()  ] \n\nprint(len(data))\nprint(data[0])\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"09333bb815dd6498479f0e1c70c20a9a0720a5ed","collapsed":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    if not isinstance( mask_rle, str ):\n        return np.zeros( shape )\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\n\ndef lincomb(im1,im2,mask,alpha=0.5):\n    im = im1.copy()      \n    row, col = np.where(mask != 0)\n    for i in range( len(row) ):\n        r,c = row[i],col[i]\n        im[r,c,0] = im1[r,c,0]*(1-alpha) + im2[r,c,0]*(alpha)\n        im[r,c,1] = im1[r,c,1]*(1-alpha) + im2[r,c,1]*(alpha)\n        im[r,c,2] = im1[r,c,2]*(1-alpha) + im2[r,c,2]*(alpha)\n    return im\n\ndef setcolor(im, mask, color):    \n    tmp=im.copy()\n    tmp=np.reshape( tmp, (-1, im.shape[2])  )   \n    mask = np.reshape( mask, (-1,1))      \n    tmp[ np.where(mask>0)[0] ,:] = color\n    im=np.reshape( tmp, (im.shape)  )\n    return im\n\ndef makecolormask( masks ):\n    cmap = plt.get_cmap('jet_r')\n    colormask = np.zeros( (masks.shape[1], masks.shape[2], 3) )    \n    for i,mask in enumerate(masks):\n        color = cmap(float(i)/masks.shape[0] )\n        colormask = setcolor(colormask, mask, color[:3] )        \n    return colormask\n\ndef codes2masks( codes ):\n    masks = []\n    for code in codes:\n        masks.append( rle_decode(code, image.shape[:2]) )\n    masks = np.stack(masks, axis=0)  \n    return masks\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"ce4711191fdb5234b1706b31325aae91a563920d"},"cell_type":"code","source":"idname, ipath, codes = data[ 50 ]\nimage = cv2.imread(ipath)[:,:,(2,1,0)]\nmasks = codes2masks(codes)\n\nplt.figure( figsize=(8,8) )\nplt.imshow( lincomb( image/255, makecolormask(masks), masks.max(axis=0) , alpha=0.8 ) )\nplt.axis('off')\n\nplt.show()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"890c7c08121d92ca0ce5ae58436b9378d3a995d3","collapsed":true},"cell_type":"code","source":"matplotlib.rcParams['font.size'] = 9\nmatplotlib.rcParams['figure.figsize'] = (12,19)\n\nnumRows = 9; numCols = 5\n\nplt.figure()\nfor k in range(numRows*numCols):\n    idname, ipath, codes = data[ np.random.randint( len(data) ) ]\n    image = cv2.imread(ipath)[:,:,(2,1,0)]\n    masks = codes2masks(codes)    \n    plt.subplot(numRows,numCols,k+1); \n    plt.imshow( lincomb( image/255, makecolormask(masks), masks.max(axis=0) , alpha=0.8 ) )\n    plt.title( idname ); \n    plt.axis('off')\n    \n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"6901de6eee8b83b50af1ee46e0d9cf2e39f7158d"},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"fa481a62083689b40de803a8bcb42cd16ff758cb","collapsed":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"5fe3c04d29c2111252c06a41482c7f8d6e37f229"},"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}