{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"import json\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom PIL import Image, ImageDraw\nImage.MAX_IMAGE_PIXELS = None\nfrom skimage import io","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Convert JSON to Mask Image"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"img_path = \"../input/medical-labeling/test.tiff\"\njson_path = \"../input/medical-labeling/test.json\"\nimg = io.imread(img_path, plugin='pil')[:,:,:3]\n\n# Conversion needs the dimension of the image to create\n# a mask with the same size\ny_max = img.shape[0]\nx_max = img.shape[1]\n\n# Open the mask file\nread_file = open(json_path, \"r\") \ndata = json.load(read_file)\n\n# Add each polygon to list\npolys = []\nfor index in range(data.__len__()):\n    geom = np.array(data[index]['geometry']['coordinates'])\n    polys.append(geom)\n\n\n# \"Draw\" the polygons\nmsk = Image.new('L', (x_max, y_max), 0)  # (w, h)\nfor i in range(len(polys)):\n    poly = polys[i]\n    ImageDraw.Draw(msk).polygon(tuple(map(tuple, poly[0])), outline=1, fill=1) \n\nmask = np.array(msk)\n\n# Visualize\nfix, ax = plt.subplots(1,2, figsize=(15,10))\nax[0].imshow(img)\nax[1].imshow(mask)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":4}