{"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)\n\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'):\n#     for filename in filenames:\n#         print(os.path.join(dirname, filename))\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-07T09:08:54.098053Z","iopub.execute_input":"2022-09-07T09:08:54.098455Z","iopub.status.idle":"2022-09-07T09:08:54.122504Z","shell.execute_reply.started":"2022-09-07T09:08:54.098376Z","shell.execute_reply":"2022-09-07T09:08:54.121678Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import sys\nsys.path.append('../input/timm-pytorch-image-models/pytorch-image-models-master')\nsys.path.append(\"../input/segmentation-models-pytorch/segmentation_models.pytorch-0.2.1\")\nsys.path.append(\"../input/pretrainedmodels/pretrainedmodels-0.7.4\")\nsys.path.append(\"../input/efficientnet-pytorch/EfficientNet-PyTorch-master\")","metadata":{"execution":{"iopub.status.busy":"2022-09-07T09:08:55.048465Z","iopub.execute_input":"2022-09-07T09:08:55.048820Z","iopub.status.idle":"2022-09-07T09:08:55.054276Z","shell.execute_reply.started":"2022-09-07T09:08:55.048793Z","shell.execute_reply":"2022-09-07T09:08:55.053197Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd \nimport numpy as np \nimport seaborn as sns \nimport matplotlib.pyplot as plt\nimport torch\nfrom torch import nn\nimport warnings\nimport albumentations as A\nfrom albumentations.pytorch import ToTensorV2\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset,DataLoader\nfrom torch import optim\nfrom torchvision import transforms\nfrom torch.utils.data import random_split\nfrom tqdm import tqdm\nfrom sklearn.model_selection import train_test_split\nimport segmentation_models_pytorch as smp\nimport cv2 as cv \nimport os\nfrom PIL import Image","metadata":{"execution":{"iopub.status.busy":"2022-09-07T09:08:56.503276Z","iopub.execute_input":"2022-09-07T09:08:56.503622Z","iopub.status.idle":"2022-09-07T09:09:03.627296Z","shell.execute_reply.started":"2022-09-07T09:08:56.503593Z","shell.execute_reply":"2022-09-07T09:09:03.626142Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"device = 'cuda' if torch.cuda.is_available() else 'cpu'","metadata":{"execution":{"iopub.status.busy":"2022-09-07T09:09:03.629934Z","iopub.execute_input":"2022-09-07T09:09:03.630952Z","iopub.status.idle":"2022-09-07T09:09:03.692184Z","shell.execute_reply.started":"2022-09-07T09:09:03.630909Z","shell.execute_reply":"2022-09-07T09:09:03.691236Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"SEED = 42\nnp.random.seed(SEED)\ntorch.manual_seed(SEED)\ntorch.cuda.manual_seed(SEED)\ntorch.cuda.manual_seed_all(SEED)\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\nos.environ['PYTHONHASHSEED'] = str(SEED)\nwarnings.filterwarnings('ignore')","metadata":{"execution":{"iopub.status.busy":"2022-09-07T09:09:03.694061Z","iopub.execute_input":"2022-09-07T09:09:03.694697Z","iopub.status.idle":"2022-09-07T09:09:03.707667Z","shell.execute_reply.started":"2022-09-07T09:09:03.694660Z","shell.execute_reply":"2022-09-07T09:09:03.706569Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def rle_encode_less_memory(img):\n    pixels = img.T.flatten()\n    pixels[0] = 0\n    pixels[-1] = 0\n    runs = np.where(pixels[1:] != pixels[:-1])[0] + 2\n    runs[1::2] -= runs[::2]\n    return ' '.join(str(x) for x in runs)","metadata":{"execution":{"iopub.status.busy":"2022-09-07T09:09:03.710126Z","iopub.execute_input":"2022-09-07T09:09:03.710552Z","iopub.status.idle":"2022-09-07T09:09:03.719048Z","shell.execute_reply.started":"2022-09-07T09:09:03.710513Z","shell.execute_reply":"2022-09-07T09:09:03.718014Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image = np.array(Image.open('../input/hubmap-organ-segmentation/test_images/10078.tiff'))\nplt.figure(figsize = (16,10))\nplt.imshow(image)","metadata":{"execution":{"iopub.status.busy":"2022-09-07T09:09:03.720543Z","iopub.execute_input":"2022-09-07T09:09:03.720922Z","iopub.status.idle":"2022-09-07T09:09:05.066434Z","shell.execute_reply.started":"2022-09-07T09:09:03.720886Z","shell.execute_reply":"2022-09-07T09:09:05.064860Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df = pd.read_csv('../input/hubmap-organ-segmentation/test.csv')\ntest_df","metadata":{"execution":{"iopub.status.busy":"2022-09-07T09:09:05.067833Z","iopub.execute_input":"2022-09-07T09:09:05.068159Z","iopub.status.idle":"2022-09-07T09:09:05.094272Z","shell.execute_reply.started":"2022-09-07T09:09:05.068129Z","shell.execute_reply":"2022-09-07T09:09:05.093541Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class Hubmap(Dataset):\n    def __init__(self,test_df,image_dir,aug=None):\n        self.test_df =test_df \n        self.image_dir = image_dir\n        self.aug = aug\n        \n    def __len__(self):\n        return self.test_df.shape[0]\n    \n    def __getitem__(self, idx):\n        image_id = self.test_df['id'][idx]\n        image_height = self.test_df['img_height'][idx]\n        image_width = self.test_df['img_width'][idx]\n        image = np.array(Image.open(image_dir+'/'+str(image_id)+'.tiff'))\n        if self.aug is not None:\n            augmented = self.aug(image=image)\n            image = augmented['image']\n        return image,image_id,image_height,image_width","metadata":{"execution":{"iopub.status.busy":"2022-09-07T09:09:05.107059Z","iopub.execute_input":"2022-09-07T09:09:05.107731Z","iopub.status.idle":"2022-09-07T09:09:05.116694Z","shell.execute_reply.started":"2022-09-07T09:09:05.107675Z","shell.execute_reply":"2022-09-07T09:09:05.115698Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_dir = '../input/hubmap-organ-segmentation/test_images'\nIMAGE_SIZE = 512","metadata":{"execution":{"iopub.status.busy":"2022-09-07T09:09:05.118168Z","iopub.execute_input":"2022-09-07T09:09:05.118876Z","iopub.status.idle":"2022-09-07T09:09:05.127879Z","shell.execute_reply.started":"2022-09-07T09:09:05.118841Z","shell.execute_reply":"2022-09-07T09:09:05.126845Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_aug = A.Compose([A.Resize(IMAGE_SIZE,IMAGE_SIZE ,p = 1.0),ToTensorV2(p=1.0)],p=1.0)","metadata":{"execution":{"iopub.status.busy":"2022-09-07T09:09:05.294646Z","iopub.execute_input":"2022-09-07T09:09:05.296143Z","iopub.status.idle":"2022-09-07T09:09:05.300833Z","shell.execute_reply.started":"2022-09-07T09:09:05.296107Z","shell.execute_reply":"2022-09-07T09:09:05.299837Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_data = Hubmap(test_df,image_dir,train_aug)","metadata":{"execution":{"iopub.status.busy":"2022-09-07T09:09:05.614409Z","iopub.execute_input":"2022-09-07T09:09:05.616177Z","iopub.status.idle":"2022-09-07T09:09:05.620378Z","shell.execute_reply.started":"2022-09-07T09:09:05.616139Z","shell.execute_reply":"2022-09-07T09:09:05.619257Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for i in test_data:\n    print(i[0].shape)\n    plt.figure(figsize = (7,7))\n    plt.imshow(np.transpose(np.array(i[0]),[1,2,0]))\n    break","metadata":{"execution":{"iopub.status.busy":"2022-09-07T09:09:05.903132Z","iopub.execute_input":"2022-09-07T09:09:05.903491Z","iopub.status.idle":"2022-09-07T09:09:06.255281Z","shell.execute_reply.started":"2022-09-07T09:09:05.903445Z","shell.execute_reply":"2022-09-07T09:09:06.254490Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_loader =DataLoader(test_data,batch_size=1,shuffle=False)","metadata":{"execution":{"iopub.status.busy":"2022-09-07T09:09:06.256821Z","iopub.execute_input":"2022-09-07T09:09:06.257728Z","iopub.status.idle":"2022-09-07T09:09:06.262769Z","shell.execute_reply.started":"2022-09-07T09:09:06.257674Z","shell.execute_reply":"2022-09-07T09:09:06.261674Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = smp.create_model(arch= 'Unet',encoder_name='efficientnet-b0',encoder_weights=None,in_channels=3,classes=1)\nmodel.load_state_dict(torch.load('../input/model-seg-1/sem-1'))\nmodel = model.to(device)","metadata":{"execution":{"iopub.status.busy":"2022-09-07T09:09:06.308737Z","iopub.execute_input":"2022-09-07T09:09:06.309504Z","iopub.status.idle":"2022-09-07T09:09:09.740446Z","shell.execute_reply.started":"2022-09-07T09:09:06.309472Z","shell.execute_reply":"2022-09-07T09:09:09.739470Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"threshold = 0.5\npred_rles = []\npred_ids = []\nfor images,ids,height,width in tqdm(test_loader):\n    images = images.to(device).float()\n    with torch.no_grad():\n        output = model(images)\n        output = nn.Sigmoid()(output)\n        mask = (output.permute((0,2,3,1))> threshold).to(torch.uint8).cpu().detach().numpy()\n        for idx in range(mask.shape[0]):\n            height = height[idx].item()\n            width = width[idx].item()\n            ids = ids[idx].item()\n            masks = cv.resize(mask[idx].squeeze(),dsize=(width, height),interpolation=cv.INTER_NEAREST)\n            rle = rle_encode_less_memory(masks)\n            pred_rles.append(rle)\n            pred_ids.append(ids)","metadata":{"execution":{"iopub.status.busy":"2022-09-07T09:09:09.742540Z","iopub.execute_input":"2022-09-07T09:09:09.742928Z","iopub.status.idle":"2022-09-07T09:09:15.096841Z","shell.execute_reply.started":"2022-09-07T09:09:09.742892Z","shell.execute_reply":"2022-09-07T09:09:15.095971Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred_df = pd.DataFrame({\"id\":pred_ids,\"rle\":pred_rles})\npred_df.to_csv('submission.csv',index=False)\npred_df","metadata":{"execution":{"iopub.status.busy":"2022-09-07T09:09:15.100158Z","iopub.execute_input":"2022-09-07T09:09:15.103339Z","iopub.status.idle":"2022-09-07T09:09:15.125747Z","shell.execute_reply.started":"2022-09-07T09:09:15.103298Z","shell.execute_reply":"2022-09-07T09:09:15.124889Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}