{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"collapsed":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport os\nimport glob\nimport cv2\nimport math\nimport seaborn as sns\nimport json\n\nsns.set()\nsns.set_palette(\"husl\")\n\nTRAIN_PATH = '../input/stage1_train/'\nTEST_PATH = '../input/stage1_test/'\n\nRANDOM_SEED=23\nOUTPUT_PATH = './'","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","collapsed":true,"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"train_ids = [x for x in os.listdir(TRAIN_PATH)]\ntest_ids = [x for x in os.listdir(TEST_PATH)]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"12b12ff1554a3bed5a00a1556e1ef3be88f03a30"},"cell_type":"code","source":"df = pd.DataFrame({'id':train_ids,'train_or_test':'train'})\ndf = df.append(pd.DataFrame({'id':test_ids,'train_or_test':'test'}))\ndf.groupby(['train_or_test']).count()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"b1602a01a8d5e0f12485d3f26ffe3ed9c41671d6"},"cell_type":"code","source":"#Building the paths for individual images:\ndf['path'] = df.apply(lambda x:'../input/stage1_{}/{}/images/{}.png'.format(x[1],x[0],x[0]), axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"cc96de666097705e1018b77cacecb667702aa747"},"cell_type":"code","source":"#Storing the shapes of the images in the dataframe:\nfrom scipy import misc\n\ndf['shape'] = ''\nfor index, row in df.iterrows():\n    image = misc.imread(row['path'])\n    df.set_value(index, 'shape', str(image.shape))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"c8a4d2c6ec53448f2a59596d42e9fe7a1f82110b"},"cell_type":"code","source":"%matplotlib inline\nfrom matplotlib import pyplot as plt\n\nagg = df[['shape','train_or_test','id']].groupby(['shape','train_or_test']).count().unstack()\nagg.columns = agg.columns.droplevel()\n\nagg.plot.barh(stacked=True,figsize=(16,4))\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"3a653dea2c20671c2f6ee0588e4601c6f379cf36"},"cell_type":"code","source":"def n_of_each(df, n = 4):\n    shapes = df['shape'].unique()\n    sample = pd.DataFrame()\n    \n    for shape in shapes:\n        sample = sample.append(df[df['shape']==shape].sample(n, replace=True))\n    \n    return sample.sort_values(by=['shape']).reset_index()\n\ndef show_image(ax,title,image):\n    ax.grid(None)\n    ax.set_title(title)\n    ax.imshow(image)\n    \ndef show_row_col(sample,cols,path_col='path',image_col=None,label_col='title',mode='file'):\n    rows = math.ceil(len(sample)/cols)\n    \n    fig, ax = plt.subplots(rows,cols,figsize=(5*cols,5*rows))\n    \n    for index, data in sample.iterrows():\n    \n        title = data[label_col]\n        if mode=='image':\n            image = np.array(data[image_col],dtype=np.uint8)\n            #image = cv2.cvtColor(image,cv2.COLOR_GRAY2RGB)\n        else:\n            image = cv2.imread(data[path_col])\n            image = cv2.cvtColor(image,cv2.COLOR_BGRA2RGB)\n\n        row = index // cols\n        col = index % cols\n        show_image(ax[row,col],title,image)\n\n    plt.show()   ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"d09a7845f1073db0bc93d0681798db67a1505f51"},"cell_type":"code","source":"sample = n_of_each(df)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f1c345d24d1991b49eb83d3f59753362720ea76e"},"cell_type":"code","source":"sample['label'] = sample[['shape','train_or_test']].apply(lambda x: '{},{}'.format(x[0],x[1]), axis=1)\nshow_row_col(sample,4,path_col='path',label_col='label',mode='file')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f2776b9e8e56a455ddae7f7815efecc727154b16"},"cell_type":"code","source":"import skimage.io\nimport skimage.segmentation\n%matplotlib inline\nplt.rcParams['figure.figsize']=10,10\n# Load a single image and its associated masks\nid = '0a7d30b252359a10fd298b638b90cb9ada3acced4e0c0e5a3692013f432ee4e9'\nfile = \"../input/stage1_train/{}/images/{}.png\".format(id,id)\nmasks = \"../input/stage1_train/{}/masks/*.png\".format(id)\nimage = skimage.io.imread(file)\nmasks = skimage.io.imread_collection(masks).concatenate()\nheight, width, _ = image.shape\nnum_masks = masks.shape[0]\n\n# Make a ground truth label image (pixel value is index of object label)\nlabels = np.zeros((height, width), np.uint16)\nfor index in range(0, num_masks):\n    labels[masks[index] > 0] = index + 1\n    \nplt.imshow(image)\nplt.imshow(labels,alpha=0.5)\nplt.grid('False')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"b68521fe74609b330f540b266742352c9c5c1ebe"},"cell_type":"code","source":"MASK_PATH_EXPR = os.path.join(TRAIN_PATH)+'{}/masks/{}.png'\nIMAGE_PATH_EXPR = os.path.join(TRAIN_PATH)+'{}/images/{}.png'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"4d8bab55cb89b560879e946e47008a173a06ab27"},"cell_type":"code","source":"def show_mask_and_image(image_id,mask_id,cx,cy,radius):\n    mask = cv2.imread(MASK_PATH_EXPR.format(image_id,mask_id),cv2.IMREAD_GRAYSCALE)\n    image = cv2.imread(IMAGE_PATH_EXPR.format(image_id,image_id))\n    image = cv2.cvtColor(image,cv2.COLOR_BGR2RGB)\n\n    fig,ax = plt.subplots(1,2,figsize=(20,20))\n    ax[0].imshow(image[cy-radius:cy+radius,cx-radius:cx+radius,:])\n    ax[0].set_title('image')\n    ax[1].imshow(mask[cy-radius:cy+radius,cx-radius:cx+radius])\n    ax[1].set_title('mask')\n    ax[0].grid('False')\n    ax[1].grid('False')\n    plt.show()\n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"d2905ad58fe76f3577e2a235e0f06e802d313da6"},"cell_type":"code","source":"image_id = '5d21acedb3015c1208b31778561f8b1079cca7487399300390c3947f691e3974'\nmask_id='5e6e650a28e22f651817b2edeacbf93a960adf633f1dbef69ecea585ef35d544'\ncx = 385\ncy = 490\nradius = 55\nshow_mask_and_image(image_id,mask_id,cx,cy,radius)","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}