{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.7.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":20604,"databundleVersionId":1357052,"sourceType":"competition"},{"sourceId":1505157,"sourceType":"datasetVersion","datasetId":886149},{"sourceId":1512580,"sourceType":"datasetVersion","datasetId":886160},{"sourceId":8223127,"sourceType":"datasetVersion","datasetId":4875192}],"dockerImageVersionId":30009,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-04-25T04:48:19.068842Z","iopub.execute_input":"2024-04-25T04:48:19.069184Z","iopub.status.idle":"2024-04-25T04:48:19.074019Z","shell.execute_reply.started":"2024-04-25T04:48:19.069155Z","shell.execute_reply":"2024-04-25T04:48:19.073058Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import copy\nfrom datetime import timedelta, datetime\nimport imageio\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nimport multiprocessing\nimport numpy as np\nimport os\nfrom pathlib import Path\nimport pydicom\nimport pytest\nimport scipy.ndimage as ndimage\nfrom scipy.ndimage.interpolation import zoom\nfrom skimage import measure, morphology, segmentation\nfrom time import time, sleep\nfrom tqdm import trange\nfrom tqdm.auto import tqdm\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset, random_split, DistributedSampler, DataLoader\nfrom torch.utils.tensorboard import SummaryWriter\nfrom torchvision import transforms\nimport warnings\nimport glob","metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","execution":{"iopub.status.busy":"2024-04-25T04:48:19.263371Z","iopub.execute_input":"2024-04-25T04:48:19.263778Z","iopub.status.idle":"2024-04-25T04:48:22.479387Z","shell.execute_reply.started":"2024-04-25T04:48:19.263740Z","shell.execute_reply":"2024-04-25T04:48:22.478651Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class CTScansDataset(Dataset):\n    def __init__(self, root_dir, transform=None,transform2=None):\n        self.root_dir = Path(root_dir)\n        self.patients = [p for p in glob.glob(root_dir+'*')]\n        self.transform = transform\n        self.transform2 = transform2\n\n    def __len__(self):\n        return len(self.patients)\n\n    def __getitem__(self, idx):\n        if torch.is_tensor(idx):\n            idx = idx.tolist()\n\n        image, metadata = self.load_scan(self.patients[idx])\n        sample = {'image': image, 'metadata': metadata}\n        return sample\n\n    def get_patient(self, patient_id):\n        patient_ids = [str(p.stem) for p in self.patients]\n        return self.__getitem__(patient_ids.index(patient_id))\n\n    @staticmethod\n    def load_scan(path):\n        T = [row for row in os.listdir(path)]\n        slices = [pydicom.dcmread(path + \"/\" + file) for file in T]\n        try:\n            slices.sort(key = lambda x: float(x.ImagePositionPatient[2]))\n        except:\n            pass\n        images = np.stack([s.pixel_array.astype(float) for s in slices])\n        images = images.astype(np.int16)\n        for n in range(len(slices)):\n            intercept = slices[n].RescaleIntercept\n            slope = slices[n].RescaleSlope\n            if slope != 1:\n                images[n] = slope * images[n].astype(np.float64)\n                images[n] = images[n].astype(np.int16)\n            images[n] += np.int16(intercept)\n        image = images\n        if image.shape[1]!=512 or image.shape[2]!=512:\n            mask = image>image[0,0,0]\n            z,y,x = np.where(mask)\n            z_min,z_max,y_min,y_max,x_min,x_max = z.min(),z.max(),y.min(),y.max(),x.min(),x.max()\n            image = image[:,y_min:y_max,x_min:x_max]\n        return image, slices[0]","metadata":{"execution":{"iopub.status.busy":"2024-04-25T04:49:07.685203Z","iopub.execute_input":"2024-04-25T04:49:07.685580Z","iopub.status.idle":"2024-04-25T04:49:07.707858Z","shell.execute_reply.started":"2024-04-25T04:49:07.685548Z","shell.execute_reply":"2024-04-25T04:49:07.707059Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from math import sqrt\nfrom joblib import Parallel, delayed\ntrain_dir = \"../input/osic-pulmonary-fibrosis-progression/train/\"\ntrain = CTScansDataset(root_dir=train_dir)","metadata":{"execution":{"iopub.status.busy":"2024-04-25T04:56:38.729651Z","iopub.execute_input":"2024-04-25T04:56:38.730147Z","iopub.status.idle":"2024-04-25T04:56:38.737958Z","shell.execute_reply.started":"2024-04-25T04:56:38.730104Z","shell.execute_reply":"2024-04-25T04:56:38.736436Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train[image]","metadata":{"execution":{"iopub.status.busy":"2024-04-25T04:59:13.485967Z","iopub.execute_input":"2024-04-25T04:59:13.486329Z","iopub.status.idle":"2024-04-25T04:59:13.505222Z","shell.execute_reply.started":"2024-04-25T04:59:13.486299Z","shell.execute_reply":"2024-04-25T04:59:13.503805Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!cp ../input/osic-model/Resnet34Unet.py ./","metadata":{"execution":{"iopub.status.busy":"2024-04-25T04:49:10.306475Z","iopub.execute_input":"2024-04-25T04:49:10.306840Z","iopub.status.idle":"2024-04-25T04:49:11.317674Z","shell.execute_reply.started":"2024-04-25T04:49:10.306810Z","shell.execute_reply":"2024-04-25T04:49:11.316263Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import importlib\nfrom sklearn.model_selection import KFold\nfrom torch.utils.data import DataLoader\nimport numpy as np\nimport torch\nimport os\nimport pandas as pd\nfrom tqdm.auto import tqdm\nfrom matplotlib import pyplot as plt\nimport cv2\nfrom PIL import Image\nimport glob\nimport os\nfrom Resnet34Unet import ResnetSuperVision","metadata":{"execution":{"iopub.status.busy":"2024-04-25T04:49:13.561441Z","iopub.execute_input":"2024-04-25T04:49:13.561894Z","iopub.status.idle":"2024-04-25T04:49:13.884868Z","shell.execute_reply.started":"2024-04-25T04:49:13.561851Z","shell.execute_reply":"2024-04-25T04:49:13.883984Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport cv2\nimport numpy as np\nimport pandas as pd\nfrom torch.utils.data import TensorDataset, DataLoader,Dataset\nimport albumentations as albu\n#from albumentations import torch as AT\nfrom skimage.color import gray2rgb\n\n\n\n\ndef get_img(path,x, folder: str='train_images'):\n    \"\"\"\n    Return image based on image name and folder.\n    \"\"\"\n    data_folder = os.path.join(path,folder)\n    image_path = os.path.join(data_folder, x)\n    img = cv2.imread(image_path)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    return img\n\ndef to_tensor(x, **kwargs):\n    \"\"\"\n    Convert image or mask.\n    \"\"\"\n    return x.transpose(2, 0, 1).astype('float32')\n\n\nsigmoid = lambda x: 1 / (1 + np.exp(-x))\n\n\ndef post_process(probability, threshold, min_size):\n    \"\"\"\n    Post processing of each predicted mask, components with lesser number of pixels\n    than `min_size` are ignored\n    \"\"\"\n    # don't remember where I saw it\n    mask = cv2.threshold(probability, threshold, 1, cv2.THRESH_BINARY)[1]\n    num_component, component = cv2.connectedComponents(mask.astype(np.uint8))\n    predictions = np.zeros((350, 525), np.float32)\n    num = 0\n    for c in range(1, num_component):\n        p = (component == c)\n        if p.sum() > min_size:\n            predictions[p] = 1\n            num += 1\n    return predictions, num\n\n\ndef get_training_augmentation(y=704,x=1024):\n    train_transform = [albu.RandomBrightnessContrast(p=0.3),\n#                            albu.RandomGamma(p=0.3),\n                           albu.VerticalFlip(p=0.5),\n                           albu.HorizontalFlip(p=0.5),\n#                            albu.ShiftScaleRotate(scale_limit=0, rotate_limit=10, shift_limit=0.0625, p=0.5, border_mode=0),\n                           albu.Downscale(p=1.0,scale_min=0.35,scale_max=0.75,),\n                           albu.Resize(y, x),\n                           albu.RandomCrop(height=400, width=400,p=0.5),\n#                            albu.GridDistortion(p=0.5),\n#                            albu.OpticalDistortion(p=0.5, distort_limit=2, shift_limit=0.5),\n                           albu.Resize(y, x)]\n    return albu.Compose(train_transform)\n\n\ndef get_validation_augmentation(y=704,x=1024):\n    \"\"\"Add paddings to make image shape divisible by 32\"\"\"\n    test_transform = [albu.Resize(y, x)]\n    return albu.Compose(test_transform)\n\n\ndef get_preprocessing(preprocessing_fn):\n    \"\"\"Construct preprocessing transform\n    \n    Args:\n        preprocessing_fn (callbale): data normalization function \n            (can be specific for each pretrained neural network)\n    Return:\n        transform: albumentations.Compose\n    \n    \"\"\"\n    \n    _transform = [\n        albu.Lambda(image=preprocessing_fn),\n        albu.Lambda(image=to_tensor, mask=to_tensor),\n    ]\n    return albu.Compose(_transform)\n\n\ndef set_lungwin(img, hu=[-1200., 600.]):\n    lungwin = np.array(hu)\n    newimg = (img-lungwin[0]) / (lungwin[1]-lungwin[0])\n    newimg[newimg < 0] = 0\n    newimg[newimg > 1] = 1\n    return newimg\n\nclass CTDataset2D(Dataset):\n    def __init__(self, x_train,y_train,y_train2,transforms = albu.Compose([albu.HorizontalFlip()]),preprocessing=None,size=512):\n        self.x_train = x_train\n        self.y_train = y_train\n        self.y_train2 = y_train2\n        self.transforms = transforms\n        self.preprocessing = preprocessing\n        self.size=size\n        self.hu =[[-1200., 600.],[-1800., 1000.],[-1500., 800.]]\n\n    def __getitem__(self, idx):\n        img = self.x_train[idx]\n        mask = self.y_train[idx]\n        mask2 = self.y_train2[idx]\n        mask = np.expand_dims(mask,axis=-1)\n        mask2 = np.expand_dims(mask2,axis=-1)\n        mask = np.concatenate([mask,mask2],axis=-1)\n        img = set_lungwin(img,self.hu[np.random.randint(3)])\n        img = img*255\n        img = img.astype(np.uint8)\n        img = gray2rgb(img)\n        \n        augmented = self.transforms(image=img, mask=mask)\n        img = augmented['image']\n        mask = augmented['mask']\n        if self.preprocessing:\n            preprocessed = self.preprocessing(image=img, mask=mask)\n            img = preprocessed['image']\n            mask = preprocessed['mask']\n        if self.y_train2[idx].sum()==0:\n            label = np.array(0.0)\n        else:\n            label = np.array(self.y_train[idx].sum()/self.y_train2[idx].sum())\n        return img, mask,torch.from_numpy(label.reshape(1,1))\n\n    def __len__(self):\n        return len(self.x_train)\n    \n\n    \ndef norm(img):\n    img-=img.min()\n    return img/img.max()\n","metadata":{"execution":{"iopub.status.busy":"2024-04-25T04:50:54.722998Z","iopub.execute_input":"2024-04-25T04:50:54.723436Z","iopub.status.idle":"2024-04-25T04:50:54.975850Z","shell.execute_reply.started":"2024-04-25T04:50:54.723401Z","shell.execute_reply":"2024-04-25T04:50:54.975155Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport functools\ndef preprocess_input(\n    x, mean=None, std=None, input_space=\"RGB\", input_range=None, **kwargs\n):\n\n    if input_space == \"BGR\":\n        x = x[..., ::-1].copy()\n\n    if input_range is not None:\n        if x.max() > 1 and input_range[1] == 1:\n            x = x / 255.0\n\n    if mean is not None:\n        mean = np.array(mean)\n        x = x - mean\n\n    if std is not None:\n        std = np.array(std)\n        x = x / std\n\n    return x","metadata":{"execution":{"iopub.status.busy":"2024-04-25T04:50:57.124654Z","iopub.execute_input":"2024-04-25T04:50:57.125017Z","iopub.status.idle":"2024-04-25T04:50:57.134496Z","shell.execute_reply.started":"2024-04-25T04:50:57.124987Z","shell.execute_reply":"2024-04-25T04:50:57.133520Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"formatted_settings = {\n            'input_size': [3, 224, 224],\n            'input_range': [0, 1],\n            'mean': [0.485, 0.456, 0.406],\n            'std': [0.229, 0.224, 0.225],}","metadata":{"execution":{"iopub.status.busy":"2024-04-25T04:50:57.673358Z","iopub.execute_input":"2024-04-25T04:50:57.673781Z","iopub.status.idle":"2024-04-25T04:50:57.678737Z","shell.execute_reply.started":"2024-04-25T04:50:57.673747Z","shell.execute_reply":"2024-04-25T04:50:57.677650Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class config:\n    model_name=\"resnet34\"\n    batch_size = 1\n    WORKERS = 1\n    DataLoder = {}\n    DataLoder['PY'] = \"\"\n    DataLoder[\"CLASS\"] = \"CTDataset2D\"\n    DataLoder[\"x_size\"] = 512\n    DataLoder[\"y_size\"] = 512\n    DataLoder[\"margin\"] = 512\n    preprocessing_fn = functools.partial(preprocess_input, **formatted_settings)\n    seg_classes =2\n    resume = True\n    MODEL_PATH = '../input/osic-model/'\n    if not os.path.exists(MODEL_PATH):\n        os.makedirs(MODEL_PATH)","metadata":{"execution":{"iopub.status.busy":"2024-04-25T04:51:36.039604Z","iopub.execute_input":"2024-04-25T04:51:36.040077Z","iopub.status.idle":"2024-04-25T04:51:36.050582Z","shell.execute_reply.started":"2024-04-25T04:51:36.040033Z","shell.execute_reply":"2024-04-25T04:51:36.049681Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_train_loder(x,y,y2):\n    train_dataset = CTDataset2D(x, y,y2,\n                                  transforms=get_training_augmentation(x=config.DataLoder[\"x_size\"], y=config.DataLoder[\"y_size\"]),\n                                  preprocessing=get_preprocessing(config.preprocessing_fn))\n    train_loader = DataLoader(train_dataset, batch_size=config.batch_size, shuffle=True, num_workers=4, pin_memory=True)\n    return train_loader,train_dataset\ndef get_val_loder(x,y,y2,b=18):\n    val_dataset = CTDataset2D(x, y,y2,\n                                  transforms=get_validation_augmentation(x=config.DataLoder[\"x_size\"], y=config.DataLoder[\"y_size\"]),\n                                  preprocessing=get_preprocessing(config.preprocessing_fn))\n    valid_loader = DataLoader(val_dataset, batch_size=b, shuffle=False, num_workers=config.WORKERS, pin_memory=True)\n    return valid_loader,val_dataset","metadata":{"execution":{"iopub.status.busy":"2024-04-25T04:51:38.345723Z","iopub.execute_input":"2024-04-25T04:51:38.346058Z","iopub.status.idle":"2024-04-25T04:51:38.355396Z","shell.execute_reply.started":"2024-04-25T04:51:38.346029Z","shell.execute_reply":"2024-04-25T04:51:38.354300Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = ResnetSuperVision(config.seg_classes, backbone_arch='resnet34').cuda()","metadata":{"execution":{"iopub.status.busy":"2024-04-25T04:51:39.188791Z","iopub.execute_input":"2024-04-25T04:51:39.189189Z","iopub.status.idle":"2024-04-25T04:51:43.211413Z","shell.execute_reply.started":"2024-04-25T04:51:39.189152Z","shell.execute_reply":"2024-04-25T04:51:43.210487Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.load_state_dict(torch.load(\"../input/osic-model/resnet34_fib_best.pth\"))","metadata":{"execution":{"iopub.status.busy":"2024-04-25T04:51:46.927194Z","iopub.execute_input":"2024-04-25T04:51:46.927585Z","iopub.status.idle":"2024-04-25T04:51:47.978118Z","shell.execute_reply.started":"2024-04-25T04:51:46.927547Z","shell.execute_reply":"2024-04-25T04:51:47.977126Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from torch.optim.lr_scheduler import ReduceLROnPlateau\nclass trainer:\n    def __init__(self,model):\n        self.model = model\n        if config.resume==True:\n            self.load_best_model()\n    \n    def batch_valid(self, batch_imgs,get_fet):\n        self.model.train()\n        batch_imgs = batch_imgs.cuda()\n        with torch.no_grad():\n            predicted = self.model(batch_imgs,get_fet)\n        predicted2 = torch.sigmoid(predicted[0])\n        if not get_fet:\n            return predicted2.cpu().numpy().astype(np.float32),predicted[1].cpu().numpy().astype(np.float32)\n        else:\n            return predicted2.cpu().numpy().astype(np.float32),predicted[1].cpu().numpy().astype(np.float32),predicted[2].cpu().numpy().astype(np.float32)\n         \n    def load_best_model(self):\n        if os.path.exists(config.MODEL_PATH+\"/{}_fib_best.pth\".format(config.model_name)):\n            self.model.load_state_dict(torch.load(config.MODEL_PATH+\"/{}_fib_best.pth\".format(config.model_name)))\n        \n    def predict(self,imgs_tensor,get_fet = False):\n        self.model.train()\n        with torch.no_grad():\n            return self.batch_valid(imgs_tensor,get_fet=get_fet)\n        ","metadata":{"execution":{"iopub.status.busy":"2024-04-25T04:51:56.669990Z","iopub.execute_input":"2024-04-25T04:51:56.670332Z","iopub.status.idle":"2024-04-25T04:51:56.684959Z","shell.execute_reply.started":"2024-04-25T04:51:56.670303Z","shell.execute_reply":"2024-04-25T04:51:56.683952Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Trainer = trainer(model)","metadata":{"execution":{"iopub.status.busy":"2024-04-25T04:52:03.206504Z","iopub.execute_input":"2024-04-25T04:52:03.206934Z","iopub.status.idle":"2024-04-25T04:52:03.286378Z","shell.execute_reply.started":"2024-04-25T04:52:03.206901Z","shell.execute_reply":"2024-04-25T04:52:03.285368Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Trainer.load_best_model()","metadata":{"execution":{"iopub.status.busy":"2024-04-25T04:52:05.037677Z","iopub.execute_input":"2024-04-25T04:52:05.038065Z","iopub.status.idle":"2024-04-25T04:52:05.110533Z","shell.execute_reply.started":"2024-04-25T04:52:05.038036Z","shell.execute_reply":"2024-04-25T04:52:05.109732Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for ids in tqdm(range(10)):\n    scan = train[ids]['image']\n    center = len(scan)//2\n    test = scan[center-2:center+2]\n    val_loder2,_ = get_val_loder(np.array(test),np.array(test),np.array(test),b=1)\n    for i,(imgs,masks,label) in enumerate(val_loder2):\n        if True:\n            im = norm(imgs.cpu().numpy()[0].transpose(1,2,0))\n            plt.figure(figsize=[20,10])\n            plt.subplot(131)\n            plt.imshow(im)\n            plt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import cv2\n\n# Load your own lung image\nmy_lung_image = cv2.imread('/kaggle/input/lungimages/11 (139).jpg')\n","metadata":{"execution":{"iopub.status.busy":"2024-04-25T05:36:48.560207Z","iopub.execute_input":"2024-04-25T05:36:48.560689Z","iopub.status.idle":"2024-04-25T05:36:48.577981Z","shell.execute_reply.started":"2024-04-25T05:36:48.560640Z","shell.execute_reply":"2024-04-25T05:36:48.576959Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\n\n# Resize and normalize your image\nresized_image = cv2.resize(my_lung_image, (512, 512))  # Use the desired dimensions\nnormalized_image = resized_image.astype(np.float32) / 255.0  # Normalize to [0, 1]\n","metadata":{"execution":{"iopub.status.busy":"2024-04-25T05:36:49.619010Z","iopub.execute_input":"2024-04-25T05:36:49.619349Z","iopub.status.idle":"2024-04-25T05:36:49.626661Z","shell.execute_reply.started":"2024-04-25T05:36:49.619320Z","shell.execute_reply":"2024-04-25T05:36:49.625460Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Assuming you have the model 'Trainer' initialized somewhere in your code\nres = Trainer.predict(torch.tensor([normalized_image.transpose(2, 0, 1)]).cuda(), get_fet=True)\n","metadata":{"execution":{"iopub.status.busy":"2024-04-25T05:36:50.429690Z","iopub.execute_input":"2024-04-25T05:36:50.430050Z","iopub.status.idle":"2024-04-25T05:36:50.658464Z","shell.execute_reply.started":"2024-04-25T05:36:50.430019Z","shell.execute_reply":"2024-04-25T05:36:50.657702Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!python --version","metadata":{"execution":{"iopub.status.busy":"2024-04-25T05:53:02.478424Z","iopub.execute_input":"2024-04-25T05:53:02.478988Z","iopub.status.idle":"2024-04-25T05:53:03.506768Z","shell.execute_reply.started":"2024-04-25T05:53:02.478924Z","shell.execute_reply":"2024-04-25T05:53:03.505804Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pip show matplotlib","metadata":{"execution":{"iopub.status.busy":"2024-04-25T06:24:44.447024Z","iopub.execute_input":"2024-04-25T06:24:44.447472Z","iopub.status.idle":"2024-04-25T06:24:50.712077Z","shell.execute_reply.started":"2024-04-25T06:24:44.447432Z","shell.execute_reply":"2024-04-25T06:24:50.711139Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Plotting the results\nlung_mask = res[0][0, 1] > 0.9\nfibrosis_mask = res[0][0, 0] > 0.9\n\nplt.figure(figsize=[20, 10])\nplt.subplot(131)\nplt.imshow(my_lung_image)  # Show your own image\nplt.subplot(132)\nplt.imshow(my_lung_image)\nplt.imshow(lung_mask, cmap='hot', alpha=0.5)\nplt.title(\"lung segmentation\")\nplt.subplot(133)\nplt.imshow(my_lung_image)\nplt.imshow(fibrosis_mask, cmap='hot', alpha=0.9)\nplt.title(\"fibrosis segmentation\")\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-04-25T06:49:46.864664Z","iopub.execute_input":"2024-04-25T06:49:46.865086Z","iopub.status.idle":"2024-04-25T06:49:47.566144Z","shell.execute_reply.started":"2024-04-25T06:49:46.865041Z","shell.execute_reply":"2024-04-25T06:49:47.565199Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for ids in tqdm(range(10)):\n    scan = train[ids]['image']\n    center = len(scan)//2\n    test = scan[center-2:center+2]\n    val_loder2,_ = get_val_loder(np.array(test),np.array(test),np.array(test),b=1)\n    for i,(imgs,masks,label) in enumerate(val_loder2):\n        if True:\n            res = Trainer.predict(imgs.cuda(),get_fet=True)\n            res1 = Trainer.predict(torch.flip(imgs.cuda(),[-1]),get_fet=True)\n            res2 = Trainer.predict(torch.flip(imgs.cuda(),[-2]),get_fet=True)\n            res = list(res)\n            res[0] = np.flip(res1[0],-1)+ res[0] +np.flip(res2[0],-2)\n            res[1] = res1[1]+ res[1] +res2[1]\n            res[0] = res[0] /3\n            res[1] = res[1] /3\n            res[2] = res1[2]+ res[2] +res2[2]\n            res[2] = res[2] /3\n            lung_mask = res[0][0,1]>0.9\n            lung_mask = cv2.resize(lung_mask.astype(np.uint8),(test[i].shape[1],test[i].shape[0]))\n            fibrosis_mask = res[0][0,0]>0.9\n            fibrosis_mask = cv2.resize(fibrosis_mask.astype(np.uint8),(test[i].shape[1],test[i].shape[0]))\n            im = norm(imgs.cpu().numpy()[0].transpose(1,2,0))\n            plt.figure(figsize=[20,10])\n            plt.subplot(131)\n            plt.imshow(im)\n            plt.subplot(132)\n            plt.imshow(im)\n            plt.imshow(res[0][0,1]>0.9,cmap='hot',alpha=.5)\n            plt.title(\"lung segmentation\")\n            plt.subplot(133)\n            plt.imshow(im)\n            plt.imshow(res[0][0,0]>0.9,cmap='hot',alpha=.5)\n            plt.title(\"fibrosis segmentation\")\n            plt.show()","metadata":{"execution":{"iopub.status.busy":"2024-04-25T06:52:37.337351Z","iopub.execute_input":"2024-04-25T06:52:37.337873Z","iopub.status.idle":"2024-04-25T06:53:57.297283Z","shell.execute_reply.started":"2024-04-25T06:52:37.337814Z","shell.execute_reply":"2024-04-25T06:53:57.296145Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!python /kaggle/input/osic-model/Resnet34Unet.py","metadata":{"execution":{"iopub.status.busy":"2024-04-24T16:06:15.628350Z","iopub.execute_input":"2024-04-24T16:06:15.628733Z","iopub.status.idle":"2024-04-24T16:06:18.683948Z","shell.execute_reply.started":"2024-04-24T16:06:15.628695Z","shell.execute_reply":"2024-04-24T16:06:18.683070Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n","metadata":{},"execution_count":null,"outputs":[]}]}