{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"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\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport keras\nfrom PIL import Image as im\nimport matplotlib.pyplot as plt\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\n\"\"\"for dirname, _, filenames in os.walk('/kaggle/input/hubmap-organ-segmentation'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\"\"\"\n\nBASE_DIR = \"/kaggle/input/hubmap-organ-segmentation\"\nWORKING_DIR = \"./\"\nprint(os.listdir(BASE_DIR))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-09-28T12:50:49.890585Z","iopub.execute_input":"2022-09-28T12:50:49.891133Z","iopub.status.idle":"2022-09-28T12:50:53.689860Z","shell.execute_reply.started":"2022-09-28T12:50:49.891031Z","shell.execute_reply":"2022-09-28T12:50:53.688216Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df = pd.read_csv(os.path.join(BASE_DIR,\"train.csv\"))\ntrain_df.head()\ntest_df = pd.read_csv(os.path.join(BASE_DIR,\"test.csv\"))\ntest_df.head()","metadata":{"execution":{"iopub.status.busy":"2022-09-28T12:50:53.691997Z","iopub.execute_input":"2022-09-28T12:50:53.692756Z","iopub.status.idle":"2022-09-28T12:50:54.173450Z","shell.execute_reply.started":"2022-09-28T12:50:53.692716Z","shell.execute_reply":"2022-09-28T12:50:54.172121Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#adding image_labels col to train dataframe and test dataframe\nimage_labels = []\nfor index, row in train_df.iterrows():\n    image_labels.append(str(row['id'])+'.tiff')\n    #print(index)\ntrain_df['img_labels'] = image_labels\n#print(train_df.head())\n\ntest_image_labels = []\nfor index, row in test_df.iterrows():\n    test_image_labels.append(str(row['id'])+'.tiff')\n    #print(index)\ntest_df['img_labels'] = test_image_labels\n\n#adding test_mask col to test dataframe\ntest_df['test_mask'] = ''\n#test_df.head()","metadata":{"execution":{"iopub.status.busy":"2022-09-28T12:50:54.175238Z","iopub.execute_input":"2022-09-28T12:50:54.176416Z","iopub.status.idle":"2022-09-28T12:50:54.209384Z","shell.execute_reply.started":"2022-09-28T12:50:54.176363Z","shell.execute_reply":"2022-09-28T12:50:54.208392Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_image_dir = os.path.join(BASE_DIR,\"train_images\")\ntest_image_dir = os.path.join(BASE_DIR,\"test_images\")\n#print(os.listdir(train_images))\n# function to get image paths from train and test directory\ndef getImagePaths(path):\n    image_names = []\n    for dirname, _, filenames in os.walk(path):\n        for filename in filenames:\n            fullpath = os.path.join(dirname, filename)\n            image_names.append(fullpath)\n    return image_names\ntrain_img_paths = getImagePaths(train_image_dir)\nprint(train_img_paths[0])\nprint(len(train_img_paths))","metadata":{"execution":{"iopub.status.busy":"2022-09-28T12:50:54.212654Z","iopub.execute_input":"2022-09-28T12:50:54.213530Z","iopub.status.idle":"2022-09-28T12:50:54.226131Z","shell.execute_reply.started":"2022-09-28T12:50:54.213477Z","shell.execute_reply":"2022-09-28T12:50:54.224993Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#method to create mask from the given rle\ndef rle2mask(rle_str, shape):\n    #split rle string into start positions(ie.pixels) and their res. lengths\n    split_list = rle_str.split()\n    starts = split_list[0::2] #starting with 0 index, jump to 2nd index(ie.skip one position)\n    lengths = split_list[1::2] #starting with 1 index, jump to 2nd index\n    #starts -= 1 \n    starts = np.asarray(starts,dtype=int)\n    lengths = np.asarray(lengths,dtype=int)\n    starts -= 1 \n    #print(starts, lengths)\n    #initialise mask 1-D matrix of size (height X width) of image \n    mask = np.zeros((shape[0]*shape[1]))\n    #creating mask with ones(masked pixels) and zeros(unmasked)\n    for (start,length) in zip(starts,lengths): \n        #print(start, length)\n        #start = int(start) - 1\n        #length = int(length)\n        mask[start: start+length] = 1\n    #print(mask)\n    #reshape mask matrix as per given requirements\n    #https://www.kaggle.com/competitions/hubmap-organ-segmentation/overview/supervised-ml-evaluation\n    mask = (mask.reshape(shape[0], shape[1])).T #outputs mask with axes reversed\n    #mask = mask.flatten()\n    #print(mask)\n    return mask","metadata":{"execution":{"iopub.status.busy":"2022-09-28T12:50:54.227952Z","iopub.execute_input":"2022-09-28T12:50:54.228327Z","iopub.status.idle":"2022-09-28T12:50:54.240544Z","shell.execute_reply.started":"2022-09-28T12:50:54.228295Z","shell.execute_reply":"2022-09-28T12:50:54.238944Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#adding masked images to train_df\nmaskedImages = []\n#rles = train_df['rle']\nfor index, row in train_df.iterrows():\n    maskedImages.append(rle2mask(row['rle'],(row['img_height'],row['img_width'])))\n    #print(index)\ntrain_df['masked_img'] = maskedImages\n#train_df.head()","metadata":{"execution":{"iopub.status.busy":"2022-09-28T12:50:54.242013Z","iopub.execute_input":"2022-09-28T12:50:54.242392Z","iopub.status.idle":"2022-09-28T12:50:59.995028Z","shell.execute_reply.started":"2022-09-28T12:50:54.242359Z","shell.execute_reply":"2022-09-28T12:50:59.993638Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#os.remove('./mask_img0.png')\n#os.removedirs('/kaggle/working/maskedImages')\n#os.mkdir('/kaggle/working/maskedImages')\n#from PIL import Image as im\n#mask_img = im.fromarray(train_df['masked_img'][0])\n#mask_img = mask_img.convert('L')\n#mask_img.save('./maskedImages/mask_img0.tiff')\n#print(mask_img)\n#Img0 = plt.imread('./mask_img0.tiff')\n#from matplotlib import pyplot as plt\n#plt.imshow(Img0, interpolation='nearest')\n#plt.imshow(mask_img,cmap='hot',alpha=0.5)\n#plt.show()","metadata":{"_kg_hide-output":true,"execution":{"iopub.status.busy":"2022-09-28T12:50:59.996699Z","iopub.execute_input":"2022-09-28T12:50:59.997865Z","iopub.status.idle":"2022-09-28T12:51:00.003973Z","shell.execute_reply.started":"2022-09-28T12:50:59.997816Z","shell.execute_reply":"2022-09-28T12:51:00.002667Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#\"\"\"\n#creating masked images in working folder\nos.makedirs('/kaggle/working/maskedImages/masks')\nfrom PIL import Image as im\n#mask_img = im.fromarray(train_df['masked_img'][0])\n#mask_img = mask_img.convert('L')\n#mask_img.save('./maskedImages/mask_img0.tiff')\nfor index, row in train_df.iterrows():\n    mask_img = im.fromarray(row['masked_img'])\n    mask_img = mask_img.convert('L')\n    mask_img.save('./maskedImages/masks/'+row['img_labels'])\n\nos.makedirs('/kaggle/working/trainImages/train')\n\n\n#import shutil\n#shutil.rmtree(\"/kaggle/working/maskedImages\")\n\nfrom distutils.dir_util import copy_tree\nfromDirectory = '../input/hubmap-organ-segmentation/train_images'\ntoDirectory = './trainImages/train'\ncopy_tree(fromDirectory, toDirectory)\n#\"\"\"\n\n\"\"\"\nos.makedirs('/kaggle/working/testImages/test')\nfrom distutils.dir_util import copy_tree\nfromDirectory = '../input/hubmap-organ-segmentation/test_images'\ntoDirectory = './testImages/test'\ncopy_tree(fromDirectory, toDirectory)\n\"\"\"","metadata":{"execution":{"iopub.status.busy":"2022-09-28T12:51:00.005596Z","iopub.execute_input":"2022-09-28T12:51:00.006124Z","iopub.status.idle":"2022-09-28T12:51:00.028790Z","shell.execute_reply.started":"2022-09-28T12:51:00.006077Z","shell.execute_reply":"2022-09-28T12:51:00.027342Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#creating directory for masked Images\ntrain_mask_dir = os.path.join(WORKING_DIR,\"maskedImages\")\n#print(os.listdir(train_images))\n# function to get image paths from train and test directory\ndef getImagePaths(path):\n    image_names = []\n    for dirname, _, filenames in os.walk(path):\n        for filename in filenames:\n            fullpath = os.path.join(dirname, filename)\n            image_names.append(fullpath)\n    return image_names\ntrain_mask_paths = getImagePaths(train_mask_dir)\n#print(train_mask_paths[3])\nprint(len(train_mask_paths))","metadata":{"execution":{"iopub.status.busy":"2022-09-28T12:51:00.031099Z","iopub.execute_input":"2022-09-28T12:51:00.031929Z","iopub.status.idle":"2022-09-28T12:51:00.041502Z","shell.execute_reply.started":"2022-09-28T12:51:00.031890Z","shell.execute_reply":"2022-09-28T12:51:00.040524Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\"\"\"\n#test run\nsample_mask_0 = train_df['masked_img'][0]\nmaskedImage = sample_mask_0.astype(float)\n#getting train image with same id\nimage_0 = os.path.join(train_image_dir,str(train_df['id'][0])+\".tiff\")\nprint(image_0)\nImg = plt.imread(image_0)\n#superimposing train image with masked image\nplt.imshow(Img, interpolation='nearest')\nplt.imshow(maskedImage,cmap='hot',alpha=0.5)\nplt.show()\nprint(Img.shape)\n\"\"\"","metadata":{"execution":{"iopub.status.busy":"2022-09-28T12:51:00.045661Z","iopub.execute_input":"2022-09-28T12:51:00.046802Z","iopub.status.idle":"2022-09-28T12:51:00.052864Z","shell.execute_reply.started":"2022-09-28T12:51:00.046739Z","shell.execute_reply":"2022-09-28T12:51:00.051757Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#method to get rle data from given mask\ndef mask2rle(mask, shape):\n    starts = []\n    lengths = []\n    #mask = mask.reshape(shape[1],shape[0])#here axes are reversed because we left the mask with axes reversed before flattening\n    mask = mask.T #required for using flat iterater\n    size_mask = mask.size\n    count_ones = 0\n    for i in range(size_mask):\n        if(mask.flat[i] == 1):\n            if(count_ones == 0):\n                starts.append(i+1)\n            count_ones += 1\n        else:\n            if(count_ones > 0):\n                lengths.append(count_ones)\n            count_ones = 0\n    return list(zip(starts,lengths))\n    ","metadata":{"execution":{"iopub.status.busy":"2022-09-28T12:51:00.054299Z","iopub.execute_input":"2022-09-28T12:51:00.055468Z","iopub.status.idle":"2022-09-28T12:51:00.068600Z","shell.execute_reply.started":"2022-09-28T12:51:00.055418Z","shell.execute_reply":"2022-09-28T12:51:00.067337Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#test run rle2mask()\nsample_mask = rle2mask(\"1 2 4 3\",(5,3)) \nprint(sample_mask)\n#sample_mask_2d = sample_mask.reshape(3,5)#because we left the mask with axes reversed before flattening\n#print(sample_mask_2d)\n#maskedImage = sample_mask.astype(float)\n#print(maskedImage)\nplt.imshow(sample_mask, cmap='hot')\n#plt.imshow(maskedImage, cmap='hot')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-09-28T12:51:00.070105Z","iopub.execute_input":"2022-09-28T12:51:00.071214Z","iopub.status.idle":"2022-09-28T12:51:00.236088Z","shell.execute_reply.started":"2022-09-28T12:51:00.071111Z","shell.execute_reply":"2022-09-28T12:51:00.234792Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#test run mask2rle()\not = mask2rle(sample_mask,(5,3))\nprint(ot)\n\"\"\"\nfor tup in ot:\n    #print(tup)\n    t = convertTuple(tup)\n    print(t)\n#print(listToString(convertTupleList(ot)))\nprint(convertTupleList(ot))\n\"\"\"","metadata":{"execution":{"iopub.status.busy":"2022-09-28T12:51:00.238128Z","iopub.execute_input":"2022-09-28T12:51:00.238640Z","iopub.status.idle":"2022-09-28T12:51:00.250158Z","shell.execute_reply.started":"2022-09-28T12:51:00.238593Z","shell.execute_reply":"2022-09-28T12:51:00.248796Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\"\"\"\n#test run rle2mask()\nrle1 = train_df['rle'][3]\nsample_mask = rle2mask(rle1,(3000,3000))\n#maskedImage = sample_mask.astype(float)\n#print(maskedImage)\n\n#getting train image with same id\nimage_1 = os.path.join(train_image_dir,str(train_df['id'][3])+\".tiff\")\n#print(image_1)\nI = plt.imread(image_1)\n#superimposing train image with masked image\nplt.imshow(I, interpolation='nearest')\nplt.imshow(sample_mask,cmap='hot',alpha=0.5)\n#plt.imshow(maskedImage,cmap='hot',alpha=0.5)\nplt.show()\n\"\"\"","metadata":{"execution":{"iopub.status.busy":"2022-09-28T12:51:00.252315Z","iopub.execute_input":"2022-09-28T12:51:00.253469Z","iopub.status.idle":"2022-09-28T12:51:02.730574Z","shell.execute_reply.started":"2022-09-28T12:51:00.253415Z","shell.execute_reply":"2022-09-28T12:51:02.729072Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# we create two instances with the same arguments\nfrom keras.preprocessing.image import ImageDataGenerator\n\nimage_datagen = ImageDataGenerator(\n    rescale=1./255)\nmask_datagen = ImageDataGenerator()\n    #rescale=1./255)\ntest_datagen = ImageDataGenerator(\n    rescale=1./255)\nimage_generator = image_datagen.flow_from_directory(\n    directory= './trainImages',\n    target_size=(256,256),\n    batch_size=27,\n    class_mode=None)\nmask_generator = mask_datagen.flow_from_directory(\n    #directory = train_mask_dir,\n    directory = './maskedImages',\n    target_size=(256,256),\n    batch_size=27,\n    class_mode=None)\n#\"\"\"\ntest_generator = test_datagen.flow_from_dataframe(\n    dataframe=test_df,\n    directory='../input/hubmap-organ-segmentation/test_images',\n    x_col=\"img_labels\",\n    y_col=\"test_mask\",\n    target_size=(256,256),\n    #batch_size=5,\n    class_mode=None,\n    shuffle=False)","metadata":{"execution":{"iopub.status.busy":"2022-09-28T12:51:02.732487Z","iopub.execute_input":"2022-09-28T12:51:02.732945Z","iopub.status.idle":"2022-09-28T12:51:03.043057Z","shell.execute_reply.started":"2022-09-28T12:51:02.732904Z","shell.execute_reply":"2022-09-28T12:51:03.041877Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras import layers\nfrom keras import models\nfrom keras import Input\nfrom keras.models import Model\nx = Input(shape=(256,256,3))\nbranch_a = layers.Conv2D(32,1,activation='relu')(x)\n\nbranch_b = layers.Conv2D(128,1,activation='relu')(x)\nbranch_b = layers.Conv2D(32,3,activation='relu',padding='same')(branch_b)\n\n#branch_c = layers.AveragePooling2D(3,strides=2,padding='same')(x)\n#branch_c = layers.Conv2D(128,3,activation='relu',padding='same')(branch_c)\n\nbranch_d = layers.Conv2D(128,1,activation='relu')(x)\nbranch_d = layers.Conv2D(128,3,activation='relu',padding='same')(branch_d)\nbranch_d = layers.Conv2D(32,3,activation='relu',padding='same')(branch_d)\n\noutput = layers.concatenate([branch_a, branch_b, branch_d], axis=-1)\ny = layers.Conv2D(3,1,activation='relu')(output)\nmodel = Model(x,y)\n#model.summary()","metadata":{"execution":{"iopub.status.busy":"2022-09-28T12:51:03.044823Z","iopub.execute_input":"2022-09-28T12:51:03.046074Z","iopub.status.idle":"2022-09-28T12:51:03.348078Z","shell.execute_reply.started":"2022-09-28T12:51:03.046032Z","shell.execute_reply":"2022-09-28T12:51:03.346853Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\"\"\"\n#defining layers for model training\nmodel = models.Sequential()\nmodel.add(layers.Conv2D(32, (1,1), activation='relu'))\n#model.add(layers.MaxPooling2D((2,2)))\nmodel.add(layers.Conv2D(128, (1,1), activation='relu'))\nmodel.add(layers.Conv2D(128, (1,1), activation='relu'))\n#model.add(layers.MaxPooling2D((2,2)))\nmodel.add(layers.Conv2D(128, (1,1), activation='relu'))\nmodel.add(layers.Conv2D(32, (1,1), activation='relu'))\n#model.add(layers.Conv2D(32, (1,1), activation='relu'))\n#model.add(layers.MaxPooling2D((2,2)))\nmodel.add(layers.Conv2D(3, (1,1), activation='relu'))\n#model.add(layers.Conv2D(3, (1,1), activation='sigmoid'))\n#model.add(layers.Conv2D(3, (1,1), activation='relu'))\n#model.summary()\n\"\"\"","metadata":{"execution":{"iopub.status.busy":"2022-09-28T12:51:03.350047Z","iopub.execute_input":"2022-09-28T12:51:03.350928Z","iopub.status.idle":"2022-09-28T12:51:03.360538Z","shell.execute_reply.started":"2022-09-28T12:51:03.350878Z","shell.execute_reply":"2022-09-28T12:51:03.359241Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_generator = zip(image_generator, mask_generator)\ncallbacks_list = [\n    keras.callbacks.EarlyStopping(\n    monitor='accuracy',\n    patience=10\n    )\n]\nmodel.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])\n\nhistory = model.fit_generator(\n    train_generator,\n    steps_per_epoch=13,\n    epochs=15,\n    callbacks=callbacks_list)\n#model.summary()","metadata":{"execution":{"iopub.status.busy":"2022-09-28T12:51:03.361622Z","iopub.execute_input":"2022-09-28T12:51:03.362873Z","iopub.status.idle":"2022-09-28T12:58:49.018839Z","shell.execute_reply.started":"2022-09-28T12:51:03.362833Z","shell.execute_reply":"2022-09-28T12:58:49.016387Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predict_x = model.predict(test_generator)\nprint(test_generator[0].shape)\np_I = test_generator[0][0]\nplt.imshow(p_I, interpolation='nearest', cmap = 'hot')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-09-28T12:58:49.022136Z","iopub.status.idle":"2022-09-28T12:58:49.022713Z","shell.execute_reply.started":"2022-09-28T12:58:49.022467Z","shell.execute_reply":"2022-09-28T12:58:49.022489Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#I = plt.imread(predict_x)\nprint(predict_x.shape)\ny = predict_x[0]\nprint(y)\n#replacing values(in prediction matrix) that are greater than 0 to 1\n#y[y > 0.5] = 1.0 \n#y[y < 0.5] = 0.0\n#print(y)\nplt.imshow(y, interpolation='nearest', cmap = 'hot')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-09-28T12:58:49.024174Z","iopub.status.idle":"2022-09-28T12:58:49.024791Z","shell.execute_reply.started":"2022-09-28T12:58:49.024464Z","shell.execute_reply":"2022-09-28T12:58:49.024495Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\"\"\"\n#code for extracting file names from image generator\nfor (i,j) in zip(image_generator, mask_generator):\n    idx = (image_generator.batch_index -1)* image_generator.batch_size\n    id = (mask_generator.batch_index -1)* mask_generator.batch_size\n    images = (image_generator.filenames[idx : idx + image_generator.batch_size])\n    masks = (mask_generator.filenames[idx : idx + mask_generator.batch_size])\n    print(images)\n    print(masks)\n    break\n\"\"\"\n\"\"\"\nfor i in test_generator:\n    idx = (test_generator.batch_index -1)* test_generator.batch_size\n    test_images = (test_generator.filenames[idx : idx + test_generator.batch_size])\n    print(test_images)\n    break\n\"\"\"","metadata":{"execution":{"iopub.status.busy":"2022-09-28T12:58:49.026886Z","iopub.status.idle":"2022-09-28T12:58:49.027467Z","shell.execute_reply.started":"2022-09-28T12:58:49.027164Z","shell.execute_reply":"2022-09-28T12:58:49.027192Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def rearrange_output(p,shape):\n    #p_max = p.max()\n    p_max_04 = 0.04 + p.max()/2\n    #replacing values(in prediction matrix) that are greater than max/2 to 1\n    #p[p > p_max/2] = 1.0 \n    #p[p < p_max/2] = 0.0\n    p[p > p_max_04] = 1.0 \n    p[p < p_max_04] = 0.0\n    predict_img = im.fromarray((p).astype(np.uint8))\n    #predict_img = im.fromarray(y)\n    predict_img = predict_img.convert('L')\n    predict_img.save('./predict_0.tiff')\n    p_I_tiff = './predict_0.tiff'\n    p_I = plt.imread(p_I_tiff)\n    plt.imshow(p_I, interpolation='nearest', cmap = 'hot')\n    plt.show()\n    image = im.open(p_I_tiff) \n    p_Ilarge = image.resize(shape)\n    p_Ilarge.save('./predict_0L.tiff')\n    p_e_1 = './predict_0L.tiff'\n    p_e = plt.imread(p_e_1)\n    plt.imshow(p_e, interpolation='nearest', cmap = 'hot', alpha = 0.9)\n    plt.show()\n    return p_e\n    ","metadata":{"execution":{"iopub.status.busy":"2022-09-28T12:58:49.028816Z","iopub.status.idle":"2022-09-28T12:58:49.029244Z","shell.execute_reply.started":"2022-09-28T12:58:49.029040Z","shell.execute_reply":"2022-09-28T12:58:49.029061Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\"\"\"\nfrom PIL import Image as im\npredict_img = im.fromarray((y*255).astype(np.uint8))\n#predict_img = im.fromarray(y)\npredict_img = predict_img.convert('L')\npredict_img.save('./predict_0.tiff')\np_I_tiff = './predict_0.tiff'\np_I = plt.imread(p_I_tiff)\nplt.imshow(p_I, interpolation='nearest', cmap = 'hot')\nplt.show()\nimage = im.open(p_I_tiff) \np_Ilarge = image.resize((2023,2023))\np_Ilarge.save('./predict_0L.tiff')\np_e_1 = './predict_0L.tiff'\np_e = plt.imread(p_e_1)\nplt.imshow(p_e, interpolation='nearest', cmap = 'hot', alpha = 0.9)\nplt.show()\n\"\"\"","metadata":{"execution":{"iopub.status.busy":"2022-09-28T12:58:49.030827Z","iopub.status.idle":"2022-09-28T12:58:49.031261Z","shell.execute_reply.started":"2022-09-28T12:58:49.031043Z","shell.execute_reply":"2022-09-28T12:58:49.031063Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"e_p = rearrange_output(y,(2023,2023))\nprint(e_p)\n#p_e[(p_e>0.5)] = 1\n#print(p_e)\nplt.imshow(e_p, interpolation='nearest', cmap = 'hot', alpha = 0.9)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-09-28T12:58:49.032728Z","iopub.status.idle":"2022-09-28T12:58:49.033152Z","shell.execute_reply.started":"2022-09-28T12:58:49.032960Z","shell.execute_reply":"2022-09-28T12:58:49.032980Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Function to convert  \ndef listToString(s): \n    # initialize an empty string\n    str1 = \" \" \n    # return string \n    return (str1.join(s))\n\ndef convertTuple(tup):\n    str_o = ' '.join(map(str,tup))\n    #print(str)\n    return str_o\ntest_df.to_csv('submission.csv', index=False)\ndef convertTupleList(tupleList):\n    l = []\n    for tup in tupleList:\n        #print(tup)\n        l.append(convertTuple(tup))\n    return listToString(l)","metadata":{"execution":{"iopub.status.busy":"2022-09-28T12:58:49.035667Z","iopub.status.idle":"2022-09-28T12:58:49.036279Z","shell.execute_reply.started":"2022-09-28T12:58:49.036076Z","shell.execute_reply":"2022-09-28T12:58:49.036096Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#print(mask2rle(e_p,(2023,2023)))\n#output_df = pd.DataFrame(data, columns=['id','rle'])\nrle = []\nfor index, row in test_df.iterrows():\n    #print(index)\n    shape = (row['img_height'],row['img_width'])\n    p_mask = rearrange_output(predict_x[index],shape)\n    rle_output = mask2rle(p_mask,shape)\n    rle_output = convertTupleList(mask2rle(p_mask,shape))\n    rle.append(rle_output)\n    #convertTupleList(rle_output)\n    #print(ol)\n    #rle.append(convertTupleList(rle_output))\ntest_df['rle'] = rle\n#adding test_mask col to test dataframe\n#test_df['test_mask'] = ''\ntest_df.head()","metadata":{"execution":{"iopub.status.busy":"2022-09-28T12:58:49.037181Z","iopub.status.idle":"2022-09-28T12:58:49.038066Z","shell.execute_reply.started":"2022-09-28T12:58:49.037720Z","shell.execute_reply":"2022-09-28T12:58:49.037751Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df.to_csv('submission.csv',columns=['id','rle'], index=False)","metadata":{"execution":{"iopub.status.busy":"2022-09-28T12:58:49.039586Z","iopub.status.idle":"2022-09-28T12:58:49.040429Z","shell.execute_reply.started":"2022-09-28T12:58:49.040198Z","shell.execute_reply":"2022-09-28T12:58:49.040221Z"},"trusted":true},"execution_count":null,"outputs":[]}]}