{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "_cell_guid": "2b650242-a8be-3c9e-4983-159c9f65b24d"
      },
      "source": [
        "This script draws selected class polygons on a image produced from sixteen m band image. I used [Small Vehicles][1] as a template. To get closer look for each polygon uncommend and edit the commented part of the script.\n",
        "\n",
        "  [1]: https://www.kaggle.com/aamaia/dstl-satellite-imagery-feature-detection/small-vehicles"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "b369332f-a783-8f5f-8893-078f859365e8"
      },
      "outputs": [],
      "source": [
        "\n",
        "\"\"\"\n",
        "This Scritp Display Traning Polygons on Satalite \u0130mages for any Class\n",
        "\"\"\"\n",
        "\n",
        "\n",
        "\n",
        "#Import Libraries\n",
        "import os,cv2,tifffile\n",
        "import pandas as pd\n",
        "import numpy as np\n",
        "import matplotlib.pyplot as plt\n",
        "from shapely import wkt, affinity\n",
        "\n",
        "\n",
        "\n",
        "\"\"\"\n",
        "Classes \n",
        "        'Buildings'        :1,\n",
        "        'Structures '      :2,\n",
        "        'Road'             :3,\n",
        "        'Track'            :4,\n",
        "        'Trees'            :5,\n",
        "        'Crops'            :6,\n",
        "        'Waterway'         :7,\n",
        "        'StandingWater'    :8,\n",
        "        'VehicleLarge'     :9,\n",
        "        'VehicleSmall'     :10,\n",
        "\"\"\"\n",
        "\n",
        "#Select a class and image id to be drawn\n",
        "Class = 1\n",
        "ImageID = '6120_2_2' #'6120_2_2', '6100_1_3', '6140_3_1','6110_3_1','6100_2_3','6140_1_2','6120_2_0','6100_2_2','6110_1_2','6070_2_3','6110_4_0','6090_2_0','6060_2_3'\n",
        "#---------------------------------------\n",
        "\n",
        "#Define Functions\n",
        "def stretch2(band, lower_percent=2, higher_percent=98):\n",
        "    a = 0 #np.min(band)\n",
        "    b = 255  #np.max(band)\n",
        "    c = np.percentile(band, lower_percent)\n",
        "    d = np.percentile(band, higher_percent)        \n",
        "    out = a + (band - c) * (b - a) / (d - c)    \n",
        "    out[out<a] = a\n",
        "    out[out>b] = b\n",
        "    return out\n",
        "def adjust_contrast(x):    \n",
        "    for i in range(3):\n",
        "        x[:,:,i] = stretch2(x[:,:,i])\n",
        "    return x.astype(np.uint8)  \n",
        "    \n",
        "W = 3396\n",
        "H = 3348\n",
        "def truth_polys(image_id, class_id, W, H):\n",
        "    x = pd.read_csv('../input/train_wkt_v4.csv')\n",
        "    rows = x.loc[(x.ImageId==image_id) & (x.ClassType==class_id), 'MultipolygonWKT']\n",
        "    mp = wkt.loads(rows.values[0])\n",
        "    grid_sizes = pd.read_csv('../input/grid_sizes.csv', names=['ImageId', 'Xmax', 'Ymin'], skiprows=1)\n",
        "    xmax, ymin = grid_sizes[grid_sizes.ImageId == ImageID].iloc[0,1:].astype(float)    \n",
        "    W_ = W * (W/(W+1.))\n",
        "    H_ = H * (H/(H+1.))\n",
        "    x_scaler = W_ / xmax\n",
        "    y_scaler = H_ / ymin\n",
        "    return affinity.scale(mp, xfact = x_scaler, yfact= y_scaler, origin=(0,0,0))  \n",
        "#-----------------------------------------------------------------------------------------    \n",
        "\n",
        "\n",
        "#Read threeband image\n",
        "rgbfile=os.path.join('..', 'input', 'three_band', '{}.tif'.format(ImageID))              \n",
        "rgb = tifffile.imread(rgbfile)\n",
        "rgb = np.rollaxis(rgb, 0, 3)     \n",
        "\n",
        "#Read 16band m image\n",
        "mfile = os.path.join('..', 'input', 'sixteen_band', '{}_M.tif'.format(ImageID))\n",
        "img_m = tifffile.imread(mfile)    \n",
        "img_m = np.rollaxis(img_m, 0, 3)\n",
        "img_m = cv2.resize(img_m, tuple(reversed(rgb.shape[:2])))    \n",
        " \n",
        "#Turn m image into rgb color           \n",
        "x = np.zeros_like(rgb)\n",
        "x[:,:,0] = img_m[:,:,4]\n",
        "x[:,:,1] = img_m[:,:,2]\n",
        "x[:,:,2] = img_m[:,:,1]\n",
        "x = adjust_contrast(x).copy()\n",
        "\n",
        "H=len(x); W=len(x[0])\n",
        "#Read Polygons\n",
        "polys = truth_polys(ImageID, Class,W,H)\n",
        "\n",
        "#Add polygons to the x image\n",
        "#patches=[]\n",
        "for poly_id, poly in enumerate(polys):\n",
        "    x1,y1,x2,y2 = [int(pb) for pb in poly.bounds]\n",
        "    xys=np.array(list(poly.exterior.coords))  \n",
        "    xys = xys.reshape((-1,1,2))\n",
        "    xys=np.around(xys, decimals=0)\n",
        "    xys=xys.astype(int)\n",
        "    cv2.polylines(x,[xys],True,(255,0,0),3)\n",
        "    #patches.append(np.hstack([x[y1-PADDING:y2+PADDING, x1-PADDING:x2+PADDING,:]]))\n",
        "\n",
        "##To focus on each element\n",
        "#PADDING = 10\n",
        "#W = 3396\n",
        "#H = 3348\n",
        "#patches = []\n",
        "#titles = []            \n",
        "#for poly_id, poly in enumerate(polys):\n",
        "#    x1,y1,x2,y2 = [int(pb) for pb in poly.bounds]\n",
        "#    cv2.rectangle(x, (x1,y1), (x2,y2), (255,0,0), 1)\n",
        "#    cv2.rectangle(img_p, (x1,y1), (x2,y2), (255,0,0), 1)\n",
        "#    patches.append(np.hstack([x[y1-PADDING:y2+PADDING, x1-PADDING:x2+PADDING,:], img_p[y1-PADDING:y2+PADDING, x1-PADDING:x2+PADDING,:]]))\n",
        "#    titles.append(\"ImageID: {} -- poly_id: {}\".format(ImageID, poly_id))\n",
        "#\n",
        "\n",
        "\n",
        "#-----------------------------------------------------------------------------------------    \n",
        "#Plot\n",
        "fig, ax = plt.subplots(figsize=(30,30))\n",
        "ax.imshow(x)\n",
        "plt.savefig(ImageID+\".png\")\n",
        "\n",
        "#fig, ax = plt.subplots(1, 1, figsize=(10,10))\n",
        "#for i in range(10):\n",
        "#    ax.imshow(patches[i]) \n"
      ]
    }
  ],
  "metadata": {
    "_change_revision": 0,
    "_is_fork": false,
    "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
}