{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":9988,"databundleVersionId":868324,"sourceType":"competition"}],"dockerImageVersionId":30732,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# EDA","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport os\nimport cv2\nimport matplotlib.pyplot as plt\nfrom skimage.io import imread\nimport random","metadata":{"execution":{"iopub.status.busy":"2024-07-14T19:16:35.275263Z","iopub.execute_input":"2024-07-14T19:16:35.275853Z","iopub.status.idle":"2024-07-14T19:16:37.538295Z","shell.execute_reply.started":"2024-07-14T19:16:35.275805Z","shell.execute_reply":"2024-07-14T19:16:37.537137Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"folder_path = '/kaggle/input/airbus-ship-detection'\ntrain_path = '/kaggle/input/airbus-ship-detection/train_v2'\ntest_path = '/kaggle/input/airbus-ship-detection/train_v2'","metadata":{"execution":{"iopub.status.busy":"2024-07-14T19:16:37.540461Z","iopub.execute_input":"2024-07-14T19:16:37.541147Z","iopub.status.idle":"2024-07-14T19:16:37.547562Z","shell.execute_reply.started":"2024-07-14T19:16:37.541105Z","shell.execute_reply":"2024-07-14T19:16:37.545921Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"os.listdir(folder_path)","metadata":{"execution":{"iopub.status.busy":"2024-07-14T19:16:37.558285Z","iopub.execute_input":"2024-07-14T19:16:37.558666Z","iopub.status.idle":"2024-07-14T19:16:37.571936Z","shell.execute_reply.started":"2024-07-14T19:16:37.558636Z","shell.execute_reply":"2024-07-14T19:16:37.570087Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_files_list = os.listdir(os.path.join(folder_path, 'train_v2'))\nprint(f'Number of images in train set: {len(train_files_list)}')\n\ntest_files_list = os.listdir(os.path.join(folder_path, 'test_v2'))\nprint(f'Number of images in test set: {len(test_files_list)}')","metadata":{"execution":{"iopub.status.busy":"2024-07-14T19:16:37.573831Z","iopub.execute_input":"2024-07-14T19:16:37.574274Z","iopub.status.idle":"2024-07-14T19:16:39.664293Z","shell.execute_reply.started":"2024-07-14T19:16:37.574234Z","shell.execute_reply":"2024-07-14T19:16:39.662993Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig, axarr = plt.subplots(3, 3, figsize=(15, 15))\n\nfor i, ax in enumerate(axarr.flat):\n    \n    img = imread(os.path.join(train_path, train_files_list[i + 200]))\n    ax.axis('off')\n    ax.imshow(img)\n    ax.set_title(f'Image {i+1}')\n\nplt.tight_layout(h_pad=0.1, w_pad=0.1)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-07-14T19:16:39.665999Z","iopub.execute_input":"2024-07-14T19:16:39.666411Z","iopub.status.idle":"2024-07-14T19:16:43.101478Z","shell.execute_reply.started":"2024-07-14T19:16:39.666374Z","shell.execute_reply":"2024-07-14T19:16:43.099806Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Utility functions","metadata":{}},{"cell_type":"code","source":"# ref.: https://www.kaggle.com/stainsby/fast-tested-rle\ndef rle_encode(img):\n    '''\n    img: numpy array, 1 - mask, 0 - background\n    Returns run length as string formated\n    '''\n    pixels = img.flatten()\n    pixels = np.concatenate([[0], pixels, [0]])\n    runs = np.where(pixels[1:] != pixels[:-1])[0] + 1\n    runs[1::2] -= runs[::2]\n    return ' '.join(str(x) for x in runs)\n \ndef rle_decode(mask_rle, shape=(768, 768)):\n    '''\n    mask_rle: run-length as string formated (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] = 1\n    return img.reshape(shape).T # added tranpose here","metadata":{"execution":{"iopub.status.busy":"2024-07-14T19:16:43.102997Z","iopub.execute_input":"2024-07-14T19:16:43.103360Z","iopub.status.idle":"2024-07-14T19:16:43.113469Z","shell.execute_reply.started":"2024-07-14T19:16:43.103331Z","shell.execute_reply":"2024-07-14T19:16:43.112301Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def masks_as_image(in_mask_list):\n    # Take the individual ship masks and create a single mask array for all ships\n    all_masks = np.zeros((768, 768), dtype = np.int16)\n    #if isinstance(in_mask_list, list):\n    for mask in in_mask_list:\n        if isinstance(mask, str):\n            all_masks += rle_decode(mask)\n    return np.expand_dims(all_masks, -1)\n  ","metadata":{"execution":{"iopub.status.busy":"2024-07-14T19:16:43.114779Z","iopub.execute_input":"2024-07-14T19:16:43.115130Z","iopub.status.idle":"2024-07-14T19:16:43.125644Z","shell.execute_reply.started":"2024-07-14T19:16:43.115103Z","shell.execute_reply":"2024-07-14T19:16:43.124448Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Masks","metadata":{}},{"cell_type":"code","source":"masks = pd.read_csv(os.path.join(folder_path,'train_ship_segmentations_v2.csv'))\n\nprint(masks.columns)\nprint(masks.shape[0], 'masks found')\nprint(masks['ImageId'].nunique(), 'images\\n')\n\nmasks.head()","metadata":{"execution":{"iopub.status.busy":"2024-07-14T19:16:43.130094Z","iopub.execute_input":"2024-07-14T19:16:43.130509Z","iopub.status.idle":"2024-07-14T19:16:44.332694Z","shell.execute_reply.started":"2024-07-14T19:16:43.130475Z","shell.execute_reply":"2024-07-14T19:16:44.331502Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ImageId = train_files_list[203]\n\nimg = imread(os.path.join(train_path, ImageId))\nimg_masks = masks.loc[masks['ImageId'] == ImageId, 'EncodedPixels'].tolist()\n\nall_masks = masks_as_image(img_masks)\n\nfig, axarr = plt.subplots(1, 2, figsize=(15, 40))\n\naxarr[0].axis('off')\naxarr[1].axis('off')\n# axarr[2].axis('off')\n\naxarr[0].imshow(img)\naxarr[1].imshow(all_masks)\n\naxarr[0].set_title('Original Image')\naxarr[1].set_title('Segmentation Mask')\n\nplt.tight_layout(h_pad=0.1, w_pad=0.1)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-07-14T19:16:44.334184Z","iopub.execute_input":"2024-07-14T19:16:44.334506Z","iopub.status.idle":"2024-07-14T19:16:45.168864Z","shell.execute_reply.started":"2024-07-14T19:16:44.334476Z","shell.execute_reply":"2024-07-14T19:16:45.167652Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Examine Number of Ship Images","metadata":{}},{"cell_type":"code","source":"masks['NumOfShips'] = masks['EncodedPixels'].apply(lambda x: 1 if isinstance(x, str) else 0)","metadata":{"execution":{"iopub.status.busy":"2024-07-14T19:16:45.170249Z","iopub.execute_input":"2024-07-14T19:16:45.170618Z","iopub.status.idle":"2024-07-14T19:16:45.293783Z","shell.execute_reply.started":"2024-07-14T19:16:45.170589Z","shell.execute_reply":"2024-07-14T19:16:45.292656Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"masks.head()","metadata":{"execution":{"iopub.status.busy":"2024-07-14T19:16:45.295002Z","iopub.execute_input":"2024-07-14T19:16:45.295293Z","iopub.status.idle":"2024-07-14T19:16:45.305956Z","shell.execute_reply.started":"2024-07-14T19:16:45.295266Z","shell.execute_reply":"2024-07-14T19:16:45.304744Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"unique_img_ids = masks.groupby('ImageId').agg({'NumOfShips': 'sum'}).reset_index()\nunique_img_ids['has_ship'] = unique_img_ids['NumOfShips'].map(lambda x: 1 if x > 0 else 0)\nunique_img_ids = unique_img_ids[~unique_img_ids['ImageId'].isin(['6384c3e78.jpg'])] # remove corrupted file\nmasks.drop(['NumOfShips'], axis=1, inplace=True)\nunique_img_ids","metadata":{"execution":{"iopub.status.busy":"2024-07-14T19:16:45.307387Z","iopub.execute_input":"2024-07-14T19:16:45.307733Z","iopub.status.idle":"2024-07-14T19:16:45.632544Z","shell.execute_reply.started":"2024-07-14T19:16:45.307705Z","shell.execute_reply":"2024-07-14T19:16:45.631244Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"has_ship_counts = unique_img_ids['has_ship'].value_counts()\n\nwithout_ships = has_ship_counts[0]\nwith_ships = has_ship_counts[1]\n\n\nprint(f'Number of images without ships: {without_ships}')\nprint(f'Number of images with ships: {with_ships}\\n')\n\nwithout_pct = (without_ships * 100) / (without_ships + with_ships)\nwith_pct = 100 - without_pct\n\nprint(f'Number of images without ships (percents): {without_pct}%')\nprint(f'Number of images with ships (percents): {with_pct}%')\n\nplt.figure(figsize=(8, 6))\n\nplt.bar(['Without ship','With ships'], has_ship_counts, color=['skyblue', 'pink'])\nplt.title('Dataset images')\n\nplt.ylabel('Number of images')\n\nplt.grid()\n\nplt.xticks(rotation=0)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-07-14T19:16:45.634076Z","iopub.execute_input":"2024-07-14T19:16:45.634487Z","iopub.status.idle":"2024-07-14T19:16:45.831054Z","shell.execute_reply.started":"2024-07-14T19:16:45.634448Z","shell.execute_reply":"2024-07-14T19:16:45.829993Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_with_ships = unique_img_ids[unique_img_ids['has_ship'] == 1]\n\nplt.figure(figsize=(10, 6))\nplt.hist(df_with_ships['NumOfShips'], bins=range(1, 18), edgecolor='black', align='left')\nplt.xticks(range(1, 17))\nplt.xlabel('Number of Ships')\nplt.ylabel('Frequency')\nplt.title(' Images with Ships Distribution')\nplt.grid(axis='y')\n\n# Show the plot\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-07-14T19:16:45.832387Z","iopub.execute_input":"2024-07-14T19:16:45.832700Z","iopub.status.idle":"2024-07-14T19:16:46.109625Z","shell.execute_reply.started":"2024-07-14T19:16:45.832674Z","shell.execute_reply":"2024-07-14T19:16:46.108169Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Split to train and validation set. Balance the sets","metadata":{}},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\ntrain_ids, valid_ids = train_test_split(unique_img_ids, \n                 test_size = 0.3, \n                 stratify = unique_img_ids['NumOfShips'])\ntrain_df = pd.merge(masks, train_ids)\nvalid_df = pd.merge(masks, valid_ids)\nprint(train_df.shape[0], 'training masks')\nprint(valid_df.shape[0], 'validation masks')","metadata":{"execution":{"iopub.status.busy":"2024-07-14T19:16:46.110922Z","iopub.execute_input":"2024-07-14T19:16:46.111251Z","iopub.status.idle":"2024-07-14T19:16:46.967589Z","shell.execute_reply.started":"2024-07-14T19:16:46.111223Z","shell.execute_reply":"2024-07-14T19:16:46.966404Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df['NumOfShips'].hist()","metadata":{"execution":{"iopub.status.busy":"2024-07-14T19:16:46.968796Z","iopub.execute_input":"2024-07-14T19:16:46.969223Z","iopub.status.idle":"2024-07-14T19:16:47.289279Z","shell.execute_reply.started":"2024-07-14T19:16:46.969185Z","shell.execute_reply":"2024-07-14T19:16:47.288055Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"min_count = train_df['NumOfShips'].value_counts().min()\nbalanced_df = train_df.groupby('NumOfShips').apply(lambda x: x.sample(min_count)).reset_index(drop=True)\nfiltered_train_df = train_df[train_df['ImageId'].isin(balanced_df['ImageId'])]","metadata":{"execution":{"iopub.status.busy":"2024-07-14T19:16:47.290908Z","iopub.execute_input":"2024-07-14T19:16:47.291348Z","iopub.status.idle":"2024-07-14T19:16:47.355385Z","shell.execute_reply.started":"2024-07-14T19:16:47.291312Z","shell.execute_reply":"2024-07-14T19:16:47.354225Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"filtered_train_df['NumOfShips'].hist()","metadata":{"execution":{"iopub.status.busy":"2024-07-14T19:16:47.357011Z","iopub.execute_input":"2024-07-14T19:16:47.357688Z","iopub.status.idle":"2024-07-14T19:16:47.651171Z","shell.execute_reply.started":"2024-07-14T19:16:47.357651Z","shell.execute_reply":"2024-07-14T19:16:47.650052Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Decode all RLE to Images\n","metadata":{}},{"cell_type":"code","source":"def df_rle_to_image(df, train_folder_path):\n    img_ids = list(df.groupby('ImageId'))\n    \n    out_rgbs = []\n    out_masks = []\n    \n    for img_info in img_ids:\n        \n        img_id = img_info[0]\n        \n        img_rgb = imread(os.path.join(train_folder_path, img_id))\n        img_mask = masks_as_image(df.loc[df['ImageId'] == img_id, 'EncodedPixels'].tolist())\n        \n        out_rgbs += [img_rgb]\n        out_masks += [img_mask]\n        \n    \n    return out_rgbs, out_masks\n\n ","metadata":{"execution":{"iopub.status.busy":"2024-07-14T19:16:47.652619Z","iopub.execute_input":"2024-07-14T19:16:47.653041Z","iopub.status.idle":"2024-07-14T19:16:47.660673Z","shell.execute_reply.started":"2024-07-14T19:16:47.653003Z","shell.execute_reply":"2024-07-14T19:16:47.659405Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x, y = df_rle_to_image(filtered_train_df, train_folder_path = train_path)","metadata":{"execution":{"iopub.status.busy":"2024-07-14T19:16:47.662432Z","iopub.execute_input":"2024-07-14T19:16:47.663052Z","iopub.status.idle":"2024-07-14T19:18:53.202812Z","shell.execute_reply.started":"2024-07-14T19:16:47.663011Z","shell.execute_reply":"2024-07-14T19:18:53.201462Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig, axarr = plt.subplots(1, 2, figsize=(15, 40))\n\naxarr[0].axis('off')\naxarr[1].axis('off')\n# axarr[2].axis('off')\n\naxarr[0].imshow(x[1030])\naxarr[1].imshow(y[1030])\n\naxarr[0].set_title('Original Image')\naxarr[1].set_title('Segmentation Mask')\n\nplt.tight_layout(h_pad=0.1, w_pad=0.1)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-07-14T19:18:53.204360Z","iopub.execute_input":"2024-07-14T19:18:53.204714Z","iopub.status.idle":"2024-07-14T19:18:54.039135Z","shell.execute_reply.started":"2024-07-14T19:18:53.204686Z","shell.execute_reply":"2024-07-14T19:18:54.036667Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def batch_gen(batch_size, images, masks):\n    \n    out_rgb = []\n    out_mask = []\n    \n    while True:\n        # random shuffle\n        combined = list(zip(images, masks))\n        random.shuffle(combined)\n\n\n        for image, mask in combined:\n\n            out_rgb.append(image)\n            out_mask.append(mask)\n\n            if len(out_rgb)>=batch_size:\n                yield np.stack(out_rgb, 0)/255.0, np.stack(out_mask, 0)\n                out_rgb, out_mask=[], []\n\n    ","metadata":{"execution":{"iopub.status.busy":"2024-07-14T19:18:54.041126Z","iopub.execute_input":"2024-07-14T19:18:54.041535Z","iopub.status.idle":"2024-07-14T19:18:54.049037Z","shell.execute_reply.started":"2024-07-14T19:18:54.041504Z","shell.execute_reply":"2024-07-14T19:18:54.047768Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"b_gen = batch_gen(4, x, y)","metadata":{"execution":{"iopub.status.busy":"2024-07-14T19:18:54.050331Z","iopub.execute_input":"2024-07-14T19:18:54.050738Z","iopub.status.idle":"2024-07-14T19:18:54.063135Z","shell.execute_reply.started":"2024-07-14T19:18:54.050709Z","shell.execute_reply":"2024-07-14T19:18:54.062002Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"batch_x, batch_y = next(b_gen)","metadata":{"execution":{"iopub.status.busy":"2024-07-14T19:18:54.064535Z","iopub.execute_input":"2024-07-14T19:18:54.064883Z","iopub.status.idle":"2024-07-14T19:18:54.109138Z","shell.execute_reply.started":"2024-07-14T19:18:54.064856Z","shell.execute_reply":"2024-07-14T19:18:54.107880Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"batch_y.shape","metadata":{"execution":{"iopub.status.busy":"2024-07-14T19:18:54.110499Z","iopub.execute_input":"2024-07-14T19:18:54.111307Z","iopub.status.idle":"2024-07-14T19:18:54.118743Z","shell.execute_reply.started":"2024-07-14T19:18:54.111274Z","shell.execute_reply":"2024-07-14T19:18:54.117346Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Augment data","metadata":{}},{"cell_type":"code","source":"# x = np.asarray(x)\n# y = np.asarray(y)","metadata":{"execution":{"iopub.status.busy":"2024-07-14T19:18:54.124380Z","iopub.execute_input":"2024-07-14T19:18:54.124763Z","iopub.status.idle":"2024-07-14T19:18:54.129497Z","shell.execute_reply.started":"2024-07-14T19:18:54.124735Z","shell.execute_reply":"2024-07-14T19:18:54.128227Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n\ndatagen_args = dict(\n    rotation_range=90,  # randomly rotate images by up to 90 degrees\n    width_shift_range=0.1,  # randomly shift images horizontally by up to 10%\n    height_shift_range=0.1,  # randomly shift images vertically by up to 10%\n    shear_range=0.02,  # shear angle in counter-clockwise direction in degrees\n    zoom_range=0.2,  # randomly zoom into images by up to 20%\n    horizontal_flip=True,  # randomly flip images horizontally\n    vertical_flip=True,  # randomly flip images vertically\n    fill_mode='reflect')\n    \nimage_gen = ImageDataGenerator(**datagen_args)\nmask_gen = ImageDataGenerator(**datagen_args)\n\n","metadata":{"execution":{"iopub.status.busy":"2024-07-14T19:18:54.131261Z","iopub.execute_input":"2024-07-14T19:18:54.131588Z","iopub.status.idle":"2024-07-14T19:19:07.493458Z","shell.execute_reply.started":"2024-07-14T19:18:54.131562Z","shell.execute_reply":"2024-07-14T19:19:07.492505Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def augment_generator(batch_gen, seed = 67):\n    np.random.seed(seed)\n    \n    for x, y in batch_gen:\n        \n#         seed = np.random.choice(range(9999))\n        batch_size = x.shape[0]\n        g_x = image_gen.flow(255*x, batch_size = batch_size, seed = seed)\n        g_y = mask_gen.flow(y, batch_size = batch_size, seed = seed)\n        \n\n        yield next(g_x)/255.0, next(g_y)\n        ","metadata":{"execution":{"iopub.status.busy":"2024-07-14T19:19:07.494618Z","iopub.execute_input":"2024-07-14T19:19:07.495247Z","iopub.status.idle":"2024-07-14T19:19:07.501512Z","shell.execute_reply.started":"2024-07-14T19:19:07.495216Z","shell.execute_reply":"2024-07-14T19:19:07.500344Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"augm_gen = augment_generator(b_gen)\n\naugm_x, augm_y = next(augm_gen)\n\nprint('x', augm_x.shape, augm_x.dtype, augm_x.min(), augm_x.max())\nprint('y', augm_y.shape, augm_y.dtype, augm_y.min(), augm_y.max())\n\n","metadata":{"execution":{"iopub.status.busy":"2024-07-14T19:19:07.503243Z","iopub.execute_input":"2024-07-14T19:19:07.504024Z","iopub.status.idle":"2024-07-14T19:19:08.366732Z","shell.execute_reply.started":"2024-07-14T19:19:07.503985Z","shell.execute_reply":"2024-07-14T19:19:08.365687Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"augm_x = augm_x[:4]\naugm_y = augm_y[:4]\n\n# Displaying the images and their corresponding masks\nfig, axs = plt.subplots(4, 2, figsize=(10, 20))\nfor i in range(4):\n    axs[i, 0].imshow(augm_x[i])\n    axs[i, 0].set_title(f'Image {i+1}')\n    axs[i, 0].axis('off')\n    axs[i, 1].imshow(augm_y[i, :, :, 0])\n    axs[i, 1].set_title(f'Mask {i+1}')\n    axs[i, 1].axis('off')\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-07-14T19:19:08.368221Z","iopub.execute_input":"2024-07-14T19:19:08.368641Z","iopub.status.idle":"2024-07-14T19:19:10.355790Z","shell.execute_reply.started":"2024-07-14T19:19:08.368605Z","shell.execute_reply":"2024-07-14T19:19:10.354700Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def montage_images(images, ncols=5):\n    \n    nindex, height, width, intensity = images.shape\n    nrows = int(np.ceil(nindex / ncols))\n    \n    # Pad with empty images if necessary\n    padded_images = np.zeros((nrows * ncols, height, width, intensity), dtype=images.dtype)\n    padded_images[:nindex, :, :, :] = images\n    \n    # Create the montage\n    montage_image = (padded_images.reshape(nrows, ncols, height, width, intensity)\n                                   .swapaxes(1, 2)\n                                   .reshape(height * nrows, width * ncols, intensity))\n    return montage_image","metadata":{"execution":{"iopub.status.busy":"2024-07-14T19:19:10.357326Z","iopub.execute_input":"2024-07-14T19:19:10.357705Z","iopub.status.idle":"2024-07-14T19:19:10.365865Z","shell.execute_reply.started":"2024-07-14T19:19:10.357674Z","shell.execute_reply":"2024-07-14T19:19:10.364624Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"augm_x = augm_x[:4]\naugm_y = augm_y[:4]\n\n# Displaying the images and their corresponding masks using montage\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(20, 10))\n\n# Display the montage of the images\nax1.imshow(montage_images(augm_x, ncols=2))\nax1.set_title('Images')\nax1.axis('off')\n\n# Display the montage of the masks\nax2.imshow(montage_images(augm_y[:, :, :, 0].reshape(augm_y.shape[0], augm_y.shape[1], augm_y.shape[2], 1), ncols=2))\nax2.set_title('Masks')\nax2.axis('off')\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-07-14T19:19:10.367434Z","iopub.execute_input":"2024-07-14T19:19:10.367923Z","iopub.status.idle":"2024-07-14T19:19:11.619776Z","shell.execute_reply.started":"2024-07-14T19:19:10.367888Z","shell.execute_reply":"2024-07-14T19:19:11.618497Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}