{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":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)\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\n#for 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 20GB 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":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train=pd.read_csv('/kaggle/input/airbus-ship-detection/train_ship_segmentations_v2.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from skimage.io import imread,imshow","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(train['ImageId'][0])\nimg_sam=imread('/kaggle/input/airbus-ship-detection/train_v2/'+train['ImageId'][30])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\n%matplotlib inline\nplt.imshow(img_sam)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(len(train['EncodedPixels'][30]))\nprint(img_sam)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def 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  # Needed to align to RLE direction","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ImageId = '0005d01c8.jpg'\n\nimg = imread('../input/airbus-ship-detection/train_v2/' + ImageId)\nimg_masks = train.loc[train['ImageId'] == ImageId, 'EncodedPixels'].tolist()\nprint(len(img_masks))\n# Take the individual ship masks and create a single mask array for all ships\nall_masks = np.zeros((768, 768))\nfor mask in img_masks:\n    all_masks += rle_decode(mask)\n\nfig, axarr = plt.subplots(1, 3, figsize=(15, 40))\naxarr[0].axis('off')\naxarr[1].axis('off')\naxarr[2].axis('off')\naxarr[0].imshow(img)\naxarr[1].imshow(all_masks)\naxarr[2].imshow(img)\naxarr[2].imshow(all_masks, alpha=0.4)\nplt.tight_layout(h_pad=0.1, w_pad=0.1)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(img_masks[0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img=io.imread('/kaggle/input/airbus-ship-detection/train_v2/'+train['ImageId'][0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"io.imshow(img)\nio.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img1=io.imread('/kaggle/input/airbus-ship-detection/train_v2/'+train['ImageId'][30])\nio.imshow(img1)\nio.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(img_sam)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"resize_sample=imread('/kaggle/input/airbus-ship-detection/train_v2/'+'0270d7317.jpg')\nprint(resize_sample.shape)\nplt.imshow(resize_sample)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from skimage.transform import resize\nresized_sam=resize(resize_sample,(256,256,3))\nplt.subplot(121), imshow(resize_sample)\nplt.title('Original Image')\nplt.subplot(122), imshow(resized_sam)\nplt.title('Resized Image')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def display_image_in_actual_size(im_data,dpi):\n\n    height, width, depth = im_data.shape\n\n    # What size does the figure need to be in inches to fit the image?\n    figsize = width / float(dpi), height / float(dpi)\n\n    # Create a figure of the right size with one axes that takes up the full figure\n    fig = plt.figure(figsize=figsize)\n    ax = fig.add_axes([0, 0, 1, 1])\n\n    # Hide spines, ticks, etc.\n    ax.axis('on')\n\n    # Display the image.\n    ax.imshow(im_data)\n\n    plt.show()\n\ndisplay_image_in_actual_size(resized_sam,100)\ndisplay_image_in_actual_size(resize_sample,140)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from skimage.transform import rotate\n\nimage_rotated = rotate(resized_sam, angle=45, resize=False)\nimshow(image_rotated)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# example of horizontal shift image augmentation\nfrom numpy import expand_dims\nfrom keras.preprocessing.image import load_img\nfrom keras.preprocessing.image import img_to_array\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom matplotlib import pyplot\n# load the image\nimg = resize_sample\n# convert to numpy array\ndata = img_to_array(img)\n# expand dimension to one sample\nsamples = expand_dims(data, 0)\n# create image data augmentation generator\ndatagen = ImageDataGenerator(width_shift_range=0.1)\n# prepare iterator\nit = datagen.flow(samples, batch_size=1)\n# generate samples and plot\npyplot.figure(num=None, figsize=(7, 7), dpi=80, facecolor='w', edgecolor='k')\nfor i in range(4):\n    pyplot.subplot(220 + 1 + i)\n    batch = it.next()\n    image = batch[0].astype('uint8')\n    pyplot.imshow(image)\npyplot.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"datagen = ImageDataGenerator(height_shift_range=0.1)\n# prepare iterator\nit = datagen.flow(samples, batch_size=1)\n# generate samples and plot\npyplot.figure().patch.set_facecolor('green')\npyplot.figure(num=None, figsize=(7, 7), dpi=80, facecolor='w', edgecolor='k')\nfor i in range(4):\n    pyplot.subplot(220 + 1 + i)\n    batch = it.next()\n    image = batch[0].astype('uint8')\n    pyplot.imshow(image)\npyplot.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"datagen = ImageDataGenerator(horizontal_flip=True)\n# prepare iterator\nit = datagen.flow(samples, batch_size=1)\n# generate samples and plot\npyplot.figure(num=None, figsize=(7, 7), dpi=80, facecolor='w', edgecolor='k')\nfor i in range(4):\n    pyplot.subplot(220 + 1 + i)\n    batch = it.next()\n    image = batch[0].astype('uint8')\n    pyplot.imshow(image)\npyplot.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"datagen = ImageDataGenerator(zoom_range=[0.9,1.25])\n# prepare iterator\nit = datagen.flow(samples, batch_size=1)\n# generate samples and plot\npyplot.figure(num=None, figsize=(7, 7), dpi=80, facecolor='w', edgecolor='k')\nfor i in range(4):\n    pyplot.subplot(220 + 1 + i)\n    batch = it.next()\n    image = batch[0].astype('uint8')\n    pyplot.imshow(image)\npyplot.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"datagen = ImageDataGenerator(shear_range=60)\n# prepare iterator\nit = datagen.flow(samples, batch_size=1)\n# generate samples and plot\npyplot.figure(num=None, figsize=(7, 7), dpi=80, facecolor='w', edgecolor='k')\nfor i in range(4):\n    pyplot.subplot(220 + 1 + i)\n    batch = it.next()\n    image = batch[0].astype('uint8')\n    pyplot.imshow(image)\npyplot.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"datagen = ImageDataGenerator(rotation_range=45)\n# prepare iterator\nit = datagen.flow(samples, batch_size=1)\n# generate samples and plot\npyplot.figure(num=None, figsize=(7, 7), dpi=80, facecolor='w', edgecolor='k')\nfor i in range(4):\n    pyplot.subplot(220 + 1 + i)\n    batch = it.next()\n    image = batch[0].astype('uint8')\n    pyplot.imshow(image)\npyplot.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"datagen = ImageDataGenerator(brightness_range=[0.5,1.5])\n# prepare iterator\nit = datagen.flow(samples, batch_size=1)\n# generate samples and plot\npyplot.figure(num=None, figsize=(7, 7), dpi=80, facecolor='w', edgecolor='k')\nfor i in range(4):\n    pyplot.subplot(220 + 1 + i)\n    batch = it.next()\n    image = batch[0].astype('uint8')\n    pyplot.imshow(image)\npyplot.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"datagen = ImageDataGenerator(vertical_flip=True)\n# prepare iterator\nit = datagen.flow(samples, batch_size=1)\n# generate samples and plot\npyplot.figure(num=None, figsize=(7, 7), dpi=80, facecolor='w', edgecolor='k')\nfor i in range(4):\n    pyplot.subplot(220 + 1 + i)\n    batch = it.next()\n    image = batch[0].astype('uint8')\n    pyplot.imshow(image)\npyplot.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf\ninput_layer = tf.keras.layers.Input(shape=(256,256,3))\ngaus        = tf.keras.layers.GaussianNoise(0.1,name='output')(input_layer)\nmodel       = tf.keras.models.Model(inputs=input_layer, outputs=gaus)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_layer_outputs(model,layer_name,input_data,train_mode=False):\n    outs_tensor   = [layer.output for layer in model.layers if layer_name == layer.name]\n    outs_function = K.function([model.input, K.learning_phase()], outs_tensor)\n    return [outs_function([input_data,int(train_mode)])][0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"result=model(resized_sam,training=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(num=None, figsize=(7, 7), dpi=80)\nplt.subplot(121)\nplt.imshow(resized_sam)\nplt.subplot(122)\nplt.imshow(result)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from skimage.color import rgb2gray\nplt.hist(rgb2gray(resized_sam*255))\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.hist(rgb2gray(result*255))\nplt.show()","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}