{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"scrolled":false},"cell_type":"code","source":"import os, keras\nimport cv2\nimport glob\nimport PIL\nfrom PIL import Image\nimport numpy as np \nimport pandas as pd \nimport matplotlib.pyplot as plt\nimport matplotlib\nimport tensorflow as tf\nimport keras.backend as K\n\nfrom sklearn.model_selection import train_test_split\nfrom keras.models import *\nfrom keras.layers import *\nfrom keras.optimizers import *\nfrom tqdm import tqdm\nfrom tensorflow.keras.preprocessing.image import load_img, ImageDataGenerator, img_to_array, array_to_img","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"scrolled":false},"cell_type":"code","source":"#Set some directories\ntrainHQ_zip_path = '/kaggle/input/carvana-image-masking-challenge/train_hq.zip'\nmasks_zip_path = '/kaggle/input/carvana-image-masking-challenge/train_masks.zip'","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import zipfile\n#Extract train images.\nwith zipfile.ZipFile(trainHQ_zip_path,'r') as zip_ref:\n    zip_ref.extractall('/kaggle/working')\n#Extract train masks/labels.\nwith zipfile.ZipFile(masks_zip_path,'r') as zip_ref:\n    zip_ref.extractall('/kaggle/working')\ndata_size = len(os.listdir('/kaggle/working/train_hq'))\nprint('Number of train images: ', len(os.listdir('/kaggle/working/train_hq')))\nprint('Number of train masks: ', len(os.listdir('/kaggle/working/train_masks')))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"scrolled":false},"cell_type":"code","source":"#Display ids for images and masks.\ncar_ids = sorted(os.listdir('/kaggle/working/train_hq'))\nmask_ids = sorted(os.listdir('/kaggle/working/train_masks'))\n#Generate some random index.\nrnd_ind = list(np.random.choice(data_size,8))\nfor i in rnd_ind:\n    print(\"Car image id: '{}' -- Corressponding Mask id '{}'\".format(car_ids[i], mask_ids[i]))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"scrolled":false},"cell_type":"code","source":"#Pick the 1553th car&mask ids from ids lists.\nn = 1553\ncar_id = car_ids[n]\nmask_id = mask_ids[n]\n#Load car&mask images using thier ids.\ncar = load_img('/kaggle/working/train_hq/' + car_id)\nmask = load_img('/kaggle/working/train_masks/' + mask_id)\nprint(\"Image Size: \", car.size)\nprint(\"Mask Size: \", mask.size)\n#Plot them.\nfig, ax = plt.subplots(1, 2, figsize=(20,20))\nfig.subplots_adjust(hspace=.1, wspace=.01)\nax[0].imshow(car)\nax[0].axis('off')\nax[0].title.set_text('Car Image')\nax[1].imshow(mask)\nax[1].axis('off')\nax[1].title.set_text('Car Mask')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"main_image = cv2.imread('/kaggle/working/train_hq/' + car_id)\nmain_image = load_img('/kaggle/working/train_hq/' + car_id)\nmain_image = np.asarray(main_image)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"main_image.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(main_image)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"mask_image = Image.open('/kaggle/working/train_masks/' + mask_id)\n#mask_image = load_img('/kaggle/working/train_masks/' + mask_id)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"mask_image = np.asarray(mask_image)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(mask_image)","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-output":true,"trusted":true},"cell_type":"code","source":"img_masked = cv2.bitwise_and(main_image, main_image, mask=mask_image)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(img_masked)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"scrolled":false},"cell_type":"code","source":"#Randomly split car&mask ids list to training and validation lists.\n#X is car image ids list, y is mask image ids list.\nX_train_ids, X_val_ids, y_train_ids, y_val_ids= train_test_split(car_ids, mask_ids,\n                                                                 test_size=.2, train_size=.8,\n                                                                 random_state=42)\nX_train_size = len(X_train_ids)\nX_val_size = len(X_val_ids)\nprint('Training images size: ', X_train_size)\nprint('Validation images size: ', X_val_size)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"scrolled":false},"cell_type":"code","source":"#Input size could be 128 or 256 or 512 or 1024.\ninput_size = [128, 128, 3]\ndef data_generator(images_path, masks_path, image_ids, mask_ids, batch_size, img_size=input_size):\n    '''\n    images_path/masks_path: Images/Masks folder directory.\n    images_ids/mask_ids: Ids for '.jpg' images/masks.\n    img_size: Generated imgs/masks size.\n    \n    returns: batch of randomly-selected car&mask images value-scaled (0 -> 1). \n    '''\n    data_size = len(image_ids)\n    while True:\n        #Choose random indice for later picking.\n        rnd_ind = np.random.choice(np.arange(data_size),batch_size)\n        imgs = []\n        masks = []\n        for i in rnd_ind:\n            #Pick a random id for car&mask images.\n            img_id, mask_id = image_ids[i], mask_ids[i]\n            #Load/resize images.\n            img = load_img(images_path + img_id, target_size=img_size) \n            mask = load_img(masks_path + mask_id, target_size=img_size[:-1], color_mode = 'grayscale')\n            #Add to the batch data.\n            imgs.append(img_to_array(img))\n            masks.append(img_to_array(mask).reshape(img_size[:-1] + [1]))\n        yield np.array(imgs, dtype=np.float16) / 255., np.array(masks, dtype=np.float16) / 255.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Try out the generator, generate data samples from the validation set.\ngen = data_generator('/kaggle/working/train_hq/', '/kaggle/working/train_masks/',\n                    X_val_ids, y_val_ids, batch_size=32)\n\nimgs, masks = next(gen)\nprint('Images batch shape: ', imgs.shape)\nprint('Masks batch shape: ', masks.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"scrolled":false},"cell_type":"code","source":"#Plot output samples of the generator.\nfig, ax = plt.subplots(2, 4, figsize=(15,7))\nfig.subplots_adjust(hspace=.1, wspace=.05)\ncar_samples, mask_samples = imgs[:4].astype(np.float32), masks[:4][:,:,:,0].astype(np.float32)\nfor i, (car, mask) in enumerate(zip(car_samples, mask_samples)):\n    ax[0, i].imshow(car)\n    ax[0, i].axis('off')\n    ax[0, i].title.set_text('Car Image')\n    \n    ax[1, i].imshow(mask, cmap='gray')\n    ax[1, i].axis('off')\n    ax[1, i].title.set_text('Car Mask')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"scrolled":false},"cell_type":"code","source":"def dice_coef(y_true, y_pred):\n    '''\n    Metric\n    '''\n    smooth = 1.\n    y_true_f = K.flatten(y_true)\n    y_pred_f = K.flatten(y_pred)\n    intersection = K.sum(y_true_f * y_pred_f)\n    score = (2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth)\n    return score\n\n\ndef dice_loss(y_true, y_pred):\n    '''\n    Loss function\n    '''\n    loss = 1 - dice_coef(y_true, y_pred)\n    return loss\n\n\ndef bce_dice_loss(y_true, y_pred):\n    '''\n    Mixed crossentropy and dice loss.\n    '''\n    loss = keras.losses.binary_crossentropy(y_true, y_pred) + dice_loss(y_true, y_pred)\n    return loss","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_unet_128(input_shape=(128, 128, 3),\n                 num_classes=1):\n    inputs = Input(shape=input_shape)\n    # 128\n\n    down1 = Conv2D(64, (3, 3), padding='same')(inputs)\n    down1 = BatchNormalization()(down1)\n    down1 = Activation('relu')(down1)\n    down1 = Conv2D(64, (3, 3), padding='same')(down1)\n    down1 = BatchNormalization()(down1)\n    down1 = Activation('relu')(down1)\n    down1_pool = MaxPooling2D((2, 2), strides=(2, 2))(down1)\n    # 64\n\n    down2 = Conv2D(128, (3, 3), padding='same')(down1_pool)\n    down2 = BatchNormalization()(down2)\n    down2 = Activation('relu')(down2)\n    down2 = Conv2D(128, (3, 3), padding='same')(down2)\n    down2 = BatchNormalization()(down2)\n    down2 = Activation('relu')(down2)\n    down2_pool = MaxPooling2D((2, 2), strides=(2, 2))(down2)\n    # 32\n\n    down3 = Conv2D(256, (3, 3), padding='same')(down2_pool)\n    down3 = BatchNormalization()(down3)\n    down3 = Activation('relu')(down3)\n    down3 = Conv2D(256, (3, 3), padding='same')(down3)\n    down3 = BatchNormalization()(down3)\n    down3 = Activation('relu')(down3)\n    down3_pool = MaxPooling2D((2, 2), strides=(2, 2))(down3)\n    # 16\n\n    down4 = Conv2D(512, (3, 3), padding='same')(down3_pool)\n    down4 = BatchNormalization()(down4)\n    down4 = Activation('relu')(down4)\n    down4 = Conv2D(512, (3, 3), padding='same')(down4)\n    down4 = BatchNormalization()(down4)\n    down4 = Activation('relu')(down4)\n    down4_pool = MaxPooling2D((2, 2), strides=(2, 2))(down4)\n    # 8\n\n    center = Conv2D(1024, (3, 3), padding='same')(down4_pool)\n    center = BatchNormalization()(center)\n    center = Activation('relu')(center)\n    center = Conv2D(1024, (3, 3), padding='same')(center)\n    center = BatchNormalization()(center)\n    center = Activation('relu')(center)\n    # center\n\n    up4 = UpSampling2D((2, 2))(center)\n    up4 = concatenate([down4, up4], axis=3)\n    up4 = Conv2D(512, (3, 3), padding='same')(up4)\n    up4 = BatchNormalization()(up4)\n    up4 = Activation('relu')(up4)\n    up4 = Conv2D(512, (3, 3), padding='same')(up4)\n    up4 = BatchNormalization()(up4)\n    up4 = Activation('relu')(up4)\n    up4 = Conv2D(512, (3, 3), padding='same')(up4)\n    up4 = BatchNormalization()(up4)\n    up4 = Activation('relu')(up4)\n    # 16\n\n    up3 = UpSampling2D((2, 2))(up4)\n    up3 = concatenate([down3, up3], axis=3)\n    up3 = Conv2D(256, (3, 3), padding='same')(up3)\n    up3 = BatchNormalization()(up3)\n    up3 = Activation('relu')(up3)\n    up3 = Conv2D(256, (3, 3), padding='same')(up3)\n    up3 = BatchNormalization()(up3)\n    up3 = Activation('relu')(up3)\n    up3 = Conv2D(256, (3, 3), padding='same')(up3)\n    up3 = BatchNormalization()(up3)\n    up3 = Activation('relu')(up3)\n    # 32\n\n    up2 = UpSampling2D((2, 2))(up3)\n    up2 = concatenate([down2, up2], axis=3)\n    up2 = Conv2D(128, (3, 3), padding='same')(up2)\n    up2 = BatchNormalization()(up2)\n    up2 = Activation('relu')(up2)\n    up2 = Conv2D(128, (3, 3), padding='same')(up2)\n    up2 = BatchNormalization()(up2)\n    up2 = Activation('relu')(up2)\n    up2 = Conv2D(128, (3, 3), padding='same')(up2)\n    up2 = BatchNormalization()(up2)\n    up2 = Activation('relu')(up2)\n    # 64\n\n    up1 = UpSampling2D((2, 2))(up2)\n    up1 = concatenate([down1, up1], axis=3)\n    up1 = Conv2D(64, (3, 3), padding='same')(up1)\n    up1 = BatchNormalization()(up1)\n    up1 = Activation('relu')(up1)\n    up1 = Conv2D(64, (3, 3), padding='same')(up1)\n    up1 = BatchNormalization()(up1)\n    up1 = Activation('relu')(up1)\n    up1 = Conv2D(64, (3, 3), padding='same')(up1)\n    up1 = BatchNormalization()(up1)\n    up1 = Activation('relu')(up1)\n    # 128\n\n    classify = Conv2D(num_classes, (1, 1), activation='sigmoid')(up1)\n\n    model = Model(inputs=inputs, outputs=classify)\n\n    model.compile(optimizer=RMSprop(lr=0.0001), loss=bce_dice_loss, metrics=[dice_coef])\n\n    return model\n\nuNet = get_unet_128()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"scrolled":false},"cell_type":"code","source":"#Prepare callbacks\nLR_callback = keras.callbacks.ReduceLROnPlateau(monitor='val_loss', patience=2, verbose=10, factor=.2, min_lr=.00001)\nEarlyStop_callback = keras.callbacks.EarlyStopping(monitor='val_loss',patience=10, restore_best_weights=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"scrolled":false},"cell_type":"code","source":"#Perpare data generators.\nbatch_size = 32\ntrain_gen = data_generator('/kaggle/working/train_hq/', '/kaggle/working/train_masks/',\n                           X_train_ids, y_train_ids, batch_size=batch_size)\nval_gen = data_generator('/kaggle/working/train_hq/', '/kaggle/working/train_masks/',\n                           X_val_ids, y_val_ids, batch_size=batch_size)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = uNet.fit_generator(train_gen, steps_per_epoch=int(X_train_size/batch_size),\n                             epochs=21, validation_data=val_gen,\n                             validation_steps=int(X_val_size/batch_size),\n                             callbacks=[LR_callback, EarlyStop_callback])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"uNet.save('unet_main1.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"uNet = tf.keras.models.load_model('../input/sir-unet/sir_unet.h5', custom_objects={'bce_dice_loss': bce_dice_loss, 'dice_coef':dice_coef})\n#load_model(modelPath, custom_objects={'mean_squared_abs_error': mean_squared_abs_error})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"scrolled":false},"cell_type":"code","source":"# Plot the loss and accuracy curves for training and validation\nfig, ax = plt.subplots(2,1, figsize=(15,7))\nax[0].plot(history.history['loss'], color='b', label=\"Training loss\")\nax[0].plot(history.history['val_loss'], color='r', label=\"validation loss\",axes =ax[0])\nlegend = ax[0].legend(loc='best', shadow=True)\n\nax[1].plot(history.history['dice_coef'], color='b', label=\"Training dice loss\")\nax[1].plot(history.history['val_dice_coef'], color='r',label=\"Validation dice loss\")\nlegend = ax[1].legend(loc='best', shadow=True)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"1. * Now let's try  to pridect masks for a batch of 32 images from the validation set.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"#Perdict some imgs.\npred_masks = uNet.predict(imgs)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, ax = plt.subplots(32, 3, figsize=(20,150))\nfig.subplots_adjust(hspace=.1, wspace=.05)\nfor i in range(32):\n    ax[i, 0].imshow(imgs[i].astype(np.float32))\n    ax[i, 0].axis('off')\n    ax[i, 0].title.set_text('Car')\n    \n    ax[i, 1].imshow(masks[i,:,:,0].astype(np.float32), cmap='gray')\n    ax[i, 1].axis('off')\n    ax[i, 1].title.set_text('Real Mask')\n    \n    ax[i, 2].imshow(pred_masks[i,:,:,0], cmap='gray')\n    ax[i, 2].axis('off')\n    ax[i, 2].title.set_text('Predicted Mask')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import shutil # for removing the directory\nshutil.rmtree('/kaggle/working/train_hq')\nshutil.rmtree('/kaggle/working/train_masks')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Prediction","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"input_image = imgs[0].astype('float32')\ninput_image = np.asarray(input_image)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(input_image)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(masks[0, :, :, 0].astype('float32'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred_mask_image = np.reshape(pred_masks[0], (128, 128))\npred_mask_image = pred_mask_image > 0.5\npred_mask_image = np.asarray(Image.fromarray(pred_mask_image, 'L'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(pred_mask_image)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred_masked_image = cv2.bitwise_and(input_image, input_image, mask=pred_mask_image)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(pred_masked_image)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Prediction","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"images = [cv2.imread(image) for image in glob.glob('../input/inputcar/input car/*.*')]\n#images = [cv2.imread(file) for file in glob.glob('path/to/files/*.jpg')]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"images2 = images.copy()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"images2[0].shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#size_images = [cv2.imread(image) for image in glob.glob('../input/inputcar/input car/*.*')]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#image = PIL.Image.open(\"../input/inputcar/input car/0010-000222-before.jpg\")\n#image to open\n\n#width, height = image.size","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"names = glob.glob('../input/inputcar/input car/*.*')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"names[0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"names[0].split('/')[-1].split('.')[0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len(images)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"images = []\nimg = load_img('../input/dataset/dataset/AgktOpMQ.jpeg', target_size=(128, 128))\nimages.append(img_to_array(img))\nimg = load_img('../input/dataset/dataset/aQzTDcFQ.jpeg', target_size=(128, 128))\nimages.append(img_to_array(img))\nimg = load_img('../input/dataset/dataset/eBbAEfLA.jpeg', target_size=(128, 128))\nimages.append(img_to_array(img))\nimg = load_img('../input/dataset/dataset/o-Oh9z6Q.jpeg', target_size=(128, 128))\nimages.append(img_to_array(img))\nimg = load_img('../input/dataset/dataset/p3S_zKbA.jpeg', target_size=(128, 128))\nimages.append(img_to_array(img))\nimages = np.array(images, dtype=np.float32) / 255.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for i in range(len(images)):\n    images[i] = cv2.resize(images[i], (128, 128))\n    #images[i] = images[i]/255.\n    #images[i] = np.asarray(images[i])\n    images[i] = np.array(images[i]) / 255.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"images = np.array(images)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"images.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred_masks = uNet.predict(images)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(pred_masks[0, :, :, 0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(images2[0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#pred_mask_image = np.reshape(pred_masks[0], (3200, 2400))\npred_mask_image = cv2.resize(pred_masks[0], (3200, 2400))\n\nmax_output_value = 100\nneighborhood_size = 50\nsubtract_from_mean = 2\n'''\nbinarized_images = [cv2.adaptiveThreshold(image, max_output_value,\n                                        cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\n                                        cv2.THRESH_BINARY,\n                                        neighborhood_size,\n                                        subtract_from_mean) for image in gray_images]\n'''\n# pred_mask_image = cv2.adaptiveThreshold(pred_mask_image, max_output_value, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, neighborhood_size, subtract_from_mean)\npred_mask_image = pred_mask_image > 0.5\npred_mask_image = np.asarray(Image.fromarray(pred_mask_image, 'L'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(pred_mask_image)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred_mask_image = cv2.adaptiveThreshold(pred_mask_image, max_output_value, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, neighborhood_size, subtract_from_mean)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"main_image = images2[0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(main_image)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred_masked_image = cv2.bitwise_and(main_image, main_image, mask=pred_mask_image)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(pred_masked_image)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred_masked_image = cv2.resize(pred_masked_image, (3200, 2400))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"matplotlib.pyplot.imsave('abc.jpeg', pred_masked_image)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for i in range(5, len(pred_masks)):\n    #pred_mask_image = np.reshape(pred_masks[i], (128, 128))\n    pred_mask_image = cv2.resize(pred_masks[i], (3200, 2400))\n    pred_mask_image = pred_mask_image > 0.5\n    pred_mask_image = np.asarray(Image.fromarray(pred_mask_image, 'L'))\n    \n    main_image = images2[i]\n    \n    pred_masked_image = cv2.bitwise_and(main_image, main_image, mask=pred_mask_image)\n    \n    pred_masked_image = cv2.resize(pred_masked_image, (3200, 2400))\n    \n    matplotlib.pyplot.imsave(names[i].split('/')[-1].split('.')[0] +'.jpeg', pred_masked_image)\n    print(i)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true},"cell_type":"code","source":"                                                '''\n                                                Thank You\n                                            \n                                                Regards,\n                                                Chirag Verma\n                                                '''","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","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}