{"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":"def rle_encode_less_memory(img):\n    #the image should be transposed\n    pixels = img.T.flatten()\n    \n    # This simplified method requires first and last pixel to be zero\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    \n    return ' '.join(str(x) for x in runs)","metadata":{"execution":{"iopub.status.busy":"2022-09-09T03:26:07.095444Z","iopub.execute_input":"2022-09-09T03:26:07.095763Z","iopub.status.idle":"2022-09-09T03:26:07.122181Z","shell.execute_reply.started":"2022-09-09T03:26:07.095680Z","shell.execute_reply":"2022-09-09T03:26:07.120606Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# ! pip install segmentation-models-pytorch\n\nfrom skimage import io, filters, transform \nimport tifffile as tiff\nimport albumentations as A\n \nimport os\nimport cv2\nimport numpy as np\nimport pandas as pd\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n","metadata":{"papermill":{"duration":13.182907,"end_time":"2022-07-12T04:01:53.673664","exception":false,"start_time":"2022-07-12T04:01:40.490757","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-09-09T03:26:07.123933Z","iopub.execute_input":"2022-09-09T03:26:07.125482Z","iopub.status.idle":"2022-09-09T03:26:11.562045Z","shell.execute_reply.started":"2022-09-09T03:26:07.125431Z","shell.execute_reply":"2022-09-09T03:26:11.561118Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class config:\n    IMAGE_SIZE = 1024\n    TRAIN_BATCH_SIZE = 2\n    VALID_BATCH_SIZE = 2*TRAIN_BATCH_SIZE\n    EPOCHS = 15\n    DEVICE = \"cuda\"\n    OUTPUT = \"/hubmap/\"\n    MODEL_PATH = \"../input/all-segformers/all-segformers/segformer-b5-finetuned-cityscapes-1024-1024\"\n    FOLDS = 5\n    LR = 1e-3\n    ","metadata":{"execution":{"iopub.status.busy":"2022-09-09T03:26:11.563719Z","iopub.execute_input":"2022-09-09T03:26:11.564367Z","iopub.status.idle":"2022-09-09T03:26:11.573006Z","shell.execute_reply.started":"2022-09-09T03:26:11.564326Z","shell.execute_reply":"2022-09-09T03:26:11.570544Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class HubDataset(torch.utils.data.Dataset):\n    def __init__(self,image_path, augmentations=None):\n        self.image_path = image_path\n        self.augmentations = augmentations\n        \n    def __len__(self):\n        return len(self.image_path)\n    \n    def __getitem__(self,item):\n        \n        image = tiff.imread(self.image_path[item])\n\n        \n        image = image.astype(np.float32)/255\n        image = cv2.resize(image, dsize=(config.IMAGE_SIZE, config.IMAGE_SIZE),interpolation=cv2.INTER_LINEAR)\n        \n#         if self.augmentations is not None:\n#             augmented = self.augmentations(image=image, mask=mask)\n#             image = augmented[\"image\"]\n#             mask = augmented[\"mask\"]    \n        image = np.transpose(image, (2, 0, 1)).astype(np.float32)\n\n        return {\n            \"image\": torch.tensor(image, dtype=torch.float),\n        }","metadata":{"papermill":{"duration":0.017041,"end_time":"2022-07-12T04:01:53.717711","exception":false,"start_time":"2022-07-12T04:01:53.70067","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-09-09T03:26:11.576336Z","iopub.execute_input":"2022-09-09T03:26:11.576792Z","iopub.status.idle":"2022-09-09T03:26:11.585634Z","shell.execute_reply.started":"2022-09-09T03:26:11.576753Z","shell.execute_reply":"2022-09-09T03:26:11.584703Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\n\n@torch.no_grad()    \ndef infer(model,valid_loader,device):\n    model.eval()\n    \n    masks = []\n    for data in valid_loader:\n        inputs = data['image']\n        \n        inputs = inputs.to(device, dtype=torch.float)\n\n        output = model(inputs,)\n        output = torch.sigmoid(output)\n        \n        output = output.detach().cpu().numpy()\n        masks.append(output)\n    return masks","metadata":{"execution":{"iopub.status.busy":"2022-09-09T03:26:11.587070Z","iopub.execute_input":"2022-09-09T03:26:11.587529Z","iopub.status.idle":"2022-09-09T03:26:11.597769Z","shell.execute_reply.started":"2022-09-09T03:26:11.587495Z","shell.execute_reply":"2022-09-09T03:26:11.596656Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\n\nfrom transformers import SegformerForSemanticSegmentation\n\n\nclass MixUpSample(nn.Module):\n    def __init__(self, scale_factor=4):\n        super().__init__()\n        self.mixing = nn.Parameter(torch.tensor(0.5))\n        self.scale_factor = scale_factor\n\n    def forward(self, x):\n        x = self.mixing * F.interpolate(\n            x, scale_factor=self.scale_factor, mode=\"bilinear\", align_corners=False\n        ) + (1 - self.mixing) * F.interpolate(\n            x, scale_factor=self.scale_factor, mode=\"nearest\"\n        )\n        return x\n\n\nclass HubmapModel(nn.Module):\n    def __init__(self):\n        super(HubmapModel, self).__init__()\n\n        self.model = SegformerForSemanticSegmentation.from_pretrained(\n            config.MODEL_PATH, num_labels=1, ignore_mismatched_sizes=True\n        )\n        self.mixup = MixUpSample()\n\n    def forward(self, image):\n        img_segs = self.model(image)\n\n        upsampled_logits = self.mixup(img_segs.logits)\n        return upsampled_logits","metadata":{"execution":{"iopub.status.busy":"2022-09-09T03:26:11.598901Z","iopub.execute_input":"2022-09-09T03:26:11.599811Z","iopub.status.idle":"2022-09-09T03:26:12.084418Z","shell.execute_reply.started":"2022-09-09T03:26:11.599774Z","shell.execute_reply":"2022-09-09T03:26:12.083491Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## MAIN","metadata":{}},{"cell_type":"code","source":"df = pd.read_csv(\"../input/hubmap-organ-segmentation/test.csv\")","metadata":{"execution":{"iopub.status.busy":"2022-09-09T03:26:12.085711Z","iopub.execute_input":"2022-09-09T03:26:12.086603Z","iopub.status.idle":"2022-09-09T03:26:12.098163Z","shell.execute_reply.started":"2022-09-09T03:26:12.086571Z","shell.execute_reply":"2022-09-09T03:26:12.097242Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_paths = [\n#               \"../input/hubmapsegformerb5/model-0.pth\",\n              \"../input/hubmapsegformerb5/model-1.pth\",\n#               \"../input/hubmapsegformerb5/model-2.pth\",\n#               \"../input/hubmapsegformerb5/model-3.pth\",\n#               \"../input/hubmapsegformerb5/model-4.pth\", \n              ]","metadata":{"execution":{"iopub.status.busy":"2022-09-09T03:26:12.099782Z","iopub.execute_input":"2022-09-09T03:26:12.100139Z","iopub.status.idle":"2022-09-09T03:26:12.105255Z","shell.execute_reply.started":"2022-09-09T03:26:12.100104Z","shell.execute_reply":"2022-09-09T03:26:12.104123Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"rle_list = []\nfor idx,row in df.iterrows():\n\n    ###\n    model = HubmapModel()\n    model.to(\"cuda\")\n    \n    \n\n    \n    df_valid  = row\n    valid_ids = df_valid.id\n\n    valid_images = [os.path.join(\"../input/hubmap-organ-segmentation/test_images\",str(valid_ids) + \".tiff\")]\n\n    valid_dataset = HubDataset(image_path=valid_images)\n    valid_loader = torch.utils.data.DataLoader(valid_dataset,batch_size=config.VALID_BATCH_SIZE,shuffle=False,pin_memory=True) \n    \n    mask = np.zeros((config.IMAGE_SIZE, config.IMAGE_SIZE))\n    \n    for path in model_paths:\n        \n        model.load_state_dict(torch.load(path))\n        masks_output = infer(model=model,valid_loader=valid_loader,device=config.DEVICE)\n\n        mask += masks_output[0][0].reshape(masks_output[0][0].shape[1],masks_output[0][0].shape[2])\n        \n    mask = mask/len(model_paths)\n\n    mask = transform.resize(mask, (df_valid.img_height, df_valid.img_width))\n    \n    threshold = filters.threshold_mean(mask) ##  isodata, otsu, li, mean, yen, minimum\n    mask = mask > threshold\n    mask = mask.astype(np.int8)\n    \n    print(mask.shape)\n    io.imshow(mask)\n    ###\n    rle_list.append(rle_encode_less_memory(mask))","metadata":{"execution":{"iopub.status.busy":"2022-09-09T03:26:12.106800Z","iopub.execute_input":"2022-09-09T03:26:12.107457Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(threshold)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission = pd.read_csv(\"../input/hubmap-organ-segmentation/sample_submission.csv\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission[\"rle\"] = rle_list\nsubmission.to_csv(\"submission.csv\", index=False)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}