{
  "metadata": {
    "kernelspec": {
      "name": "python"
    },
    "language_info": {
      "name": "python",
      "version": "3.5.1"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0,
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "_cell_guid": "333e1883-0c9a-5b55-b87f-9f2df608d878",
        "_active": false
      },
      "source": "Transform a polygon to the scale of an image. gdal is not installed here yet, so I've put the number of x and y pixels in manually for now. ",
      "outputs": []
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "136cd7ae-8c51-249f-e78a-a8eb9ff672e5",
        "_active": true,
        "collapsed": false
      },
      "outputs": [],
      "source": "import pandas as pd\nimport numpy as np\nfrom shapely import wkt\nfrom shapely import affinity\nimport shapely\nimport gdal\n\npolygons_raw = pd.read_csv('../input/train_wkt_v3.csv')\ngrid_sizes = pd.read_csv('../input/grid_sizes.csv')\ncols = grid_sizes.columns.tolist()\ncols[0]='ImageId'\ngrid_sizes.columns = cols\n\nimg_id = '6120_2_2'\ni_grid_size = grid_sizes[grid_sizes.ImageId == img_id]\nx_max = i_grid_size.Xmax.values[0]\ny_min = i_grid_size.Ymin.values[0]\n\n#Get just a single class of training polygons for this image\nclass_2 = polygons_raw[(polygons_raw.ImageId == img_id) & (polygons_raw.ClassType==2)]\n\n#WKT to shapely object\npolygons = wkt.loads(class_2.MultipolygonWKT.values[0])\n\nprint('Original Extent')\nprint(polygons.bounds)\n\n#Load the image and get its width and height\n#image = gdal.Open('three_band/6120_2_2.tif')\n#W = image.RasterXSize\n#H = image.RasterYSize\n#gdal is not loaded in kaggle yet, so I'll do these manually for now.\nW = 3403\nH = 3348\n\n#Transform the polygons \nW_ = W * (W/(W+1))\nH_ = H * (H/(H+1))\n\nx_scaler = W_ / x_max\ny_scaler = H_ / y_min\n\npolygons = shapely.affinity.scale(polygons, xfact = x_scaler, yfact= y_scaler, origin=(0,0,0))\n\nprint('New Extent to match raster')\nprint(polygons.bounds)\n\n#Now scale the shapely file back to its original coordinates for submission\n#The scaler is the inverse of the original scaler\nx_scaler = 1/x_scaler\ny_scaler = 1/y_scaler\n\npolygons = shapely.affinity.scale(polygons, xfact = x_scaler, yfact= y_scaler, origin=(0,0,0))\n\nprint('Back to original')\nprint(polygons.bounds)"
    }
  ]
}