{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt \nfrom pydicom import dcmread\nimport os \nimport cv2\nimport torch.nn as nn\nimport pandas as pd \nimport numpy as np\nimport torch \nfrom typing import List\nfrom matplotlib.patches import Rectangle \n\nBASE_FOLDER = \"/kaggle/input/vinbigdata-chest-xray-abnormalities-detection/train\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df = pd.read_csv(\"/kaggle/input/vinbigdata-chest-xray-abnormalities-detection/train.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_sample(df, index):\n    sample = df.iloc[index]\n    image_id = sample['image_id']\n    class_name = sample['class_name']\n    path = os.path.join(BASE_FOLDER, image_id+\".dicom\")\n    \n    raw_img = dcmread(path)\n    img = raw_img.pixel_array\n    mask = np.zeros(img.shape)\n    \n    if class_name != 'No finding':\n        x_min = sample['x_min'].astype(int)\n        y_min = sample['y_min'].astype(int)\n        height = sample['y_max'].astype(int) - y_min\n        width = sample['x_max'].astype(int) - x_min\n        \n        mask[y_min:y_min+width, x_min:x_min+height] = 1\n        \n    return img, mask, class_name\n        \ndef plot_image(df, index):\n    \n    sample = df.iloc[index]\n    img, mask, class_name = get_sample(df, index)\n    \n    fig, ax = plt.subplots(1,2, dpi=100)\n    ax[0].imshow(img, cmap=plt.cm.gray);\n    ax[1].imshow(mask, cmap=plt.cm.gray);\n\n    if class_name != 'No finding':\n        x_min = sample['x_min'].astype(int)\n        y_min = sample['y_min'].astype(int)\n        height = sample['y_max'].astype(int) - y_min\n        width = sample['x_max'].astype(int) - x_min\n        \n        rect = Rectangle(\n            (x_min, y_min), \n            height, \n            width, \n            edgecolor='red', \n            facecolor='none'\n        )\n    \n    ax[0].add_patch(rect)\n    plt.tight_layout();\n    plt.show();","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plot_image(df, 3);","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def double_conv(in_c, out_c):\n    return nn.Sequential(\n        nn.Conv2d(in_c, out_c, kernel_size=3),\n        nn.ReLU(inplace=True),\n        nn.Conv2d(out_c, out_c, kernel_size=3),\n        nn.ReLU(inplace=True),\n    )\n\ndef crop_and_cat(source, target):\n    source_size_x = target.shape[2]\n    target_size_x = target.shape[2]\n    \n    source_size_y = target.shape[3]\n    target_size_y = target.shape[3]\n    \n    delta_x = (source_size_x-target_size_x)//2\n    delta_y = (source_size_y-target_size_y)//2\n    \n    cropped = source[:, :, delta_x: source_size_x-delta_x, delta_y:source_size_y-delta_y]\n    clipped = torch.cat([cropped, target], 1)\n    return clipped\n        \nclass UNET(nn.Module):\n    def __init__(self):\n        super(UNET, self).__init__()\n        \n        self.max_pool = nn.MaxPool2d(kernel_size=2, stride=2)\n        \n        self.down_conv1 = double_conv(1, 64)\n        self.down_conv2 = double_conv(64, 128)\n        self.down_conv3 = double_conv(128, 256)\n        self.down_conv4 = double_conv(256, 512)\n        self.down_conv5 = double_conv(512, 1024)\n        \n        self.up_trans1 = nn.ConvTranspose2d(1024, 512, kernel_size=2, stride=2)\n        self.up_conv1 = double_conv(1024, 512)\n\n        self.up_trans2 = nn.ConvTranspose2d(512, 256, kernel_size=2, stride=2)\n        self.up_conv2 = double_conv(512, 256)\n        \n        self.up_trans3 = nn.ConvTranspose2d(256, 128, kernel_size=2, stride=2)\n        self.up_conv3 = double_conv(256, 128)\n\n        self.up_trans4 = nn.ConvTranspose2d(128, 64, kernel_size=2, stride=2)\n        self.up_conv4 = double_conv(128, 64)\n\n        self.out = nn.Conv2d(64, 2, kernel_size=1)\n        \n        \n    def forward(self, image):\n        \n        # encoder\n        \n        x1 = self.down_conv1(image)\n        x2 = self.max_pool(x1)\n        x3 = self.down_conv2(x2)\n        x4 = self.max_pool(x3)\n        x5 = self.down_conv3(x4)\n        x6 = self.max_pool(x5)\n        x7 = self.down_conv4(x6)\n        x8 = self.max_pool(x7)\n        x9 = self.down_conv5(x8)\n\n        # decoder \n        x = self.up_trans1(x9)\n        x = crop_and_cat(x7 , x)\n        x = self.up_conv1(x)\n\n        x = self.up_trans2(x)\n        x = crop_and_cat(x5 , x)\n        x = self.up_conv2(x)        \n\n        x = self.up_trans3(x)\n        x = crop_and_cat(x3 , x)\n        x = self.up_conv3(x)\n\n        x = self.up_trans4(x)\n        x = crop_and_cat(x1 , x)\n        x = self.up_conv4(x)\n\n        out = self.out(x)\n        print(out.shape)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"device = torch.device('cuda')\n\nunet = UNET()\nunet.to(device)\n\nimg, _, _ = get_sample(df, 1)\nx = img.reshape(1,1,img.shape[0], img.shape[1]).astype(np.float32)\nx = torch.tensor(x)\nx = x.to(device)\n\nunet(x)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":4}