{
  "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": "14050a94-da60-659f-8b60-f3bae0bb7d3d",
        "_active": true,
        "collapsed": false
      },
      "source": "import cv2\nimport matplotlib\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport os\nfrom shapely import affinity\nfrom shapely import geometry\nfrom shapely import wkt\nfrom PIL import Image\nimport tifffile\n\n\ndef scale_percentile(matrix):\n    w, h, d = matrix.shape\n    matrix = np.reshape(matrix, [w * h, d]).astype(np.float64)\n    # Get 2nd and 98th percentile\n    mins = np.percentile(matrix, 1, axis=0)\n    maxs = np.percentile(matrix, 99, axis=0) - mins\n    matrix = (matrix - mins[None, :]) / maxs[None, :]\n    matrix = np.reshape(matrix, [w, h, d])\n    matrix = matrix.clip(0, 1)\n    return matrix\n\n\ndef mask_for_polygons(polygons, im_size):\n    img_mask = np.zeros(im_size, np.uint8)\n    if not polygons:\n        return img_mask\n\n    int_coords = lambda x: np.array(x).round().astype(np.int32)\n    exteriors = [int_coords(poly.exterior.coords) for poly in polygons]\n    interiors = [int_coords(pi.coords) for poly in polygons\n                 for pi in poly.interiors]\n    cv2.fillPoly(img_mask, exteriors, 1)\n    cv2.fillPoly(img_mask, interiors, 0)\n    return img_mask\n\n\ndef show_mask(m):\n    # hack for nice display\n    tifffile.imshow(255 * np.stack([m, m, m]));",
      "execution_count": 1,
      "cell_type": "code",
      "outputs": [],
      "execution_state": "idle"
    },
    {
      "metadata": {
        "_cell_guid": "59f4e256-b567-1ca4-f8e1-ceb5050b8ffd",
        "_active": false,
        "collapsed": false
      },
      "source": "SELECTED = '6100_2_2' # Use line of training csv\nCLASSTYPE = 'ClassType'\nIMAGE_ID = 'ImageId'\nINPUT = '../input'\nPOLYGON = 'MultipolygonWKT'\nTHREE_BAND = '../input/three_band'\nTIF = '.tif'\nXMAX = 'Xmax'\nYMIN = 'Ymin'\n\ntrain_labels = pd.read_csv('../input/train_wkt_v4.csv', index_col=[IMAGE_ID, CLASSTYPE])\n\ngrid = pd.read_csv('../input/grid_sizes.csv', index_col=0)",
      "execution_count": 2,
      "cell_type": "code",
      "outputs": [],
      "execution_state": "idle"
    },
    {
      "metadata": {
        "_cell_guid": "694bd14f-3e64-1ad7-3465-ccedf90160cb",
        "_active": false,
        "collapsed": false
      },
      "source": "row = train_labels.loc[SELECTED, 1]\n\nimage = tifffile.imread(os.path.join(THREE_BAND, SELECTED + TIF)).transpose([1,2,0])\n\nmasks = affinity.scale(wkt.loads(row[POLYGON]),\n                       xfact=image.shape[1]/grid.loc[SELECTED, XMAX],\n                       yfact=image.shape[0]/grid.loc[SELECTED, YMIN],\n                       origin=(0, 0, 0))\n\nx0, y0, x1, y1 = masks.geoms[0].exterior.bounds\n\ntifffile.imshow(255 * scale_percentile(image[:200:,3000:]))\ntifffile.imshow(255 * scale_percentile(image))\nshow_mask(mask_for_polygons(masks, image.shape[:2])[:200:,3000:])\naa = np.copy(image)\naa[:,:,2] += mask_for_polygons(masks, image.shape[:2]) * 1000\ntifffile.imshow(255 * scale_percentile(aa)[:200:,3000:])",
      "execution_count": 8,
      "cell_type": "code",
      "outputs": [],
      "execution_state": "idle"
    }
  ]
}