{
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.5.2"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0,
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "_cell_guid": "910630a8-8716-de19-c937-563a95e5172d",
        "_active": false
      },
      "source": "Trying to put the masks created by amaia in this script:\nhttps://www.kaggle.com/aamaia/dstl-satellite-imagery-feature-detection/trees-are-red-buildings-are-blue-sort-of\ninto polygons and check the results",
      "execution_count": null,
      "outputs": [],
      "execution_state": "idle"
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "6cf4c02f-937f-f1db-9049-30843bbbf3f1",
        "_active": false,
        "collapsed": false
      },
      "outputs": [],
      "source": "import os\nimport numpy as np\nimport tifffile as tiff\nimport cv2\nfrom skimage.segmentation import slic, mark_boundaries\n\nfrom matplotlib.patches import Polygon \nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\n",
      "execution_state": "idle"
    },
    {
      "metadata": {
        "_cell_guid": "c601b216-8a27-2541-f112-14c3e27f1c54",
        "_active": false,
        "collapsed": false
      },
      "source": "######################\n# How to use shapely #\n######################\n\nfrom shapely import geometry\nfrom shapely.geometry import Polygon as Polygon_shapely\n\nfig, ax = plt.subplots(figsize=(8,8))\n\npolygon = Polygon_shapely([[0,0], [1,0.5], [1,1],[0.5,0.8], [0,1]]) \nprint('Area', polygon.area)\nprint('Length', polygon.length)\nprint(np.array(polygon.exterior))\n\nmpoly = Polygon(np.array(polygon.exterior), color=plt.cm.Set2(1),  alpha=0.3)\n\nprint(mpoly)\n\nax.add_patch(mpoly)",
      "execution_count": null,
      "cell_type": "code",
      "outputs": [],
      "execution_state": "idle"
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "e5ab2dc2-a29a-2685-2638-6d8c0542d35a",
        "_active": true
      },
      "outputs": [],
      "source": "def stretch_8bit(bands, lower_percent=2, higher_percent=98):\n    out = np.zeros_like(bands)\n    for i in range(3):\n        a = 0 #np.min(band)\n        b = 255  #np.max(band)\n        c = np.percentile(bands[:,:,i], lower_percent)\n        d = np.percentile(bands[:,:,i], higher_percent)        \n        t = a + (bands[:,:,i] - c) * (b - a) / (d - c)    \n        t[t<a] = a\n        t[t>b] = b\n        out[:,:,i] =t\n    return out.astype(np.uint8) \n",
      "execution_state": "idle"
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "51b86c6e-090a-9c20-ef84-48b13aedf309",
        "_active": false
      },
      "outputs": [],
      "source": "def RGB(image_id):\n    filename = os.path.join('..', 'input', 'three_band', '{}.tif'.format(image_id))\n    img = tiff.imread(filename)\n    img = np.rollaxis(img, 0, 3)    \n    return img\n    ",
      "execution_state": "idle"
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "8800dc50-2e19-e287-1a8e-6354a6dc6751",
        "_active": false
      },
      "outputs": [],
      "source": "def M(image_id):\n    filename = os.path.join('..', 'input', 'sixteen_band', '{}_M.tif'.format(image_id))\n    img = tiff.imread(filename)    \n    img = np.rollaxis(img, 0, 3)\n    return img",
      "execution_state": "idle"
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "7e79e609-1a41-33dd-5647-88bfdf0a1101",
        "_active": false
      },
      "outputs": [],
      "source": "image_id = '6120_2_2'\nrgb = RGB(image_id)\nrgb1 = stretch_8bit(rgb)",
      "execution_state": "idle"
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "2bbcaa8e-e961-cabc-591d-386b2bf0b8ed",
        "_active": false,
        "collapsed": false
      },
      "outputs": [],
      "source": null,
      "execution_state": "idle"
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "a6aa1f01-c4ea-a1f5-d418-59314117d529",
        "_active": false
      },
      "outputs": [],
      "source": "y1,y2,x1,x2 = 1000, 1600, 2000, 2600\n#region = rgb1[y1:y2, x1:x2, :]\nregion  = rgb1[:,:,:]\nplt.figure()\nplt.imshow(region)",
      "execution_state": "idle"
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "170f19bf-d231-f8c9-6c44-57fc36f39bae",
        "_active": false
      },
      "outputs": [],
      "source": "m = M(image_id)    \nm = cv2.resize(m, tuple(reversed(rgb.shape[:2])))\n\nimg = np.zeros_like(rgb)\nimg[:,:,0] = m[:,:,6] #nir1\nimg[:,:,1] = m[:,:,4] #red\nimg[:,:,2] = rgb[:,:,2] #blue\nimg = stretch_8bit(img)\n#region = img[y1:y2, x1:x2, :]\nregion = img[:,:,:]\nplt.figure()\nplt.imshow(region)",
      "execution_state": "idle"
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "105a1c2e-34a9-55ab-86e6-6db9d844846a",
        "_active": false
      },
      "outputs": [],
      "source": "blue_mask = cv2.inRange(region, np.array([15,115,200]), np.array([80,200,255]))    \nmask = cv2.bitwise_and(region, region, mask=blue_mask)\nmask = cv2.cvtColor(mask, cv2.COLOR_RGB2GRAY)    \nplt.figure()\nplt.imshow(mask, cmap='gray')",
      "execution_state": "idle"
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "6f9c58d1-e0dd-84b7-7cc4-120165f3cfa2",
        "_active": false,
        "collapsed": false
      },
      "outputs": [],
      "source": "segments = slic(region, n_segments=100, compactness=20.0, \n         max_iter=10, sigma=5, spacing=None, multichannel=True, \n         convert2lab=True, enforce_connectivity=False, \n         min_size_factor=10, max_size_factor=3, slic_zero=False)\n\nboundaries = mark_boundaries(region, segments, color=(0,255,0))\nplt.figure()\nplt.imshow(boundaries)",
      "execution_state": "idle"
    },
    {
      "metadata": {
        "_cell_guid": "dd85cb9c-8116-102d-e457-ea1c0c388d84",
        "_active": false,
        "collapsed": false
      },
      "source": "print(np.shape(mask))\nprint(mask)\n",
      "execution_count": null,
      "cell_type": "code",
      "outputs": [],
      "execution_state": "idle"
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "3a9028ae-02b5-2b93-9be6-b210904e3dca",
        "_active": false
      },
      "outputs": [],
      "source": "out = np.zeros_like(mask)\nfor i in range(np.max(segments)):\n    s = segments == i\n    s_size = np.sum(s)\n    s_count = np.sum([1 for x in mask[s].ravel() if x>0])\n    #print(s_count, s_size)\n    if s_count > 0.1*s_size:\n        out[s] = 255\n        \nplt.figure()\nplt.imshow(out, cmap='gray')",
      "execution_state": "idle"
    },
    {
      "metadata": {
        "_cell_guid": "727248f9-6011-7ded-8643-b438028ae7dc",
        "_active": false,
        "collapsed": false
      },
      "source": "print(type(out))\nprint(np.shape(out))\nprint(out[1500:2100,1500:2100])",
      "execution_count": null,
      "cell_type": "code",
      "outputs": [],
      "execution_state": "idle"
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "b5f5c739-2cc4-2b38-21d8-f18004914f98",
        "_active": false
      },
      "outputs": [],
      "source": "out2 = cv2.bitwise_and(region, region, mask=out)\nfig, ax = plt.subplots(1, 2)\nax[0].imshow(region)\nax[1].imshow(out2)",
      "execution_state": "idle"
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "162a3d4b-7f64-0a4b-8871-caafbe205bd1",
        "_active": false
      },
      "outputs": [],
      "source": null,
      "execution_state": "idle"
    }
  ]
}