-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathgenerate_metatile.py
189 lines (152 loc) · 7.17 KB
/
generate_metatile.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
176
177
178
179
180
181
182
183
184
185
186
187
#!/usr/bin/env python
import mapnik
import sys
import math
import json
import os
import time
import regions
from PIL import Image, ImageMath
import color_to_alpha
from pysqlite2 import dbapi2 as sqlite3
try:
from osgeo import gdal
from osgeo import osr
except ImportError:
import gdal
import osr
def deg2num(lon_deg, lat_deg, zoom):
lat_rad = math.radians(lat_deg)
n = 2.0 ** zoom
xtile = int((lon_deg + 180.0) / 360.0 * n)
ytile = int((1.0 - math.log(math.tan(lat_rad) + (1 / math.cos(lat_rad))) / math.pi) / 2.0 * n)
return (xtile, ytile)
def num2deg(xtile, ytile, zoom):
n = 2.0 ** zoom
lon_deg = xtile / n * 360.0 - 180.0
lat_rad = math.atan(math.sinh(math.pi * (1 - 2 * ytile / n)))
lat_deg = math.degrees(lat_rad)
return (lon_deg, lat_deg)
def composite(size,im1,im2 = None, opts = None):
if not im2:
im2 = Image.new('RGBA', (size,size), (255, 255, 255, 255))
if opts and 'colorToAlpha' in opts:
im1 = color_to_alpha.color_to_alpha(im1,opts['colorToAlpha'])
alpha = im1.split()[-1]
if opts and 'opacity' in opts:
alpha = Image.eval(alpha,lambda a: a*opts['opacity'])
im = Image.composite(im1,im2,alpha)
return im.convert('RGB')
TILE_SIZE = 256
METATILE_ZOOM = 8 # ZOOM where the metatile size is one tile size
P_900913 = mapnik.Projection('+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')
mtileX = int(sys.argv[1])
mtileY = int(sys.argv[2])
zoom = int(sys.argv[3])
bbs = ([map(float,sys.argv[4].split(','))] if sys.argv[4] != 'regions' else regions.get(zoom)) if len(sys.argv) >= 5 else None
TILES_DIR = os.environ['TILE_PATH'] if 'TILE_PATH' in os.environ else "/tmp/tiles"
mappath = os.environ['MAPNIK_MAP_PATH']
mapfiles = os.environ['MAPNIK_MAP_FILES'].strip(';').split(';')
layer_options = json.loads(os.environ['LAYER_OPTIONS'])
if zoom == 15:
MAX_ZOOM_DIFF = 4
elif zoom == 16:
MAX_ZOOM_DIFF = 4
else:
MAX_ZOOM_DIFF = 4
fractions = 2 ** (zoom - METATILE_ZOOM - MAX_ZOOM_DIFF) if (zoom - METATILE_ZOOM) >= MAX_ZOOM_DIFF else 1
mtileSize = int(TILE_SIZE * (2 ** (zoom - METATILE_ZOOM))) / fractions
_1 = num2deg(mtileX,mtileY,METATILE_ZOOM)
_2 = num2deg(mtileX+1,mtileY+1,METATILE_ZOOM)
print "Rendering (%dx%d) subtiles." % (mtileSize,mtileSize)
sys.stdout.flush()
for xfrac in range(0,fractions):
for yfrac in range(0,fractions):
t00 = time.clock()
t00_ = time.time()
sys.stdout.flush()
im = None
k = 0;
bboxll = mapnik.Box2d(_1[0], _1[1], _2[0], _2[1])
bbox = P_900913.forward(bboxll)
bbox = mapnik.Box2d(
bbox.minx + xfrac * (bbox.maxx - bbox.minx) / fractions,
bbox.miny + yfrac * (bbox.maxy - bbox.miny) / fractions,
bbox.minx + (xfrac + 1) * (bbox.maxx - bbox.minx) / fractions,
bbox.miny + (yfrac + 1) * (bbox.maxy - bbox.miny) / fractions
)
bbox2 = P_900913.inverse(bbox)
if bbs != None:
skiped = True
for bb in bbs:
if not (max(bbox2.minx,bb[0]) >= min(bbox2.maxx,bb[2]) or max(bbox2.miny,bb[1]) >= min(bbox2.maxy,bb[3])):
skiped = False
break
if skiped:
print "SKIPED (out of bounds). (%gs/%gs)" % (time.clock() - t00,time.time() - t00_)
continue
for mapfile in mapfiles:
opts = layer_options[str(k)] if str(k) in layer_options else None
if mapfile == 'hillshade':
t0 = time.clock()
t0_ = time.time()
sys.stdout.write("\tRendering 'hillshade'...")
sys.stdout.flush()
os.system("gdal_translate -q -projwin %(x1)f %(y2)f %(x2)f %(y1)f /root/map1/data/tiles/srtm/~%(tileX)s.%(tileY)s.hillshade.tif /tmp/~%(tileX)s.%(tileY)s.hillshade.tif" % {
'x1': bbox.minx,
'y1': bbox.miny,
'x2': bbox.maxx,
'y2': bbox.maxy,
'tileX': mtileX,
'tileY': mtileY
});
tileim = Image.open('/tmp/~%s.%s.hillshade.tif' % (mtileX,mtileY))
sizeX,sizeY = tileim.size
tileim = tileim.resize(
(int(mtileSize),int(mtileSize)),
Image.ANTIALIAS if mtileSize < sizeX else Image.BILINEAR
)
lowLimit = 150
lowCompression = 2.0
highLimit = 225
highCompression = 2.5
lowCompress = lambda x: lowLimit - ((lowLimit - x) / lowCompression) if x < lowLimit else x
highCompress = lambda x: (highLimit + ((x - highLimit) / highCompression) if x > highLimit else x) + (255 - highLimit) * (1.0 - 1.0/highCompression);
gamma = lambda x,g: 255.0 * (float(x) / 255.0) ** (1.0/float(g))
tileim = Image.eval(tileim,lambda x: highCompress(lowCompress(gamma(x,1.3))))
sys.stdout.write("done. (%gs/%gs)\n" % (time.clock() - t0,time.time() - t0_))
sys.stdout.flush()
else:
t0 = time.clock()
t0_ = time.time()
sys.stdout.write("\tRendering '%s'..." % (mapfile))
sys.stdout.flush()
m = mapnik.Map(mtileSize,mtileSize)
mapnik.load_map(m, "%s/~map-%s.xml" % (mappath,mapfile), True)
m.buffer_size = 512 if mapfile == "text" else 48
m.resize(mtileSize, mtileSize)
m.zoom_to_box(bbox)
tileim = mapnik.Image(mtileSize, mtileSize)
mapnik.render(m, tileim)
tileim = Image.fromstring('RGBA',(mtileSize, mtileSize),tileim.tostring())
sys.stdout.write("done. (%gs/%gs)\n" % (time.clock() - t0,time.time() - t0_))
sys.stdout.flush()
im = composite(mtileSize,tileim,im,opts)
k += 1
t0 = time.clock()
t0_ = time.time()
sys.stdout.write("\tCroping tiles...")
sys.stdout.flush()
im.convert('RGB')
for i in range(mtileSize/TILE_SIZE):
for j in range(mtileSize/TILE_SIZE):
im2 = im.crop((TILE_SIZE*i, TILE_SIZE*j,TILE_SIZE*(i+1),TILE_SIZE*(j+1)))
tileX = mtileX * 2 ** (zoom - METATILE_ZOOM) + xfrac * mtileSize / TILE_SIZE + i
tileY = (mtileY + 1) * 2 ** (zoom - METATILE_ZOOM) - (yfrac + 1) * mtileSize / TILE_SIZE + j
if not os.path.isdir("%s/%s/%s" % (TILES_DIR,zoom,tileX)):
os.makedirs("%s/%s/%s" % (TILES_DIR,zoom,tileX))
im2.save("%s/%s/%s/%s.jpg" % (TILES_DIR,zoom,tileX,tileY),'JPEG',quality=85)
sys.stdout.write("done. (%gs/%gs)\n" % (time.clock() - t0,time.time() - t0_))
sys.stdout.flush()
print "DONE. (%gs/%gs)" % (time.clock() - t00,time.time() - t00_)
sys.stdout.flush()