{"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\nWhat 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\nimport json\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n%matplotlib inline\n\ngrid_name = '6010_4_2'\ndata_dir = '../input'\nshape = (3345, 3396)\n\n# Load grid CSV\ngrid_sizes = pd.read_csv(os.path.join(data_dir, 'grid_sizes.csv'), index_col=0)\ngrid_sizes.ix[grid_name]\n\ndef 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\nsh_fname = os.path.join(data_dir, 'train_geojson_v3/%s/002_TR_L4_POOR_DIRT_CART_TRACK.geojson'%grid_name)\nwith open(sh_fname, 'r') as f:\n    sh_json = json.load(f)\n\n# Scale the polygon coordinates to match the pixels\npolys = []\nfor 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\nmask = np.zeros(shape)\ncv2.fillPoly(mask, polys, 1)\nmask = mask.astype(bool)\n\nplt.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}