{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "09ee4ef2-7026-c832-37b3-2287665e1d26"
      },
      "outputs": [],
      "source": [
        "from collections import defaultdict\n",
        "import csv\n",
        "import sys\n",
        "\n",
        "import cv2\n",
        "from shapely.geometry import MultiPolygon, Polygon\n",
        "import shapely.wkt\n",
        "import shapely.affinity\n",
        "import numpy as np\n",
        "import tifffile as tiff\n",
        "\n",
        "csv.field_size_limit(sys.maxsize);"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "3c3b3fc7-b670-15af-d8ec-7a6f6e9b97bf"
      },
      "outputs": [],
      "source": [
        "IM_ID = '6120_2_2'\n",
        "POLY_TYPE = '1'  # buildings\n",
        "\n",
        "# Load grid size\n",
        "x_max = y_min = None\n",
        "for _im_id, _x, _y in csv.reader(open('../input/grid_sizes.csv')):\n",
        "    if _im_id == IM_ID:\n",
        "        x_max, y_min = float(_x), float(_y)\n",
        "        break\n",
        "\n",
        "# Load train poly with shapely\n",
        "train_polygons = None\n",
        "for _im_id, _poly_type, _poly in csv.reader(open('../input/train_wkt_v4.csv')):\n",
        "    if _im_id == IM_ID and _poly_type == POLY_TYPE:\n",
        "        train_polygons = shapely.wkt.loads(_poly)\n",
        "        break\n",
        "\n",
        "# Read image with tiff\n",
        "im_rgb = tiff.imread('../input/three_band/{}.tif'.format(IM_ID)).transpose([1, 2, 0])\n",
        "im_size = im_rgb.shape[:2]"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "12a8effb-b1ef-89ba-e38c-c3edffdb09fe"
      },
      "outputs": [],
      "source": [
        "def get_scalers():\n",
        "    h, w = im_size  # they are flipped so that mask_for_polygons works correctly\n",
        "    w_ = w * (w / (w + 1))\n",
        "    h_ = h * (h / (h + 1))\n",
        "    return w_ / x_max, h_ / y_min\n",
        "\n",
        "x_scaler, y_scaler = get_scalers()\n",
        "\n",
        "train_polygons_scaled = shapely.affinity.scale(\n",
        "    train_polygons, xfact=x_scaler, yfact=y_scaler, origin=(0, 0, 0))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "04c80376-5f2a-0d23-7087-dadfa07207e8"
      },
      "outputs": [],
      "source": [
        "def mask_for_polygons(polygons):\n",
        "    img_mask = np.zeros(im_size, np.uint8)\n",
        "    if not polygons:\n",
        "        return img_mask\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",
        "train_mask = mask_for_polygons(train_polygons_scaled)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "7be33fa2-bf75-5d0b-bcc7-5c63ba8b6927"
      },
      "outputs": [],
      "source": [
        "train_mask.shape"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "6a4f172b-fc09-7e9e-8f48-2298392aea54"
      },
      "outputs": [],
      "source": [
        "im_rgb = tiff.imread('../input/three_band/{}.tif'.format(IM_ID)).transpose([1, 2, 0])"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "45ffddbc-9235-3500-227c-a412c90d3866"
      },
      "outputs": [],
      "source": [
        "im_rgb.shape"
      ]
    }
  ],
  "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
}