{"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 matplotlib.pyplot as plt\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\nfor 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-10T16:53:08.509295Z","iopub.execute_input":"2022-09-10T16:53:08.509951Z","iopub.status.idle":"2022-09-10T16:53:08.526821Z","shell.execute_reply.started":"2022-09-10T16:53:08.509911Z","shell.execute_reply":"2022-09-10T16:53:08.525478Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls","metadata":{"execution":{"iopub.status.busy":"2022-09-10T16:53:08.528915Z","iopub.execute_input":"2022-09-10T16:53:08.529637Z","iopub.status.idle":"2022-09-10T16:53:09.566074Z","shell.execute_reply.started":"2022-09-10T16:53:08.529598Z","shell.execute_reply":"2022-09-10T16:53:09.564926Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%matplotlib inline","metadata":{"execution":{"iopub.status.busy":"2022-09-10T16:53:09.568074Z","iopub.execute_input":"2022-09-10T16:53:09.568904Z","iopub.status.idle":"2022-09-10T16:53:09.576515Z","shell.execute_reply.started":"2022-09-10T16:53:09.568863Z","shell.execute_reply":"2022-09-10T16:53:09.575332Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from zipfile import ZipFile\nfrom fastai.vision.all import Path, get_image_files\nfrom skimage import io, transform","metadata":{"execution":{"iopub.status.busy":"2022-09-10T16:53:09.579545Z","iopub.execute_input":"2022-09-10T16:53:09.579913Z","iopub.status.idle":"2022-09-10T16:53:09.597789Z","shell.execute_reply.started":"2022-09-10T16:53:09.579879Z","shell.execute_reply":"2022-09-10T16:53:09.596809Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with ZipFile('../input/carvana-image-masking-challenge/sample_submission.csv.zip', 'r') as zip_ref:\n  zip_ref.extractall('')","metadata":{"execution":{"iopub.status.busy":"2022-09-10T16:53:09.599240Z","iopub.execute_input":"2022-09-10T16:53:09.600082Z","iopub.status.idle":"2022-09-10T16:53:09.621610Z","shell.execute_reply.started":"2022-09-10T16:53:09.600038Z","shell.execute_reply":"2022-09-10T16:53:09.620567Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with ZipFile('../input/carvana-image-masking-challenge/test.zip', 'r') as zip_ref:\n  zip_ref.extractall('')","metadata":{"execution":{"iopub.status.busy":"2022-09-10T16:53:09.624093Z","iopub.execute_input":"2022-09-10T16:53:09.624837Z","iopub.status.idle":"2022-09-10T16:53:13.744168Z","shell.execute_reply.started":"2022-09-10T16:53:09.624812Z","shell.execute_reply":"2022-09-10T16:53:13.741104Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#View the file\npath = Path('')\nfnames = get_image_files(path/'train')\nlbl_names = get_image_files(path/'train_masks')","metadata":{"execution":{"iopub.status.busy":"2022-09-10T16:53:26.907897Z","iopub.execute_input":"2022-09-10T16:53:26.908483Z","iopub.status.idle":"2022-09-10T16:53:26.914226Z","shell.execute_reply.started":"2022-09-10T16:53:26.908443Z","shell.execute_reply":"2022-09-10T16:53:26.913218Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import albumentations as A\nimport albumentations.pytorch as alb_pytorch\nimport cv2\nfrom torchvision import transforms, utils\nfrom torchvision.transforms import InterpolationMode\n\nresize_num = 256\n\n# transform_seg = A.Compose([\n#     A.RandomCrop(width=1000, height=1000),\n# #     alb_pytorch.ToTensorV2(),\n# #     A.HorizontalFlip(p=0.5),\n# #     A.RandomBrightnessContrast(p=0.2),\n# ])\n# transform_seg=transforms.Compose([transforms.RandomCrop(1000),transforms.ToTensor()])\ntransform_seg_img=transforms.Compose([transforms.Resize((resize_num,resize_num)),transforms.ToTensor()])\ntransform_seg_mask=transforms.Compose([transforms.ToTensor(),transforms.Resize((resize_num,resize_num), interpolation=InterpolationMode.NEAREST)])","metadata":{"execution":{"iopub.status.busy":"2022-09-10T16:53:27.663460Z","iopub.execute_input":"2022-09-10T16:53:27.664112Z","iopub.status.idle":"2022-09-10T16:53:27.682199Z","shell.execute_reply.started":"2022-09-10T16:53:27.664075Z","shell.execute_reply":"2022-09-10T16:53:27.680439Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\nfrom torch.nn import Flatten, Linear, ReLU, Conv2d, MaxPool2d, Sigmoid, Upsample\nfrom torchvision import transforms","metadata":{"execution":{"iopub.status.busy":"2022-09-10T16:53:27.831533Z","iopub.execute_input":"2022-09-10T16:53:27.832133Z","iopub.status.idle":"2022-09-10T16:53:27.837491Z","shell.execute_reply.started":"2022-09-10T16:53:27.832102Z","shell.execute_reply":"2022-09-10T16:53:27.836468Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\"\"\" Parts of the U-Net model \"\"\"\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass DoubleConv(nn.Module):\n    \"\"\"(convolution => [BN] => ReLU) * 2\"\"\"\n\n    def __init__(self, in_channels, out_channels, mid_channels=None):\n        super().__init__()\n        if not mid_channels:\n            mid_channels = out_channels\n        self.double_conv = nn.Sequential(\n            nn.Conv2d(in_channels, mid_channels, kernel_size=3, padding=1, bias=False),\n            nn.BatchNorm2d(mid_channels),\n            nn.ReLU(inplace=True),\n            nn.Conv2d(mid_channels, out_channels, kernel_size=3, padding=1, bias=False),\n            nn.BatchNorm2d(out_channels),\n            nn.ReLU(inplace=True)\n        )\n\n    def forward(self, x):\n        return self.double_conv(x)\n\n\nclass Down(nn.Module):\n    \"\"\"Downscaling with maxpool then double conv\"\"\"\n\n    def __init__(self, in_channels, out_channels):\n        super().__init__()\n        self.maxpool_conv = nn.Sequential(\n            nn.MaxPool2d(2),\n            DoubleConv(in_channels, out_channels)\n        )\n\n    def forward(self, x):\n        return self.maxpool_conv(x)\n\n\nclass Up(nn.Module):\n    \"\"\"Upscaling then double conv\"\"\"\n\n    def __init__(self, in_channels, out_channels, bilinear=True):\n        super().__init__()\n\n        # if bilinear, use the normal convolutions to reduce the number of channels\n        if bilinear:\n            self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)\n            self.conv = DoubleConv(in_channels, out_channels, in_channels // 2)\n        else:\n            self.up = nn.ConvTranspose2d(in_channels, in_channels // 2, kernel_size=2, stride=2)\n            self.conv = DoubleConv(in_channels, out_channels)\n\n    def forward(self, x1, x2):\n        x1 = self.up(x1)\n        # input is CHW\n        diffY = x2.size()[2] - x1.size()[2]\n        diffX = x2.size()[3] - x1.size()[3]\n\n        x1 = F.pad(x1, [diffX // 2, diffX - diffX // 2,\n                        diffY // 2, diffY - diffY // 2])\n        # if you have padding issues, see\n        # https://github.com/HaiyongJiang/U-Net-Pytorch-Unstructured-Buggy/commit/0e854509c2cea854e247a9c615f175f76fbb2e3a\n        # https://github.com/xiaopeng-liao/Pytorch-UNet/commit/8ebac70e633bac59fc22bb5195e513d5832fb3bd\n        x = torch.cat([x2, x1], dim=1)\n        return self.conv(x)\n\n\nclass OutConv(nn.Module):\n    def __init__(self, in_channels, out_channels):\n        super(OutConv, self).__init__()\n        self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1)\n\n    def forward(self, x):\n        return self.conv(x)","metadata":{"execution":{"iopub.status.busy":"2022-09-10T16:53:27.997377Z","iopub.execute_input":"2022-09-10T16:53:27.998734Z","iopub.status.idle":"2022-09-10T16:53:28.016789Z","shell.execute_reply.started":"2022-09-10T16:53:27.998685Z","shell.execute_reply":"2022-09-10T16:53:28.015747Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class UNet(nn.Module):\n    def __init__(self, n_channels, n_classes, bilinear=False):\n        super(UNet, self).__init__()\n        self.n_channels = n_channels\n        self.n_classes = n_classes\n        self.bilinear = bilinear\n\n        self.inc = DoubleConv(n_channels, 64)\n        self.down1 = Down(64, 128)\n        self.down2 = Down(128, 256)\n        self.down3 = Down(256, 512)\n        factor = 2 if bilinear else 1\n        self.down4 = Down(512, 1024 // factor)\n        self.up1 = Up(1024, 512 // factor, bilinear)\n        self.up2 = Up(512, 256 // factor, bilinear)\n        self.up3 = Up(256, 128 // factor, bilinear)\n        self.up4 = Up(128, 64, bilinear)\n        self.outc = OutConv(64, n_classes)\n\n    def forward(self, x):\n        x1 = self.inc(x)\n        x2 = self.down1(x1)\n        x3 = self.down2(x2)\n        x4 = self.down3(x3)\n        x5 = self.down4(x4)\n        x = self.up1(x5, x4)\n        x = self.up2(x, x3)\n        x = self.up3(x, x2)\n        x = self.up4(x, x1)\n        logits = self.outc(x)\n        return logits","metadata":{"execution":{"iopub.status.busy":"2022-09-10T16:53:28.145222Z","iopub.execute_input":"2022-09-10T16:53:28.146111Z","iopub.status.idle":"2022-09-10T16:53:28.156870Z","shell.execute_reply.started":"2022-09-10T16:53:28.146060Z","shell.execute_reply":"2022-09-10T16:53:28.155652Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = UNet(3,2)\n# model = torch.nn.modules.Sequential(Conv2d(in_channels=3, out_channels=16, kernel_size=3, padding=1, stride=1),\n#                                     ReLU(),\n#                                     Conv2d(in_channels=16, out_channels=32, kernel_size=3, padding=1, stride=1),\n#                                     ReLU(),\n#                                     MaxPool2d(2),\n#                                     ReLU(),\n#                                     Conv2d(in_channels=32, out_channels=64, kernel_size=3, padding=1, stride=1),\n#                                     ReLU(),\n#                                     Conv2d(in_channels=64, out_channels=128, kernel_size=3, padding=1, stride=1),\n#                                     ReLU(),\n#                                     MaxPool2d(2),\n#                                     ReLU(),\n#                                     Conv2d(in_channels=128, out_channels=64, kernel_size=3, padding=1, stride=1),\n#                                     ReLU(),\n#                                     Upsample(scale_factor=2, mode='bilinear'),\n#                                     ReLU(),\n#                                     Conv2d(in_channels=64, out_channels=32, kernel_size=3, padding=1, stride=1),\n#                                     ReLU(),\n#                                     Conv2d(in_channels=32, out_channels=16, kernel_size=3, padding=1, stride=1),\n#                                     ReLU(),\n#                                     Upsample(scale_factor=2, mode='bilinear'),\n#                                     ReLU(),\n#                                     Conv2d(in_channels=16, out_channels=2, kernel_size=3, padding=1, stride=1),\n#                                     )\n# model = torch.nn.modules.Sequential(Conv2d(in_channels=3, out_channels=64, kernel_size=3, padding=1, stride=1),\n#                                             ReLU(),\n#                                             Conv2d(in_channels=64, out_channels=128, kernel_size=3, padding=1, stride=1),\n#                                             ReLU(),\n#                                             Conv2d(in_channels=128, out_channels=256, kernel_size=3, padding=1, stride=1),\n#                                             ReLU(),\n#                                             Conv2d(in_channels=256, out_channels=128, kernel_size=3, padding=1, stride=1),\n#                                             ReLU(),\n#                                             Conv2d(in_channels=128, out_channels=64, kernel_size=3, padding=1, stride=1),\n#                                             ReLU(),\n#                                             Conv2d(in_channels=64, out_channels=2, kernel_size=3, padding=1, stride=1),\n#         )","metadata":{"execution":{"iopub.status.busy":"2022-09-10T16:53:28.297850Z","iopub.execute_input":"2022-09-10T16:53:28.298379Z","iopub.status.idle":"2022-09-10T16:53:28.574383Z","shell.execute_reply.started":"2022-09-10T16:53:28.298350Z","shell.execute_reply":"2022-09-10T16:53:28.573347Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls ../input/","metadata":{"execution":{"iopub.status.busy":"2022-09-10T16:53:28.576341Z","iopub.execute_input":"2022-09-10T16:53:28.577040Z","iopub.status.idle":"2022-09-10T16:53:29.616441Z","shell.execute_reply.started":"2022-09-10T16:53:28.577000Z","shell.execute_reply":"2022-09-10T16:53:29.615264Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load checkpoint\ncheckpoint = torch.load('../input/unetarch/best_checkpoint (3).pt') # or latest_checkpoint.pt\n\nmodel.load_state_dict(checkpoint['model_state_dict'])\n# optimizer.load_state_dict(checkpoint['optimizer_state_dict'])\n# epoch = checkpoint['epoch']\n# best_acc = checkpoint['best_acc']","metadata":{"execution":{"iopub.status.busy":"2022-09-10T16:53:29.619097Z","iopub.execute_input":"2022-09-10T16:53:29.619520Z","iopub.status.idle":"2022-09-10T16:53:32.814298Z","shell.execute_reply.started":"2022-09-10T16:53:29.619479Z","shell.execute_reply":"2022-09-10T16:53:32.813364Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(len(fnames))","metadata":{"execution":{"iopub.status.busy":"2022-09-10T16:53:32.815681Z","iopub.execute_input":"2022-09-10T16:53:32.816267Z","iopub.status.idle":"2022-09-10T16:53:32.823298Z","shell.execute_reply.started":"2022-09-10T16:53:32.816229Z","shell.execute_reply":"2022-09-10T16:53:32.822073Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"path = Path('')\ntest_names = get_image_files(path/'test')","metadata":{"execution":{"iopub.status.busy":"2022-09-10T16:53:32.826259Z","iopub.execute_input":"2022-09-10T16:53:32.827433Z","iopub.status.idle":"2022-09-10T16:53:33.845943Z","shell.execute_reply.started":"2022-09-10T16:53:32.827375Z","shell.execute_reply":"2022-09-10T16:53:33.844921Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_names.sort()","metadata":{"execution":{"iopub.status.busy":"2022-09-10T16:53:33.847731Z","iopub.execute_input":"2022-09-10T16:53:33.848147Z","iopub.status.idle":"2022-09-10T16:53:34.768287Z","shell.execute_reply.started":"2022-09-10T16:53:33.848108Z","shell.execute_reply":"2022-09-10T16:53:34.767280Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.imshow(io.imread(test_names[16]))\nio.imread(test_names[16]).shape","metadata":{"execution":{"iopub.status.busy":"2022-09-10T16:53:34.769939Z","iopub.execute_input":"2022-09-10T16:53:34.770596Z","iopub.status.idle":"2022-09-10T16:53:35.274571Z","shell.execute_reply.started":"2022-09-10T16:53:34.770558Z","shell.execute_reply":"2022-09-10T16:53:35.271556Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from PIL import Image\n\nmodel = model.cuda()\nconvert = transforms.ToTensor()\nf, axarr = plt.subplots(5,5, figsize=(10, 10))\n# plt.figure(figsize=(10,10))\nfor x in range(5):\n    for i in range(5):\n        img = transform_seg_img(Image.open(test_names[i+x]))\n        img = img.cuda()\n#         img = convert(img['image']).cuda().reshape(1,3,1000,1000)\n#         print(img.shape)\n        l = model(img.reshape(1,img.shape[0],img.shape[1],img.shape[2]))\n        preds = torch.argmax(l, axis=1)\n#         print(preds)\n    #     print(l[0].shape)\n        l = preds.cpu().detach().numpy()\n        axarr[x,i].imshow(l.reshape(resize_num,resize_num), cmap='gray')","metadata":{"execution":{"iopub.status.busy":"2022-09-10T16:53:35.276226Z","iopub.execute_input":"2022-09-10T16:53:35.277034Z","iopub.status.idle":"2022-09-10T16:53:38.787005Z","shell.execute_reply.started":"2022-09-10T16:53:35.276988Z","shell.execute_reply":"2022-09-10T16:53:38.786142Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def rle_encode(mask_image):\n    pixels = mask_image.flatten()\n    # We avoid issues with '1' at the start or end (at the corners of \n    # the original image) by setting those pixels to '0' explicitly.\n    # We do not expect these to be non-zero for an accurate mask, \n    # so this should not harm the score.\n    pixels[0] = 0\n    pixels[-1] = 0\n    runs = np.where(pixels[1:] != pixels[:-1])[0] + 2\n    runs[1::2] = runs[1::2] - runs[:-1:2]\n    return runs\n\n\n","metadata":{"execution":{"iopub.status.busy":"2022-09-10T16:53:38.791174Z","iopub.execute_input":"2022-09-10T16:53:38.793438Z","iopub.status.idle":"2022-09-10T16:53:38.801597Z","shell.execute_reply.started":"2022-09-10T16:53:38.793386Z","shell.execute_reply":"2022-09-10T16:53:38.800422Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\n\n\nsubmit_mask = pd.read_csv('sample_submission.csv')\n\nfor idx,name in (enumerate(submit_mask['img'].iloc[:])):\n        name =  'test/'+ str(name)\n        if(not(os.path.exists(name))):\n            print (idx,name)\n\n# rle = rle_encode(submit_np2)\n\n#         rle = ' '.join(str(x) for x in rle)","metadata":{"execution":{"iopub.status.busy":"2022-09-10T16:53:38.806447Z","iopub.execute_input":"2022-09-10T16:53:38.809238Z","iopub.status.idle":"2022-09-10T16:53:39.275664Z","shell.execute_reply.started":"2022-09-10T16:53:38.809203Z","shell.execute_reply":"2022-09-10T16:53:39.274650Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from torch.utils.data import Dataset\nfrom torchvision import transforms\nfrom PIL import Image\nclass ImageMasksDataset(Dataset):\n    \"\"\"Face Landmarks dataset.\"\"\"\n\n    def __init__(self, fnames, lbl_names, transform=None):\n        \"\"\"\n        Args:\n            csv_file (string): Path to the csv file with annotations.\n            root_dir (string): Directory with all the images.\n            transform (callable, optional): Optional transform to be applied\n                on a sample.\n        \"\"\"\n        self.fnames = fnames\n        self.lbl_names = lbl_names\n        self.transform = transform\n\n    def __len__(self):\n        return len(self.fnames)\n\n    def __getitem__(self, idx):\n        if torch.is_tensor(idx):\n            idx = idx.tolist()\n        \n        sample = (Image.open(self.fnames[idx]),Image.open(self.lbl_names[idx]))\n\n        if self.transform:\n#             convert = transforms.ToTensor()\n            if len(self.transform)>1:\n                img = Image.fromarray(np.array(sample[1])>0)\n                sample = (self.transform[0](sample[0]), torch.squeeze(self.transform[1](img)).long())\n            else:\n                sample = (self.transform[0](sample[0]), torch.squeeze(self.transform[0](sample[1])))\n\n#             sample = self.transform(image=sample[0], mask=sample[1])\n#             sample = (sample['image'], sample['mask'])\n#             sample = (convert(sample[0]), convert(sample[1]))\n        return sample","metadata":{"execution":{"iopub.status.busy":"2022-09-10T16:53:39.278897Z","iopub.execute_input":"2022-09-10T16:53:39.279369Z","iopub.status.idle":"2022-09-10T16:53:39.289221Z","shell.execute_reply.started":"2022-09-10T16:53:39.279329Z","shell.execute_reply":"2022-09-10T16:53:39.288147Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import csv\nimport pandas as pd\n\nout = pd.DataFrame(columns=['img', 'rle_mask'])\n\nmissing = []\nmodel.cuda()\n\nwith open('sample_submission.csv', 'r', encoding='utf-8') as sample:\n    reader = csv.reader(sample)\n    next(reader)\n    for i, row in enumerate(reader):\n        if (i%1000 == 0):\n            print(i)\n        x = []\n        x.append(row[0])\n        img = transform_seg_img(Image.open('test/'+row[0]))\n        img = img.cuda()\n        with torch.no_grad():\n            l = model(img.reshape(1,img.shape[0],img.shape[1],img.shape[2]))\n        preds = torch.argmax(l, axis=1)\n        l = preds.reshape(1,resize_num,resize_num)\n        trans = transforms.Resize((1280,1918))\n        l = trans(l)\n        l = l.cpu().detach().squeeze()\n        rle = rle_encode(np.array(l))\n        rle = ' '.join([str(x) for x in rle])\n        x.append(rle)\n        out = out.append({'img':x[0], 'rle_mask':x[1]}, ignore_index=True)\n        \n#         if i == 10:\n#             break\n\nout.to_csv('end.csv', index = False, sep=',')","metadata":{"execution":{"iopub.status.busy":"2022-09-10T16:53:39.290846Z","iopub.execute_input":"2022-09-10T16:53:39.291201Z","iopub.status.idle":"2022-09-10T16:53:40.102437Z","shell.execute_reply.started":"2022-09-10T16:53:39.291162Z","shell.execute_reply":"2022-09-10T16:53:40.101519Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def rle2mask(mask_rle: str, label=1, shape=[1280, 1918]):\n    \"\"\"\n    mask_rle: run-length as string formatted (start length)\n    shape: (height,width) of array to return\n    Returns numpy array, 1 - mask, 0 - background\n\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] = label\n    return img.reshape(shape)  # Needed to align to RLE direction","metadata":{"execution":{"iopub.status.busy":"2022-09-10T16:53:40.103888Z","iopub.execute_input":"2022-09-10T16:53:40.104270Z","iopub.status.idle":"2022-09-10T16:53:40.111766Z","shell.execute_reply.started":"2022-09-10T16:53:40.104234Z","shell.execute_reply":"2022-09-10T16:53:40.110548Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.read_csv('end.csv')\nplt.imshow(rle2mask(df['rle_mask'][5]), cmap='gray')","metadata":{"execution":{"iopub.status.busy":"2022-09-10T16:53:40.113641Z","iopub.execute_input":"2022-09-10T16:53:40.114434Z","iopub.status.idle":"2022-09-10T16:53:40.494229Z","shell.execute_reply.started":"2022-09-10T16:53:40.114307Z","shell.execute_reply":"2022-09-10T16:53:40.493278Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# plt.imshow(rle2mask(df['rle_mask'][5]), cmap='gray')","metadata":{"execution":{"iopub.status.busy":"2022-09-10T16:53:13.788244Z","iopub.status.idle":"2022-09-10T16:53:13.788980Z","shell.execute_reply.started":"2022-09-10T16:53:13.788732Z","shell.execute_reply":"2022-09-10T16:53:13.788757Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!rm -rf test","metadata":{"execution":{"iopub.status.busy":"2022-09-10T16:53:13.790290Z","iopub.status.idle":"2022-09-10T16:53:13.791030Z","shell.execute_reply.started":"2022-09-10T16:53:13.790781Z","shell.execute_reply":"2022-09-10T16:53:13.790805Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls","metadata":{"execution":{"iopub.status.busy":"2022-09-10T16:53:13.792370Z","iopub.status.idle":"2022-09-10T16:53:13.793106Z","shell.execute_reply.started":"2022-09-10T16:53:13.792846Z","shell.execute_reply":"2022-09-10T16:53:13.792870Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('-'*20)\nprint('end')\nprint('-'*20)","metadata":{"execution":{"iopub.status.busy":"2022-09-10T16:53:13.794439Z","iopub.status.idle":"2022-09-10T16:53:13.795165Z","shell.execute_reply.started":"2022-09-10T16:53:13.794906Z","shell.execute_reply":"2022-09-10T16:53:13.794929Z"},"trusted":true},"execution_count":null,"outputs":[]}]}