/
offroad_tiles.py
175 lines (134 loc) · 4.95 KB
/
offroad_tiles.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
from __future__ import print_function
import os
import requests
import mercantile
import mapnik
import numpy as np
from matplotlib import image
def tile_url(template, tile):
return template.format(z=tile.z, x=tile.x, y=tile.y)
def tile_path(base, tile, ext):
return os.path.join(base, str(tile.z), str(tile.x), str(tile.y) + "." + ext)
def prep_dirs(path):
directory_name = os.path.dirname(path)
if not os.path.exists(directory_name):
os.makedirs(directory_name)
return True
def save_tile(url, path):
if os.path.exists(path):
return
prep_dirs(path)
res = requests.get(url)
if res.ok and res.content != '':
with open(path, 'wb') as fh:
fh.write(res.content)
return True
else:
print("Could not save {}".format(url))
return False
strava = "http://d2z9m7k9h4f0yp.cloudfront.net/tiles/cycling/color1/{z}/{x}/{y}.png"
osm_vect = "http://tile.openstreetmap.us/vectiles-highroad/{z}/{x}/{y}.json"
tiledir = os.path.abspath(os.path.join(os.path.dirname(__file__), 'tiles'))
def seed_inputs(bounds, zooms):
for tile in mercantile.tiles(*bounds, zooms=zooms):
s = tile_url(strava, tile), tile_path(os.path.join(tiledir, 'strava'), tile, 'png')
v = tile_url(osm_vect, tile), tile_path(os.path.join(tiledir, 'osm'), tile, 'json')
save_tile(*s)
save_tile(*v)
##################################################
##################################################
def vecttile_mask(tile, save_mask=True):
bounds = mercantile.bounds(tile.x, tile.y, tile.z)
ll = mercantile.xy(bounds.west, bounds.south)
ur = mercantile.xy(bounds.east, bounds.north)
extent = mapnik.Box2d(*(ll + ur))
m = mapnik.Map(256, 256)
m.srs = "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs +over"
s = mapnik.Style()
r = mapnik.Rule()
road_width = 75 # meters
pixel_size = mercantile.pixel_size(tile.z, bounds.north)
pixels = int(road_width/pixel_size) + 1
line_symbolizer = mapnik.LineSymbolizer(mapnik.Color('black'), pixels)
r.symbols.append(line_symbolizer)
s.rules.append(r)
m.append_style('RoadStyle', s)
layer = mapnik.Layer('Roads from PostGIS')
layer.srs = "+init=epsg:3857"
ROADS = """
(SELECT way
FROM planet_osm_line
WHERE roadbiking = TRUE) linestring
"""
layer.datasource = mapnik.PostGIS(host='localhost', user='mperry', password='mperry',
dbname='osm_uswest', table=ROADS, geometry_field='way')
layer.styles.append('RoadStyle')
m.layers.append(layer)
m.zoom_to_box(extent)
img = mapnik.Image(m.width, m.height)
mapnik.render(m, img)
imgpath = tile_path(os.path.join(tiledir, 'mask'), tile, 'png')
prep_dirs(imgpath)
if save_mask:
img.save(imgpath)
imgdata = np.frombuffer(img.tostring(), dtype=np.uint8).reshape((256, 256, 4))
# use alpha channel to get 0->1 scale for mask
alpha = imgdata[:,:,3] / 255.0
# invert for easy multiplication w/ strava alpha channel
# 1 = no road, keep strava heatmap values)
# 0 = road, make strava heatmap transparent
mask = 1 - alpha
return mask
def seed_outputs(bounds, zooms):
for tile in mercantile.tiles(*bounds, zooms=zooms):
print(tile)
render_offroad_tile(tile)
def heatmap_array(pngpath):
arr = image.imread(pngpath)
return arr
def adjust_alpha(rgba, mask):
rgba_alpha = rgba[:,:,3]
rgba[:,:,3] = rgba_alpha * mask
return rgba
def render_offroad_tile(tile):
mask = vecttile_mask(tile)
heatmap = heatmap_array(tile_path(os.path.join(tiledir, 'strava'), tile, 'png'))
mod = adjust_alpha(heatmap.copy(), mask)
path = tile_path(os.path.join(tiledir, 'offroad'), tile, 'png')
prep_dirs(path)
image.imsave(path, mod)
return path
def test():
bounds = -123.40, 45.47, -122.42, 46.33
zooms = [10,11,12]
print("Seeding inputs...")
seed_inputs(bounds, zooms)
print("Seeding outputs...")
seed_outputs(bounds, zooms)
def make_tile(x, y, z):
tile = mercantile.Tile(x, y, z)
# cache inputs
s = tile_url(strava, tile), tile_path(os.path.join(tiledir, 'strava'), tile, 'png')
#v = tile_url(osm_vect, tile), tile_path(os.path.join(tiledir, 'osm'), tile, 'json')
save_tile(*s)
#save_tile(*v)
# cache outputs
return render_offroad_tile(tile)
from flask import Flask, make_response
app = Flask(__name__, static_url_path='')
app.debug = True
application = app
@app.route('/offroad/<z>/<x>/<y>.png', methods = ['GET'])
def tiles(x, y, z):
x = int(x)
y = int(y)
z = int(z)
path = tile_path(os.path.join(tiledir, 'offroad'), mercantile.Tile(x, y, z), 'png')
if not os.path.exists(path):
path = make_tile(x, y, z)
with open(path, 'r') as fh:
response = make_response(fh.read())
response.mimetype = 'image/png'
return response
if __name__ == '__main__':
app.run(debug = True)