{"cells": [{"cell_type": "markdown", "metadata": {"_cell_guid": "1b0f9bdc-bc5f-4e37-8a73-d9071860bd04", "_uuid": "59f8d5c27cd8c1e9d02cef4f83fdb5c905cd53fe"}, "source": ["This kernel is essentially copy-paste from another kerenl:\n", "[https://www.kaggle.com/bguberfain/elastic-transform-for-data-augmentation](http://)\n", "written by Bruno G. do Amaral. I'm relatively new to Kaggle system, so if there is a way to fork kernel from different competition, please let me know.\n", "\n", "It demonstrate the use of elastic_transform as suggested by the authors of the original U-Net article as a mean for data augmentation :\n", "[https://arxiv.org/abs/1505.04597](http://)\n", "\n", "Note that the current implementation support only gray-scale images. Some work need to be done in order to use it for color images.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "outputs": [], "source": ["import numpy as np # linear algebra\n", "import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n", "import skimage.io\n", "from skimage import color\n", "from skimage import io\n", "import glob\n", "import cv2\n", "from scipy.ndimage.interpolation import map_coordinates\n", "from scipy.ndimage.filters import gaussian_filter\n", "import matplotlib.pyplot as plt"], "metadata": {"_cell_guid": "2c72f1e8-8279-43c1-80b0-f2d13277366d", "_uuid": "93654d545c8df7a545494d75f1e4fd3be6a48b38", "collapsed": true}}, {"cell_type": "code", "execution_count": null, "outputs": [], "source": ["image_id = \"0d3640c1f1b80f24e94cc9a5f3e1d9e8db7bf6af7d4aba920265f46cadc25e37\"\n", "image_dir = \"../input/stage1_train/{image_id}/masks/\".format(image_id=image_id)\n", "image_sb20182 = skimage.io.imread(\"../input/stage1_train/{image_id}/images/{image_id}.png\".format(image_id=image_id),as_gray=True)\n", "image_sb2018= color.rgb2gray(image_sb20182)\n"], "metadata": {"_cell_guid": "1f41ba31-64dd-430e-a7c0-e76b6827eded", "_uuid": "c01497cbc5dc239c5ad3f3537a05476e487db73f", "collapsed": true}}, {"cell_type": "code", "execution_count": null, "outputs": [], "source": ["all_masks_files = glob.glob(image_dir+\"*.png\")\n", "final_mask = []\n", "for item in all_masks_files:\n", "    image_sb2018_mask = cv2.imread(item,-1)\n", "    final_mask.append(image_sb2018_mask)\n", "image_sb2018_mask= np.max(final_mask,axis=0) \n", "image_sb2018_mask = image_sb2018_mask/np.max(image_sb2018_mask)\n", "plt.imshow(image_sb2018_mask)"], "metadata": {"_cell_guid": "2e78cfad-70a2-4800-ad76-f9e87b8847d4", "_uuid": "fb4d3d71477f6ed20167901a7ec3ccfeb23deb71"}}, {"cell_type": "code", "execution_count": null, "outputs": [], "source": ["#taken from: https://www.kaggle.com/bguberfain/elastic-transform-for-data-augmentation\n", "# Function to distort image\n", "def elastic_transform(image, alpha, sigma, alpha_affine, random_state=None):\n", "    \"\"\"Elastic deformation of images as described in [Simard2003]_ (with modifications).\n", "    .. [Simard2003] Simard, Steinkraus and Platt, \"Best Practices for\n", "         Convolutional Neural Networks applied to Visual Document Analysis\", in\n", "         Proc. of the International Conference on Document Analysis and\n", "         Recognition, 2003.\n", "\n", "     Based on https://gist.github.com/erniejunior/601cdf56d2b424757de5\n", "    \"\"\"\n", "    if random_state is None:\n", "        random_state = np.random.RandomState(None)\n", "\n", "    shape = image.shape\n", "    shape_size = shape[:2]\n", "    \n", "    # Random affine\n", "    center_square = np.float32(shape_size) // 2\n", "    square_size = min(shape_size) // 3\n", "    pts1 = np.float32([center_square + square_size, [center_square[0]+square_size, center_square[1]-square_size], center_square - square_size])\n", "    pts2 = pts1 + random_state.uniform(-alpha_affine, alpha_affine, size=pts1.shape).astype(np.float32)\n", "    M = cv2.getAffineTransform(pts1, pts2)\n", "    image = cv2.warpAffine(image, M, shape_size[::-1], borderMode=cv2.BORDER_REFLECT_101)\n", "\n", "    dx = gaussian_filter((random_state.rand(*shape) * 2 - 1), sigma) * alpha\n", "    dy = gaussian_filter((random_state.rand(*shape) * 2 - 1), sigma) * alpha\n", "    dz = np.zeros_like(dx)\n", "\n", "    x, y, z = np.meshgrid(np.arange(shape[1]), np.arange(shape[0]), np.arange(shape[2]))\n", "    indices = np.reshape(y+dy, (-1, 1)), np.reshape(x+dx, (-1, 1)), np.reshape(z, (-1, 1))\n", "\n", "    return map_coordinates(image, indices, order=1, mode='reflect').reshape(shape)"], "metadata": {"_cell_guid": "42538fd6-50a6-464c-a7e8-a6ac47598c8f", "_uuid": "b09eab95fdc5046d2f90e209edbdc6ebb8641b7c", "collapsed": true}}, {"cell_type": "code", "execution_count": null, "outputs": [], "source": ["# Define function to draw a grid\n", "def draw_grid(im, grid_size):\n", "    # Draw grid lines\n", "    for i in range(0, im.shape[1], grid_size):\n", "        cv2.line(im, (i, 0), (i, im.shape[0]), color=(1,))\n", "    for j in range(0, im.shape[0], grid_size):\n", "        cv2.line(im, (0, j), (im.shape[1], j), color=(1,))\n", "\n", "# Load images\n", "im = image_sb2018\n", "im_mask = image_sb2018_mask\n", "\n", "# Draw grid lines\n", "draw_grid(im, 50)\n", "draw_grid(im_mask, 50)\n", "\n", "# Merge images into separete channels (shape will be (cols, rols, 2))\n", "im_merge = np.concatenate((im[...,None], im_mask[...,None]), axis=2)\n", "# im_merge = np.concatenate((im[...,None]), axis=2)\n", "\n", "%matplotlib inline\n", "\n", "# Apply transformation on image\n", "im_merge_t = elastic_transform(im_merge, im_merge.shape[1] * 2, im_merge.shape[1] * 0.08, im_merge.shape[1] * 0.08)\n", "\n", "# Split image and mask\n", "im_t = im_merge_t[...,0]\n", "im_mask_t = im_merge_t[...,1]\n", "\n", "# Display result\n", "plt.figure(figsize = (16,14))\n", "plt.imshow(np.c_[np.r_[im, im_mask], np.r_[im_t, im_mask_t]], cmap='gray')\n", "# plt.imshow(np.c_[np.r_[im], np.r_[im_t]], cmap='gray')"], "metadata": {"_cell_guid": "e21faa1d-76bf-4697-b0f3-b0e6172b69fd", "_uuid": "112a2df12fb9af6b46d460b6d332381f00d913bf"}}, {"cell_type": "code", "execution_count": null, "outputs": [], "source": [], "metadata": {"_cell_guid": "ab28d5b6-9bb0-4231-8c65-628d16ae13f7", "_uuid": "e912392989e70c56843c6d8cc0f976530b8177c5", "collapsed": true}}], "metadata": {"language_info": {"mimetype": "text/x-python", "file_extension": ".py", "pygments_lexer": "ipython3", "nbconvert_exporter": "python", "version": "3.6.4", "codemirror_mode": {"version": 3, "name": "ipython"}, "name": "python"}, "kernelspec": {"display_name": "Python 3", "language": "python", "name": "python3"}}, "nbformat_minor": 1, "nbformat": 4}