{
  "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": [
    {
      "metadata": {
        "_cell_guid": "2b650242-a8be-3c9e-4983-159c9f65b24d",
        "_active": false,
        "collapsed": false
      },
      "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",
      "execution_count": null,
      "cell_type": "markdown",
      "outputs": []
    },
    {
      "metadata": {
        "_cell_guid": "b369332f-a783-8f5f-8893-078f859365e8",
        "_active": false,
        "collapsed": false
      },
      "source": "\n\"\"\"\nThis Scritp Display Traning Polygons on Satalite İmages for any Class\n\"\"\"\n\n\n\n#Import Libraries\nimport os,cv2,tifffile\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom shapely import wkt, affinity\n\n\n\n\"\"\"\nClasses \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\nClass = 1\nImageID = '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\ndef 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\ndef adjust_contrast(x):    \n    for i in range(3):\n        x[:,:,i] = stretch2(x[:,:,i])\n    return x.astype(np.uint8)  \n    \nW = 3396\nH = 3348\ndef 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\nrgbfile=os.path.join('..', 'input', 'three_band', '{}.tif'.format(ImageID))              \nrgb = tifffile.imread(rgbfile)\nrgb = np.rollaxis(rgb, 0, 3)     \n\n#Read 16band m image\nmfile = os.path.join('..', 'input', 'sixteen_band', '{}_M.tif'.format(ImageID))\nimg_m = tifffile.imread(mfile)    \nimg_m = np.rollaxis(img_m, 0, 3)\nimg_m = cv2.resize(img_m, tuple(reversed(rgb.shape[:2])))    \n \n#Turn m image into rgb color           \nx = np.zeros_like(rgb)\nx[:,:,0] = img_m[:,:,4]\nx[:,:,1] = img_m[:,:,2]\nx[:,:,2] = img_m[:,:,1]\nx = adjust_contrast(x).copy()\n\nH=len(x); W=len(x[0])\n#Read Polygons\npolys = truth_polys(ImageID, Class,W,H)\n\n#Add polygons to the x image\n#patches=[]\nfor 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\nfig, ax = plt.subplots(figsize=(30,30))\nax.imshow(x)\nplt.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",
      "execution_count": 1,
      "cell_type": "code",
      "outputs": [],
      "execution_state": "idle"
    }
  ]
}