Skip to content

Instantly share code, notes, and snippets.

@dvj
Created September 11, 2015 04:05
Show Gist options
  • Save dvj/b1dd5df190b3cd417a1e to your computer and use it in GitHub Desktop.
Save dvj/b1dd5df190b3cd417a1e to your computer and use it in GitHub Desktop.
simplify points in geojson file using opencv implementation of Douglas–Peucker : https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm
import cv2, numpy as np, json, sys
def simplify(data):
d = np.array(data).astype(np.float32)
if d.size > 3:
simple = cv2.approxPolyDP(d, thresh, False).tolist()
data = [[round(n, 6), round(p, 6)] for n,p in np.reshape(simple, [-1, 2]).tolist()]
else:
print "not reducing {}".format(d)
print "reduced {} to {}".format(len(d), len(data))
return data
if __name__ == '__main__':
thresh = float(sys.argv[1])
with open(sys.argv[2]) as f:
data = json.load(f)
for feature in data['features']:
geo = feature['geometry']
if geo['type'] in ['LineString', 'Polygon']:
geo['coordinates'] = simplify(geo['coordinates'])
elif geo['type'] in ['MultiLineString', 'MultiPolygon']:
for indx, line in enumerate(geo['coordinates']):
geo['coordinates'][indx] = simplify(line)
elif geo['type'] == 'GeometryCollection':
print "Reducing Geometry inside GeometryCollection is not supported"
else:
print "Unknown geometry: {}".format(geo['type'])
with open(sys.argv[3], 'w') as output_file:
output_file.write(json.dumps(data))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment