{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","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? ","metadata":{"_cell_guid":"18d27eb0-3755-a476-34c8-05cfe6b4663a"}},{"cell_type":"code","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)","metadata":{"_cell_guid":"6e83104f-dd23-3adc-cf4c-f79aa655cfb6","execution":{"iopub.status.busy":"2021-06-28T12:27:42.615728Z","iopub.status.idle":"2021-06-28T12:27:42.616655Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load JSON of image overlays\nsh_fname = os.path.join(data_dir, 'train_geojson_v3/%s/006_VEG_L5_STANDALONE_TREES.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)","metadata":{"_cell_guid":"5734c8dd-d0ba-04ef-4a25-9d28530fd847","execution":{"iopub.status.busy":"2021-06-28T12:28:36.377716Z","iopub.execute_input":"2021-06-28T12:28:36.378081Z","iopub.status.idle":"2021-06-28T12:28:36.39921Z","shell.execute_reply.started":"2021-06-28T12:28:36.378051Z","shell.execute_reply":"2021-06-28T12:28:36.397936Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"_cell_guid":"d4154b1e-f09b-ec68-1f0e-c9f8f3383d4f"},"execution_count":null,"outputs":[]}]}