{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"_kg_hide-input":true,"_kg_hide-output":true},"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)\nimport json\nimport tensorflow as tf\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\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"In this notebook I implemted Image Augmentation technqiue by which we can use 100 percent of real Time data for classification. And Use Mobile Net model for Training. Later I will try to make same technique for object detection data. ","execution_count":null},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"base_path = \"/kaggle/input/global-wheat-detection/train/\"\ndf = pd.read_csv(\"/kaggle/input/global-wheat-detection/train.csv\")\nprint(\"Total Unique Images\", len(set(df[\"image_id\"].values)))\ndf.head()\nprint(\"Unique Sources {}\".format(len(set(df[\"source\"].values))))\nprint(\"Unique Sources {}\".format((set(df[\"source\"].values))))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Merging Boudning box of all unique Images**","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"\nunique_df={key: [] for key in (set(df[\"image_id\"].values))}\nfor i in range(len(df)):\n    unique_df[df[\"image_id\"].iloc[i]].append(json.loads(df[\"bbox\"].iloc[i]))\nunique_df = pd.DataFrame(zip(list(unique_df.keys()),list(unique_df.values())), columns=['image_id', 'bbox'])\nunique_df = pd.merge(unique_df, df, on='image_id').drop([\"bbox_y\"],axis=1).drop_duplicates(subset=[\"image_id\"],keep=\"first\", inplace=False)\nunique_df.rename(columns={'bbox_x': 'bbox'}, inplace=True)\nprint(\"Unique Dataframe Length {}\".format(len(unique_df)))\nunique_df.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Classification","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"\nImages_from_source = unique_df.groupby('source').count()[\"image_id\"]\nprint(Images_from_source)\nprint(\"Total Records\",len(unique_df))\nprint(\"Cross Checking \",sum(list(Images_from_source)))\n \n    #176 Minimum samples\n\n\n                            ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Image Augmentation For Classification Problem\n\nI think If we can do Image Augmentation like this we can use our 100% of real data.\n\nI am using Image of 1024 * 1024 Diminsion\n\n1. Take Image as it is and resize it to the Dimision you want.     (1024 * 1024 ---- > 256 * 256)\n2. Slice image from different portions and resize them to the specefic diminsion  (1024 * 1024 ---- > Slice (512 * 512)) -----> (256 * 256)\n3. Repeat this step according to the number of images you want.\n![Untitled%20Diagram%20%281%29.jpg](attachment:Untitled%20Diagram%20%281%29.jpg)","attachments":{"Untitled%20Diagram%20%281%29.jpg":{"image/jpeg":"/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/2wBDAQMDAwQDBAgEBAgQCwkLEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBD/wAARCAF9Af8DASIAAhEBAxEB/8QAHQABAQEBAAIDAQAAAAAAAAAAAAcICQMGAgQFAf/EAEMQAQAAAwQCEQ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QqrkBSfZlP+F9LMm0z1cf6n+0sv4dgX6393/R/VfpbtLk/V+n+ii3G6+nutzuotrb2tu3a23te/ndF3xt8AHVQcq9/O6Lvjb4Bv53Rd8bfAB1UHKvfzui742+Ab+d0XfG3wAdVByr387ou+NvgG/ndF3xt8AHVQcq9/O6Lvjb4Bv53Rd8bfAB1UHKvfzui742+Ab+d0XfG3wAdVByr387ou+NvgG/ndF3xt8AHVQcq9/O6Lvjb4Bv53Rd8bfAB1UHKvfzui742+Ab+d0XfG3wAdVByr387ou+NvgG/ndF3xt8AHVQcq9/O6Lvjb4Bv53Rd8bfAB1UHKvfzui742+Ab+d0XfG3wAdVByr387ou+NvgG/ndF3xt8AHVQcq9/O6Lvjb4Bv53Rd8bfAB1UHKvfzui742+Ab+d0XfG3wAdVEqo3wi126wLn+K4CwBv53Rd8bfAeqZN2ZT9pZjz3j+rj+r/AHrmCTjv0f3f9P8ASfTwq4XD6W6/RW/U2/0H1N1tQ/8Ad3O1/buog6/jlXv53Rd8bfAN/O6Lvjb4AOqg5V7+d0XfG3wDfzui742+ADqoOVe/ndF3xt8A387ou+NvgA6qDlXv53Rd8bfAN/O6Lvjb4AOqg5V7+d0XfG3wDfzui742+ADqoOVe/ndF3xt8A387ou+NvgA6qDlXv53Rd8bfAN/O6Lvjb4AOqg5V7+d0XfG3wDfzui742+ADqoOVe/ndF3xt8A387ou+NvgA6qDlXv53Rd8bfAN/O6Lvjb4AOqg5V7+d0XfG3wDfzui742+ADqoOVe/ndF3xt8A387ou+NvgA6qDlXv53Rd8bfAN/O6Lvjb4AOqg5V7+d0XfG3wDfzui742+ADqoOVe/ndF3xt8A387ou+NvgA6qMq7KPxE6m/ZfOLkyrv53Rd8bfASrSj2VvWUoTmain/AX9ufuP9F/6n+6f1n0P098kXn/ALP6SXut19Dc/wCuza3W3/O1tWh//9k="}},"execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"\nimport os\nimport matplotlib.pyplot as plt\nfrom PIL import Image, ImageDraw \nimport json\nimport matplotlib.pyplot as plt\n\nclass augmentation:\n    def imgcrop(self, im, label ,xPieces, yPieces, diminsion=(256,256)):\n        sliced_images=[]\n        labels=[]\n        file_extension = \"jpg\"\n        imgwidth, imgheight = im.size\n        height = imgheight // yPieces\n        width = imgwidth // xPieces\n        for i in range(0, yPieces):\n            for j in range(0, xPieces):\n                box = (j * width, i * height, (j + 1) * width, (i + 1) * height)\n                croped_image = im.crop(box).resize(diminsion) \n                \n                try:\n                    sliced_images.append(np.asarray(croped_image))\n                    labels.append(label)\n                except:\n                    pass\n        return sliced_images , labels\n    \n    def run(self, images, labels):\n        while(True):\n            for index,image_id in enumerate(images):\n                __sliced_images = []\n                __summed_labels = []\n                image, label = Image.fromarray(plt.imread(base_path + image_id + \".jpg\")), labels[index]\n\n                for i in range(1,5):\n                    augmented_images, augmented_labels = self.imgcrop(image,label,i, i)\n                    __sliced_images.extend(augmented_images)\n                    __summed_labels.extend(augmented_labels)\n                yield np.asarray(__sliced_images), np.asarray(__summed_labels)\n\ngenerator=augmentation().run([unique_df[\"image_id\"].iloc[1], unique_df[\"image_id\"].iloc[16]], [unique_df[\"source\"].iloc[1],unique_df[\"source\"].iloc[16]])\n\ncounter = 0\nfor i in generator:\n    \n    _sliced_images, _labels = i              \n    print(\"Total Images formed {} and Labels formed {}\".format(len(_sliced_images), len(_labels)))\n    for index,k in enumerate(_sliced_images):\n        plt.title(_labels[index])\n        plt.imshow(k)\n        plt.show()\n        counter = counter + 1\n    \n    if counter > 3:break\n        \n    \n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Using MobilenetV2 ","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"MobileNet v2 models for Keras.\n# Reference\n- [Inverted Residuals and Linear Bottlenecks Mobile Networks for\n   Classification, Detection and Segmentation]\n   (https://arxiv.org/abs/1801.04381)\n\"\"\"\n\n\nfrom keras.models import Model\nfrom keras.layers import Input, Conv2D, GlobalAveragePooling2D, Dropout\nfrom keras.layers import Activation, BatchNormalization, Add, Reshape, DepthwiseConv2D\nfrom keras.utils.vis_utils import plot_model\n\nfrom keras import backend as K\n\n\ndef _make_divisible(v, divisor, min_value=None):\n    if min_value is None:\n        min_value = divisor\n    new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)\n    # Make sure that round down does not go down by more than 10%.\n    if new_v < 0.9 * v:\n        new_v += divisor\n    return new_v\n\n\ndef relu6(x):\n    \"\"\"Relu 6\n    \"\"\"\n    return K.relu(x, max_value=6.0)\n\n\ndef _conv_block(inputs, filters, kernel, strides):\n    \"\"\"Convolution Block\n    This function defines a 2D convolution operation with BN and relu6.\n    # Arguments\n        inputs: Tensor, input tensor of conv layer.\n        filters: Integer, the dimensionality of the output space.\n        kernel: An integer or tuple/list of 2 integers, specifying the\n            width and height of the 2D convolution window.\n        strides: An integer or tuple/list of 2 integers,\n            specifying the strides of the convolution along the width and height.\n            Can be a single integer to specify the same value for\n            all spatial dimensions.\n    # Returns\n        Output tensor.\n    \"\"\"\n\n    channel_axis = 1 if K.image_data_format() == 'channels_first' else -1\n\n    x = Conv2D(filters, kernel, padding='same', strides=strides)(inputs)\n    x = BatchNormalization(axis=channel_axis)(x)\n    return Activation(relu6)(x)\n\n\ndef _bottleneck(inputs, filters, kernel, t, alpha, s, r=False):\n    \"\"\"Bottleneck\n    This function defines a basic bottleneck structure.\n    # Arguments\n        inputs: Tensor, input tensor of conv layer.\n        filters: Integer, the dimensionality of the output space.\n        kernel: An integer or tuple/list of 2 integers, specifying the\n            width and height of the 2D convolution window.\n        t: Integer, expansion factor.\n            t is always applied to the input size.\n        s: An integer or tuple/list of 2 integers,specifying the strides\n            of the convolution along the width and height.Can be a single\n            integer to specify the same value for all spatial dimensions.\n        alpha: Integer, width multiplier.\n        r: Boolean, Whether to use the residuals.\n    # Returns\n        Output tensor.\n    \"\"\"\n\n    channel_axis = 1 if K.image_data_format() == 'channels_first' else -1\n    # Depth\n    tchannel = K.int_shape(inputs)[channel_axis] * t\n    # Width\n    cchannel = int(filters * alpha)\n\n    x = _conv_block(inputs, tchannel, (1, 1), (1, 1))\n\n    x = DepthwiseConv2D(kernel, strides=(s, s), depth_multiplier=1, padding='same')(x)\n    x = BatchNormalization(axis=channel_axis)(x)\n    x = Activation(relu6)(x)\n\n    x = Conv2D(cchannel, (1, 1), strides=(1, 1), padding='same')(x)\n    x = BatchNormalization(axis=channel_axis)(x)\n\n    if r:\n        x = Add()([x, inputs])\n\n    return x\n\n\ndef _inverted_residual_block(inputs, filters, kernel, t, alpha, strides, n):\n    \"\"\"Inverted Residual Block\n    This function defines a sequence of 1 or more identical layers.\n    # Arguments\n        inputs: Tensor, input tensor of conv layer.\n        filters: Integer, the dimensionality of the output space.\n        kernel: An integer or tuple/list of 2 integers, specifying the\n            width and height of the 2D convolution window.\n        t: Integer, expansion factor.\n            t is always applied to the input size.\n        alpha: Integer, width multiplier.\n        s: An integer or tuple/list of 2 integers,specifying the strides\n            of the convolution along the width and height.Can be a single\n            integer to specify the same value for all spatial dimensions.\n        n: Integer, layer repeat times.\n    # Returns\n        Output tensor.\n    \"\"\"\n\n    x = _bottleneck(inputs, filters, kernel, t, alpha, strides)\n\n    for i in range(1, n):\n        x = _bottleneck(x, filters, kernel, t, alpha, 1, True)\n\n    return x\n\n\ndef MobileNetv2(input_shape, k, alpha=1.0):\n    \"\"\"MobileNetv2\n    This function defines a MobileNetv2 architectures.\n    # Arguments\n        input_shape: An integer or tuple/list of 3 integers, shape\n            of input tensor.\n        k: Integer, number of classes.\n        alpha: Integer, width multiplier, better in [0.35, 0.50, 0.75, 1.0, 1.3, 1.4].\n    # Returns\n        MobileNetv2 model.\n    \"\"\"\n    inputs = Input(shape=input_shape)\n\n    first_filters = _make_divisible(32 * alpha, 8)\n    x = _conv_block(inputs, first_filters, (3, 3), strides=(2, 2))\n\n    x = _inverted_residual_block(x, 16, (3, 3), t=1, alpha=alpha, strides=1, n=1)\n    x = _inverted_residual_block(x, 24, (3, 3), t=6, alpha=alpha, strides=2, n=2)\n    x = _inverted_residual_block(x, 32, (3, 3), t=6, alpha=alpha, strides=2, n=3)\n    x = _inverted_residual_block(x, 64, (3, 3), t=6, alpha=alpha, strides=2, n=4)\n    x = _inverted_residual_block(x, 96, (3, 3), t=6, alpha=alpha, strides=1, n=3)\n    x = _inverted_residual_block(x, 160, (3, 3), t=6, alpha=alpha, strides=2, n=3)\n    x = _inverted_residual_block(x, 320, (3, 3), t=6, alpha=alpha, strides=1, n=1)\n\n    if alpha > 1.0:\n        last_filters = _make_divisible(1280 * alpha, 8)\n    else:\n        last_filters = 1280\n\n    x = _conv_block(x, last_filters, (1, 1), strides=(1, 1))\n    x = GlobalAveragePooling2D()(x)\n    x = Reshape((1, 1, last_filters))(x)\n    x = Dropout(0.3, name='Dropout')(x)\n    x = Conv2D(k, (1, 1), padding='same')(x)\n\n    x = Activation('softmax', name='softmax')(x)\n    output = Reshape((k,))(x)\n\n    model = Model(inputs, output)\n    # plot_model(model, to_file='images/MobileNetv2.png', show_shapes=True)\n    model.compile(optimizer='adam', loss=tf.keras.losses.CategoricalCrossentropy())\n    return model\n\n\n\nmodel = MobileNetv2((256,256, 3), 7, 1.0)\nprint(model.summary())\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.utils import to_categorical\n   \nimages=list(unique_df[\"image_id\"].values)\nlabels=list(unique_df[\"source\"].values)\n\n# Converting string to integer \nunique_labels = list(set(unique_df[\"source\"].values))\nlabels_dict={i:unique_labels.index(i) for i in unique_labels}\nlabels=[labels_dict[label] for label in  labels]\nlabel_df = pd.DataFrame(zip(list(labels_dict.keys()),list(labels_dict.values())), columns=['Label', 'Value'])\nprint(label_df)\nlabel_df.to_csv(\"Label_dict.csv\")\n\n# Converting to Categorical Labels\nlabels = to_categorical(labels, num_classes=len(set(unique_df[\"source\"].values)))\n\n# test train Split \n\nTrain_range=int(len(images)*0.7)\n\ntrain_images_list=images[:Train_range]\ntrain_labels_list=labels[:Train_range]\nval_images_list=images[Train_range:]\nval_labels_list=labels[Train_range:]\n\n\nprint(\"Train Images List\" ,len(train_images_list))\nprint(\"train_labels_list\" ,len(train_labels_list))\nprint(\"Val Images list\" ,len(val_images_list))\nprint(\"Val Labels list\" ,len(val_labels_list))","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-output":true,"trusted":true},"cell_type":"code","source":"from keras.callbacks import ModelCheckpoint, LearningRateScheduler\nweights_path='/kaggle/working/MobileNet_{epoch}_{loss}.h5'\ntrain = augmentation().run(train_images_list, train_labels_list)\nvalidation = augmentation().run(val_images_list, val_labels_list)\n\nmodel.fit_generator( train,\n    steps_per_epoch=300,\n    epochs = 30,\n    callbacks = [\n                 ModelCheckpoint(weights_path,save_best_only=True,save_weights_only=True)\n    ],\n     validation_data=validation,\n    validation_steps=200)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import random\nindex = random.choice([i for i in range(len(next(validation)[0]))])\nimage = np.expand_dims(next(validation)[0][index],axis=0)\nlabel = list(labels_dict.keys())[list(labels_dict.values()).index(next(validation)[1][index].argmax())]\n\nprediction = model.predict(image)\npredicted_label = list(labels_dict.keys())[list(labels_dict.values()).index(prediction.argmax())]\n\nplt.title(\"GT: {}   Actual: {}\".format(predicted_label,label))\nplt.imshow(next(validation)[0][index])\nplt.show()\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Sematic Segmentation by Unet\n\nWill proceed this later","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"\nfor i in range(len(unique_df)):\n    image = Image.open(base_path + unique_df[\"image_id\"].iloc[i] + \".jpg\")\n    w, h = image.size\n    bounding_box = unique_df[\"bbox\"].iloc[i]\n    \n    for bbox in bounding_box:\n        x,y,w,h=bbox\n        shape = [x,y,x+w,y+h]\n        img1 = ImageDraw.Draw(image)   \n        img1.rectangle(shape,  outline =\"white\", width=5) \n    \n    plt.title(unique_df[\"image_id\"].iloc[i]+ \" \" + unique_df[\"source\"].iloc[i])\n    plt.imshow(np.asarray(image))\n    plt.show()\n    \n    if i ==15:break\n    \n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Unet","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np \nimport os\nimport skimage.io as io\nimport skimage.transform as trans\nimport numpy as np\nfrom keras.models import *\nfrom keras.layers import *\nfrom keras.optimizers import *\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras import backend as keras\nimport keras.backend as K\nsmooth = 1\ndef dice_coef(y_true, y_pred):\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    return (2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth)   \n\ndef dice_coef_loss(y_true,y_pred):\n    return 1-dice_coef(y_true,y_pred)\n\ndef unet(pretrained_weights = None,input_size = (256,256,1)):\n    inputs = Input(input_size)\n    conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(inputs)\n    conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv1)\n    pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)\n    conv2 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool1)\n    conv2 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv2)\n    pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)\n    conv3 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool2)\n    conv3 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv3)\n    pool3 = MaxPooling2D(pool_size=(2, 2))(conv3)\n    conv4 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool3)\n    conv4 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv4)\n    drop4 = Dropout(0.5)(conv4)\n    pool4 = MaxPooling2D(pool_size=(2, 2))(drop4)\n\n    conv5 = Conv2D(1024, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool4)\n    conv5 = Conv2D(1024, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv5)\n    drop5 = Dropout(0.5)(conv5)\n\n    up6 = Conv2D(512, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(drop5))\n    merge6 = concatenate([drop4,up6], axis = 3)\n    conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge6)\n    conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv6)\n\n    up7 = Conv2D(256, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv6))\n    merge7 = concatenate([conv3,up7], axis = 3)\n    conv7 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge7)\n    conv7 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv7)\n\n    up8 = Conv2D(128, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv7))\n    merge8 = concatenate([conv2,up8], axis = 3)\n    conv8 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge8)\n    conv8 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv8)\n\n    up9 = Conv2D(64, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv8))\n    merge9 = concatenate([conv1,up9], axis = 3)\n    conv9 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge9)\n    conv9 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv9)\n    conv9 = Conv2D(2, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv9)\n    conv10 = Conv2D(1, 1, activation = 'sigmoid')(conv9)\n\n    model = Model(input = inputs, output = conv10)\n\n    model.compile(optimizer = Adam(lr = 1e-4), loss = dice_coef_loss, metrics = [dice_coef])\n    \n    #model.summary()\n\n    if(pretrained_weights):\n    \tmodel.load_weights(pretrained_weights)\n\n    return model","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Image Augmentation**\n\nUsing Rotation for Object Detection Image Augmentation","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import skimage\nimport os\nimport cv2\nimport numpy as np\nimport math\nfrom contextlib import suppress\nimport matplotlib.pyplot as plt\n\n\ndef MakeMask(bounding_box,width,height,image=[],debug=False):\n    \n    if not debug:\n        image =  Image.new(\"RGB\", (height,width)).convert('L')\n        \n        for bbox in bounding_box:\n            x,y,w,h=bbox\n            shape = [x,y,x+w,y+h]\n            img1 = ImageDraw.Draw(image)   \n            img1.rectangle(shape,  fill =\"wheat\")\n    else:\n        image=Image.fromarray(image)\n        for bbox in bounding_box:\n            x,y,w,h=bbox\n            shape = [x,y,x+w,y+h]\n            img1 = ImageDraw.Draw(image)   \n            img1.rectangle(shape, outline =\"wheat\",width=10) \n    return np.asarray(image)\n\n\ndef adjustData(img,mask):\n    img = img / 255\n    mask = mask /255\n    mask[mask > 0.5] = 1\n    mask[mask <= 0.5] = 0\n    return (img,mask)\n\ndef rotation(image,angelInDegrees):\n    h,w = image.shape[:2]\n    img_c = (w/2 , h/2)\n    rot =cv2.getRotationMatrix2D(img_c, angelInDegrees,1)\n    rad = math.radians(angelInDegrees)\n    sin = math.sin(rad)\n    cos = math.cos(rad)\n    b_w= int((h * abs(sin))+ (w * abs(cos)))\n    b_h = int((h*abs(cos)) + (w * abs(sin)))\n    rot[0,2] += ((b_w / 2) - img_c[0])\n    rot[1,2] += ((b_h /2) - (img_c[1]))\n    outImg = cv2.warpAffine(image,rot,(b_w,b_h),flags= cv2.INTER_LINEAR)\n    return outImg\n\n\n\n\ndef read_images(image_path, label,debug = False):\n    image,mask,e=None,None,''\n    \n    if debug:\n        with suppress(Exception) : image= cv2.imread(image_path)\n        width,height,_ = image.shape\n        mask = MakeMask(label,width,height,image=image,debug=debug)\n        \n    else:\n        with suppress(Exception) : image= cv2.imread(image_path,0)\n        width,height = image.shape\n        mask = MakeMask(label,width,height,image=image,debug=debug)\n        \n    return image,mask\n\ndef ImageGenerator(images,labels,rotation_angel,resize_diminsion,batch_size,debug=False):\n    image_list, label_list = [],[]\n    while True:\n        for index,image in enumerate(images):\n            try:\n                image,label=read_images(os.path.join(image),labels[index],debug)\n                \n                for count,angel in enumerate(range(0,360,rotation_angel)):\n                    rot_label = cv2.resize(rotation(label,angel),resize_diminsion,interpolation = cv2.INTER_AREA)\n                    rot_image = cv2.resize(rotation(image,angel),resize_diminsion,interpolation = cv2.INTER_AREA)\n                    if not debug:\n                        rot_image,rot_label = adjustData(rot_image,rot_label)\n                    image_list.append(rot_image)\n                    label_list.append(rot_label)\n                    \n                    if count % batch_size == 0 and count >= batch_size:\n                        yield np.expand_dims(np.asarray(image_list),axis=3),np.expand_dims(np.asarray(label_list),axis=3)\n                        image_list,label_list =[],[]\n            except Exception as e:\n                print(e)\n            pass\n\ndef augment(images_path,label,rotation_angel=10,resize_diminsion=(256,256),batch_size=8,debug=False):\n    percentage_of_training_data=0.7\n    no_of_images=len(images_path)\n    augment.TOTAL_TRAINING_IMAGES = (360 /rotation_angel) * no_of_images\n    \n    training_images = int(no_of_images * percentage_of_training_data)\n    training_gen = ImageGenerator(images_path[0:training_images],label[0:training_images],rotation_angel,resize_diminsion,batch_size,debug)\n    validation_gen = ImageGenerator(images_path[training_images:],label[training_images:],rotation_angel,resize_diminsion,batch_size,debug)\n    return training_gen,validation_gen\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import random\nimages=[base_path+i+\".jpg\" for i in list(unique_df[\"image_id\"].values)]\nlabels=list(unique_df[\"bbox\"].values)\n\ntrain,val=augment(images,labels,debug=False)\nimage,label=next(val)\nindex=random.choice([i-1 for i in range(image.shape[0])])\nplt.title(\"Image\")\nplt.imshow(image[index].squeeze())\nplt.show()\nplt.title(\"Mask\")\nplt.imshow(label[index].squeeze())\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# To be Continued","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# weights_path='/kaggle/working/Unet_{epoch}_{dice_coef}_{loss}.h5'\n# model=unet(input_size=(256,256,1))\n# model.fit_generator(\n#     train,\n#     steps_per_epoch=100,\n#     epochs = 1000,\n#     callbacks = [\n#                  ModelCheckpoint(weights_path,save_best_only=True,save_weights_only=True)\n#     ],\n#      validation_data=val,\n#     validation_steps=10)","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}