Skip to content

Instantly share code, notes, and snippets.

@shnhrtkyk
Last active October 4, 2019 12:10
Show Gist options
  • Save shnhrtkyk/432da0c45d0def4c2152b4d6405bf918 to your computer and use it in GitHub Desktop.
Save shnhrtkyk/432da0c45d0def4c2152b4d6405bf918 to your computer and use it in GitHub Desktop.
Convert polygons to raster image
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 3 10:46:28 2019
@author: shino
"""
from shapely import wkt
import json
import pylab as plt
import numpy as np
from matplotlib.path import Path
from PIL import Image
width, height=1024, 1024
finalgt = np.zeros((width, height))
path = "/path/to/labels/"
filename = path + "guatemala-volcano_00000000_pre_disaster.json"
outpath= path + "guatemala-volcano_00000000_pre_disaster.jpg"
file = open(filename, 'r')
json = json.load(file)
for i in json['features']['xy']:
geom = wkt.loads(i['wkt'])
pts = list(geom.exterior.coords)
poly_path=Path(pts)
# print(poly_path)
x, y = np.mgrid[:height, :width]
coors = (np.hstack((x.reshape(-1, 1), y.reshape(-1,1))))# coors.shape is (4000000,2)
mask = poly_path.contains_points(coors)
# print(mask)
finalgt = np.where(mask.reshape(height, width) == True,255,finalgt)
# print(pts)
plt.imshow(finalgt.reshape(height, width))
plt.show()
pilImg = Image.fromarray(np.uint8(finalgt))
pilImg.save(outpath, 'JPEG')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment