{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "_cell_guid": "18d27eb0-3755-a476-34c8-05cfe6b4663a"
      },
      "source": [
        "This notebook will demonstrate how to convert JSON polygons into an image mask using openCV's `fillPoly` function.  I tested a few ways, including `shapely` polygons and `matplotlib` polygons, and this was the fastest by far.  \n",
        "\n",
        "What do I have to do to make Kaggle stop overwriting my updates? "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "6e83104f-dd23-3adc-cf4c-f79aa655cfb6"
      },
      "outputs": [],
      "source": [
        "import cv2\n",
        "import json\n",
        "import os\n",
        "import numpy as np\n",
        "import matplotlib.pyplot as plt\n",
        "import pandas as pd\n",
        "\n",
        "%matplotlib inline\n",
        "\n",
        "grid_name = '6010_4_2'\n",
        "data_dir = '../input'\n",
        "shape = (3345, 3396)\n",
        "\n",
        "# Load grid CSV\n",
        "grid_sizes = pd.read_csv(os.path.join(data_dir, 'grid_sizes.csv'), index_col=0)\n",
        "grid_sizes.ix[grid_name]\n",
        "\n",
        "def scale_coords(shape, grid_name, point):\n",
        "    \"\"\"Scale the coordinates of a polygon into the image coordinates for a grid cell\"\"\"\n",
        "    w,h = shape\n",
        "    Xmax, Ymin = grid_sizes.ix[grid_name][['Xmax', 'Ymin']]\n",
        "    x,y = point[:,0], point[:,1]\n",
        "\n",
        "    wp = float(w**2)/(w+1)\n",
        "    xp = x/Xmax*wp\n",
        "\n",
        "    hp = float(h**2)/(h+1)\n",
        "    yp = y/Ymin*hp\n",
        "\n",
        "    return np.concatenate([xp[:,None],yp[:,None]], axis=1)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "5734c8dd-d0ba-04ef-4a25-9d28530fd847"
      },
      "outputs": [],
      "source": [
        "# Load JSON of image overlays\n",
        "sh_fname = os.path.join(data_dir, 'train_geojson_v3/%s/002_TR_L4_POOR_DIRT_CART_TRACK.geojson'%grid_name)\n",
        "with open(sh_fname, 'r') as f:\n",
        "    sh_json = json.load(f)\n",
        "\n",
        "# Scale the polygon coordinates to match the pixels\n",
        "polys = []\n",
        "for sh in sh_json['features']:\n",
        "    geom = np.array(sh['geometry']['coordinates'][0])\n",
        "    geom_fixed = scale_coords(shape, grid_name, geom)\n",
        "\n",
        "    pts = geom_fixed.astype(int)\n",
        "    polys.append(pts)\n",
        "\n",
        "# Create an empty mask and then fill in the polygons\n",
        "mask = np.zeros(shape)\n",
        "cv2.fillPoly(mask, polys, 1)\n",
        "mask = mask.astype(bool)\n",
        "\n",
        "plt.imshow(mask)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "d4154b1e-f09b-ec68-1f0e-c9f8f3383d4f"
      },
      "outputs": [],
      "source": ""
    }
  ],
  "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
}