{
  "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": "ebe40fa1-1189-132c-373a-6f612df71742",
        "_active": false,
        "collapsed": false
      },
      "source": "I started writing the notebook to check the effect of moving vehicles  vs the time gap in acquisition of sensor bands.  The plan was to:\n\n - choose samples where vehicles were along a road\n - compare vehicle positions against different bands\n\nBut in the meantime I realized this is not very important. There are more challenging things to deal with. The images below speak for themselves.\n",
      "outputs": []
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "6a9d48c4-1234-1643-8a39-ba73442725e1",
        "_active": false,
        "collapsed": false
      },
      "outputs": [],
      "source": "import os\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport cv2\nimport tifffile as tiff\nfrom shapely.wkt import loads\nfrom shapely import affinity\n\n# living dangerously\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nSVEHICLE_TYPE = 10\nSVEHICLE_IMAGES = [ '6120_2_2',\n    '6100_1_3', '6140_3_1','6110_3_1','6100_2_3',\n    '6140_1_2','6120_2_0','6100_2_2','6110_1_2',\n    '6070_2_3','6110_4_0','6090_2_0','6060_2_3'\n]\n\nPADDING = 10\nW = 3396\nH = 3348\n\ndef P(image_id):\n    filename = os.path.join('..', 'input', 'sixteen_band', '{}_P.tif'.format(image_id))\n    img = tiff.imread(filename)    \n    return img\n\ndef 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    \ndef 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\n\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\n\ndef adjust_contrast(x):    \n    for i in range(3):\n        x[:,:,i] = stretch2(x[:,:,i])\n    return x.astype(np.uint8)\n    \ndef truth_polys(image_id, class_id):\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 = loads(rows.values[0])\n    \n    grid_sizes = pd.read_csv('../input/grid_sizes.csv')\n    xmax, ymin = [(row[1], row[2]) for row in grid_sizes.values if row[0] == image_id][0]    \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    "
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "621393a1-5649-c925-99d1-b635f30a25ea",
        "_active": true
      },
      "outputs": [],
      "source": "    \n    patches = []\n    titles = []\n    for image_id in SVEHICLE_IMAGES:\n        print(image_id)\n        polys = truth_polys(image_id, SVEHICLE_TYPE)                \n        rgb = RGB(image_id)\n        #rgb = adjust_contrast(rgb)        \n        #rgb = rgb.copy().astype(np.uint8)        \n        \n        img_p = P(image_id)\n        img_p = cv2.resize(img_p, tuple(reversed(rgb.shape[:2])))        \n        img_p = cv2.cvtColor(img_p, cv2.COLOR_GRAY2RGB)        \n        img_p = adjust_contrast(img_p)\n        \n        img_m = M(image_id)\n        img_m = cv2.resize(img_m, tuple(reversed(rgb.shape[:2])))                \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        for poly_id, poly in enumerate(polys):\n            x1,y1,x2,y2 = [int(x) for x 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(\"image_id: {} -- poly_id: {}\".format(image_id, poly_id))\n    \n    "
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "c250e212-14c1-b3e3-695c-c6c638df502b",
        "_active": false
      },
      "outputs": [],
      "source": "    #random = np.arange(len(patches))\n    #np.random.shuffle(random)\n    c = 0\n    for _ in range(15):\n        rows = 10\n        cols = 5\n        f, ax = plt.subplots(rows, cols, figsize=(10,10))\n        for i in range(rows):\n            for j in range(cols):                \n                c += 1\n                if c >= len(patches):\n                    break\n                ax[i,j].axis('off')\n                ax[i,j].grid(False)\n                ax[i,j].imshow(patches[c])                \n                #ax[i, j].set_title(titles[c])"
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "c585aa87-0281-9213-eaad-0bde52466220",
        "_active": false
      },
      "outputs": [],
      "source": ""
    }
  ]
}