source: src/common/bin/gdal2tiles-gnuboat.py@ 5e16955

debian/bullseye
Last change on this file since 5e16955 was 9f5877d, checked in by Joachim Langenbach <joachim.langenbach@…>, 7 years ago

Moved all functions needed to generate raster data and tiles into new class TileGenerator in gnuboat_common

  • Property mode set to 100755
File size: 117.5 KB
Line 
1#!/usr/bin/python3
2# -*- coding: utf-8 -*-
3# ******************************************************************************
4# $Id: gdal2tiles.py 17c3fa6fefeb3b305a27ff6ed1590145815d7ee3 2019-03-14 22:12:27 +0100 Even Rouault $
5#
6# Project: Google Summer of Code 2007, 2008 (http://code.google.com/soc/)
7# Support: BRGM (http://www.brgm.fr)
8# Purpose: Convert a raster into TMS (Tile Map Service) tiles in a directory.
9# - generate Google Earth metadata (KML SuperOverlay)
10# - generate simple HTML viewer based on Google Maps and OpenLayers
11# - support of global tiles (Spherical Mercator) for compatibility
12# with interactive web maps a la Google Maps
13# Author: Klokan Petr Pridal, klokan at klokan dot cz
14# Web: http://www.klokan.cz/projects/gdal2tiles/
15# GUI: http://www.maptiler.org/
16#
17###############################################################################
18# Copyright (c) 2008, Klokan Petr Pridal
19# Copyright (c) 2010-2013, Even Rouault <even dot rouault at mines-paris dot org>
20#
21# Permission is hereby granted, free of charge, to any person obtaining a
22# copy of this software and associated documentation files (the "Software"),
23# to deal in the Software without restriction, including without limitation
24# the rights to use, copy, modify, merge, publish, distribute, sublicense,
25# and/or sell copies of the Software, and to permit persons to whom the
26# Software is furnished to do so, subject to the following conditions:
27#
28# The above copyright notice and this permission notice shall be included
29# in all copies or substantial portions of the Software.
30#
31# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
32# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
33# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
34# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
35# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
36# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
37# DEALINGS IN THE SOFTWARE.
38# ******************************************************************************
39
40from __future__ import print_function, division
41
42import math
43from multiprocessing import Pool
44from functools import partial
45import os
46import tempfile
47import threading
48import shutil
49import sys
50from uuid import uuid4
51from xml.etree import ElementTree
52
53from osgeo import gdal
54from osgeo import osr
55
56try:
57 from PIL import Image
58 import numpy
59 import osgeo.gdal_array as gdalarray
60 numpy_available = True
61except ImportError:
62 # 'antialias' resampling is not available
63 numpy_available = False
64
65__version__ = "$Id: gdal2tiles.py 17c3fa6fefeb3b305a27ff6ed1590145815d7ee3 2019-03-14 22:12:27 +0100 Even Rouault $"
66
67resampling_list = ('average', 'near', 'bilinear', 'cubic', 'cubicspline', 'lanczos', 'antialias')
68profile_list = ('mercator', 'geodetic', 'raster')
69webviewer_list = ('all', 'google', 'openlayers', 'leaflet', 'none')
70
71threadLocal = threading.local()
72
73# =============================================================================
74# =============================================================================
75# =============================================================================
76
77__doc__globalmaptiles = """
78globalmaptiles.py
79
80Global Map Tiles as defined in Tile Map Service (TMS) Profiles
81==============================================================
82
83Functions necessary for generation of global tiles used on the web.
84It contains classes implementing coordinate conversions for:
85
86 - GlobalMercator (based on EPSG:3857)
87 for Google Maps, Yahoo Maps, Bing Maps compatible tiles
88 - GlobalGeodetic (based on EPSG:4326)
89 for OpenLayers Base Map and Google Earth compatible tiles
90
91More info at:
92
93http://wiki.osgeo.org/wiki/Tile_Map_Service_Specification
94http://wiki.osgeo.org/wiki/WMS_Tiling_Client_Recommendation
95http://msdn.microsoft.com/en-us/library/bb259689.aspx
96http://code.google.com/apis/maps/documentation/overlays.html#Google_Maps_Coordinates
97
98Created by Klokan Petr Pridal on 2008-07-03.
99Google Summer of Code 2008, project GDAL2Tiles for OSGEO.
100
101In case you use this class in your product, translate it to another language
102or find it useful for your project please let me know.
103My email: klokan at klokan dot cz.
104I would like to know where it was used.
105
106Class is available under the open-source GDAL license (www.gdal.org).
107"""
108
109MAXZOOMLEVEL = 32
110
111
112class GlobalMercator(object):
113 r"""
114 TMS Global Mercator Profile
115 ---------------------------
116
117 Functions necessary for generation of tiles in Spherical Mercator projection,
118 EPSG:3857.
119
120 Such tiles are compatible with Google Maps, Bing Maps, Yahoo Maps,
121 UK Ordnance Survey OpenSpace API, ...
122 and you can overlay them on top of base maps of those web mapping applications.
123
124 Pixel and tile coordinates are in TMS notation (origin [0,0] in bottom-left).
125
126 What coordinate conversions do we need for TMS Global Mercator tiles::
127
128 LatLon <-> Meters <-> Pixels <-> Tile
129
130 WGS84 coordinates Spherical Mercator Pixels in pyramid Tiles in pyramid
131 lat/lon XY in meters XY pixels Z zoom XYZ from TMS
132 EPSG:4326 EPSG:387
133 .----. --------- -- TMS
134 / \ <-> | | <-> /----/ <-> Google
135 \ / | | /--------/ QuadTree
136 ----- --------- /------------/
137 KML, public WebMapService Web Clients TileMapService
138
139 What is the coordinate extent of Earth in EPSG:3857?
140
141 [-20037508.342789244, -20037508.342789244, 20037508.342789244, 20037508.342789244]
142 Constant 20037508.342789244 comes from the circumference of the Earth in meters,
143 which is 40 thousand kilometers, the coordinate origin is in the middle of extent.
144 In fact you can calculate the constant as: 2 * math.pi * 6378137 / 2.0
145 $ echo 180 85 | gdaltransform -s_srs EPSG:4326 -t_srs EPSG:3857
146 Polar areas with abs(latitude) bigger then 85.05112878 are clipped off.
147
148 What are zoom level constants (pixels/meter) for pyramid with EPSG:3857?
149
150 whole region is on top of pyramid (zoom=0) covered by 256x256 pixels tile,
151 every lower zoom level resolution is always divided by two
152 initialResolution = 20037508.342789244 * 2 / 256 = 156543.03392804062
153
154 What is the difference between TMS and Google Maps/QuadTree tile name convention?
155
156 The tile raster itself is the same (equal extent, projection, pixel size),
157 there is just different identification of the same raster tile.
158 Tiles in TMS are counted from [0,0] in the bottom-left corner, id is XYZ.
159 Google placed the origin [0,0] to the top-left corner, reference is XYZ.
160 Microsoft is referencing tiles by a QuadTree name, defined on the website:
161 http://msdn2.microsoft.com/en-us/library/bb259689.aspx
162
163 The lat/lon coordinates are using WGS84 datum, yes?
164
165 Yes, all lat/lon we are mentioning should use WGS84 Geodetic Datum.
166 Well, the web clients like Google Maps are projecting those coordinates by
167 Spherical Mercator, so in fact lat/lon coordinates on sphere are treated as if
168 the were on the WGS84 ellipsoid.
169
170 From MSDN documentation:
171 To simplify the calculations, we use the spherical form of projection, not
172 the ellipsoidal form. Since the projection is used only for map display,
173 and not for displaying numeric coordinates, we don't need the extra precision
174 of an ellipsoidal projection. The spherical projection causes approximately
175 0.33 percent scale distortion in the Y direction, which is not visually
176 noticeable.
177
178 How do I create a raster in EPSG:3857 and convert coordinates with PROJ.4?
179
180 You can use standard GIS tools like gdalwarp, cs2cs or gdaltransform.
181 All of the tools supports -t_srs 'epsg:3857'.
182
183 For other GIS programs check the exact definition of the projection:
184 More info at http://spatialreference.org/ref/user/google-projection/
185 The same projection is designated as EPSG:3857. WKT definition is in the
186 official EPSG database.
187
188 Proj4 Text:
189 +proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0
190 +k=1.0 +units=m +nadgrids=@null +no_defs
191
192 Human readable WKT format of EPSG:3857:
193 PROJCS["Google Maps Global Mercator",
194 GEOGCS["WGS 84",
195 DATUM["WGS_1984",
196 SPHEROID["WGS 84",6378137,298.257223563,
197 AUTHORITY["EPSG","7030"]],
198 AUTHORITY["EPSG","6326"]],
199 PRIMEM["Greenwich",0],
200 UNIT["degree",0.0174532925199433],
201 AUTHORITY["EPSG","4326"]],
202 PROJECTION["Mercator_1SP"],
203 PARAMETER["central_meridian",0],
204 PARAMETER["scale_factor",1],
205 PARAMETER["false_easting",0],
206 PARAMETER["false_northing",0],
207 UNIT["metre",1,
208 AUTHORITY["EPSG","9001"]]]
209 """
210
211 def __init__(self, tile_size=256):
212 "Initialize the TMS Global Mercator pyramid"
213 self.tile_size = tile_size
214 self.initialResolution = 2 * math.pi * 6378137 / self.tile_size
215 # 156543.03392804062 for tile_size 256 pixels
216 self.originShift = 2 * math.pi * 6378137 / 2.0
217 # 20037508.342789244
218
219 def LatLonToMeters(self, lat, lon):
220 "Converts given lat/lon in WGS84 Datum to XY in Spherical Mercator EPSG:3857"
221
222 mx = lon * self.originShift / 180.0
223 my = math.log(math.tan((90 + lat) * math.pi / 360.0)) / (math.pi / 180.0)
224
225 my = my * self.originShift / 180.0
226 return mx, my
227
228 def MetersToLatLon(self, mx, my):
229 "Converts XY point from Spherical Mercator EPSG:3857 to lat/lon in WGS84 Datum"
230
231 lon = (mx / self.originShift) * 180.0
232 lat = (my / self.originShift) * 180.0
233
234 lat = 180 / math.pi * (2 * math.atan(math.exp(lat * math.pi / 180.0)) - math.pi / 2.0)
235 return lat, lon
236
237 def PixelsToMeters(self, px, py, zoom):
238 "Converts pixel coordinates in given zoom level of pyramid to EPSG:3857"
239
240 res = self.Resolution(zoom)
241 mx = px * res - self.originShift
242 my = py * res - self.originShift
243 return mx, my
244
245 def MetersToPixels(self, mx, my, zoom):
246 "Converts EPSG:3857 to pyramid pixel coordinates in given zoom level"
247
248 res = self.Resolution(zoom)
249 px = (mx + self.originShift) / res
250 py = (my + self.originShift) / res
251 return px, py
252
253 def PixelsToTile(self, px, py):
254 "Returns a tile covering region in given pixel coordinates"
255
256 tx = int(math.ceil(px / float(self.tile_size)) - 1)
257 ty = int(math.ceil(py / float(self.tile_size)) - 1)
258 return tx, ty
259
260 def PixelsToRaster(self, px, py, zoom):
261 "Move the origin of pixel coordinates to top-left corner"
262
263 mapSize = self.tile_size << zoom
264 return px, mapSize - py
265
266 def MetersToTile(self, mx, my, zoom):
267 "Returns tile for given mercator coordinates"
268
269 px, py = self.MetersToPixels(mx, my, zoom)
270 return self.PixelsToTile(px, py)
271
272 def TileBounds(self, tx, ty, zoom):
273 "Returns bounds of the given tile in EPSG:3857 coordinates"
274
275 minx, miny = self.PixelsToMeters(tx * self.tile_size, ty * self.tile_size, zoom)
276 maxx, maxy = self.PixelsToMeters((tx + 1) * self.tile_size, (ty + 1) * self.tile_size, zoom)
277 return (minx, miny, maxx, maxy)
278
279 def TileLatLonBounds(self, tx, ty, zoom):
280 "Returns bounds of the given tile in latitude/longitude using WGS84 datum"
281
282 bounds = self.TileBounds(tx, ty, zoom)
283 minLat, minLon = self.MetersToLatLon(bounds[0], bounds[1])
284 maxLat, maxLon = self.MetersToLatLon(bounds[2], bounds[3])
285
286 return (minLat, minLon, maxLat, maxLon)
287
288 def Resolution(self, zoom):
289 "Resolution (meters/pixel) for given zoom level (measured at Equator)"
290
291 # return (2 * math.pi * 6378137) / (self.tile_size * 2**zoom)
292 return self.initialResolution / (2**zoom)
293
294 def ZoomForPixelSize(self, pixelSize):
295 "Maximal scaledown zoom of the pyramid closest to the pixelSize."
296
297 for i in range(MAXZOOMLEVEL):
298 if pixelSize > self.Resolution(i):
299 return max(0, i - 1) # We don't want to scale up
300 return MAXZOOMLEVEL - 1
301
302 def GoogleTile(self, tx, ty, zoom):
303 "Converts TMS tile coordinates to Google Tile coordinates"
304
305 # coordinate origin is moved from bottom-left to top-left corner of the extent
306 return tx, (2**zoom - 1) - ty
307
308 def QuadTree(self, tx, ty, zoom):
309 "Converts TMS tile coordinates to Microsoft QuadTree"
310
311 quadKey = ""
312 ty = (2**zoom - 1) - ty
313 for i in range(zoom, 0, -1):
314 digit = 0
315 mask = 1 << (i - 1)
316 if (tx & mask) != 0:
317 digit += 1
318 if (ty & mask) != 0:
319 digit += 2
320 quadKey += str(digit)
321
322 return quadKey
323
324
325class GlobalGeodetic(object):
326 r"""
327 TMS Global Geodetic Profile
328 ---------------------------
329
330 Functions necessary for generation of global tiles in Plate Carre projection,
331 EPSG:4326, "unprojected profile".
332
333 Such tiles are compatible with Google Earth (as any other EPSG:4326 rasters)
334 and you can overlay the tiles on top of OpenLayers base map.
335
336 Pixel and tile coordinates are in TMS notation (origin [0,0] in bottom-left).
337
338 What coordinate conversions do we need for TMS Global Geodetic tiles?
339
340 Global Geodetic tiles are using geodetic coordinates (latitude,longitude)
341 directly as planar coordinates XY (it is also called Unprojected or Plate
342 Carre). We need only scaling to pixel pyramid and cutting to tiles.
343 Pyramid has on top level two tiles, so it is not square but rectangle.
344 Area [-180,-90,180,90] is scaled to 512x256 pixels.
345 TMS has coordinate origin (for pixels and tiles) in bottom-left corner.
346 Rasters are in EPSG:4326 and therefore are compatible with Google Earth.
347
348 LatLon <-> Pixels <-> Tiles
349
350 WGS84 coordinates Pixels in pyramid Tiles in pyramid
351 lat/lon XY pixels Z zoom XYZ from TMS
352 EPSG:4326
353 .----. ----
354 / \ <-> /--------/ <-> TMS
355 \ / /--------------/
356 ----- /--------------------/
357 WMS, KML Web Clients, Google Earth TileMapService
358 """
359
360 def __init__(self, tmscompatible, tile_size=256):
361 self.tile_size = tile_size
362 if tmscompatible is not None:
363 # Defaults the resolution factor to 0.703125 (2 tiles @ level 0)
364 # Adhers to OSGeo TMS spec
365 # http://wiki.osgeo.org/wiki/Tile_Map_Service_Specification#global-geodetic
366 self.resFact = 180.0 / self.tile_size
367 else:
368 # Defaults the resolution factor to 1.40625 (1 tile @ level 0)
369 # Adheres OpenLayers, MapProxy, etc default resolution for WMTS
370 self.resFact = 360.0 / self.tile_size
371
372 def LonLatToPixels(self, lon, lat, zoom):
373 "Converts lon/lat to pixel coordinates in given zoom of the EPSG:4326 pyramid"
374
375 res = self.resFact / 2**zoom
376 px = (180 + lon) / res
377 py = (90 + lat) / res
378 return px, py
379
380 def PixelsToTile(self, px, py):
381 "Returns coordinates of the tile covering region in pixel coordinates"
382
383 tx = int(math.ceil(px / float(self.tile_size)) - 1)
384 ty = int(math.ceil(py / float(self.tile_size)) - 1)
385 return tx, ty
386
387 def LonLatToTile(self, lon, lat, zoom):
388 "Returns the tile for zoom which covers given lon/lat coordinates"
389
390 px, py = self.LonLatToPixels(lon, lat, zoom)
391 return self.PixelsToTile(px, py)
392
393 def Resolution(self, zoom):
394 "Resolution (arc/pixel) for given zoom level (measured at Equator)"
395
396 return self.resFact / 2**zoom
397
398 def ZoomForPixelSize(self, pixelSize):
399 "Maximal scaledown zoom of the pyramid closest to the pixelSize."
400
401 for i in range(MAXZOOMLEVEL):
402 if pixelSize > self.Resolution(i):
403 return max(0, i - 1) # We don't want to scale up
404 return MAXZOOMLEVEL - 1
405
406 def TileBounds(self, tx, ty, zoom):
407 "Returns bounds of the given tile"
408 res = self.resFact / 2**zoom
409 return (
410 tx * self.tile_size * res - 180,
411 ty * self.tile_size * res - 90,
412 (tx + 1) * self.tile_size * res - 180,
413 (ty + 1) * self.tile_size * res - 90
414 )
415
416 def TileLatLonBounds(self, tx, ty, zoom):
417 "Returns bounds of the given tile in the SWNE form"
418 b = self.TileBounds(tx, ty, zoom)
419 return (b[1], b[0], b[3], b[2])
420
421
422class Zoomify(object):
423 """
424 Tiles compatible with the Zoomify viewer
425 ----------------------------------------
426 """
427
428 def __init__(self, width, height, tile_size=256, tileformat='jpg'):
429 """Initialization of the Zoomify tile tree"""
430
431 self.tile_size = tile_size
432 self.tileformat = tileformat
433 imagesize = (width, height)
434 tiles = (math.ceil(width / tile_size), math.ceil(height / tile_size))
435
436 # Size (in tiles) for each tier of pyramid.
437 self.tierSizeInTiles = []
438 self.tierSizeInTiles.append(tiles)
439
440 # Image size in pixels for each pyramid tierself
441 self.tierImageSize = []
442 self.tierImageSize.append(imagesize)
443
444 while (imagesize[0] > tile_size or imagesize[1] > tile_size):
445 imagesize = (math.floor(imagesize[0] / 2), math.floor(imagesize[1] / 2))
446 tiles = (math.ceil(imagesize[0] / tile_size), math.ceil(imagesize[1] / tile_size))
447 self.tierSizeInTiles.append(tiles)
448 self.tierImageSize.append(imagesize)
449
450 self.tierSizeInTiles.reverse()
451 self.tierImageSize.reverse()
452
453 # Depth of the Zoomify pyramid, number of tiers (zoom levels)
454 self.numberOfTiers = len(self.tierSizeInTiles)
455
456 # Number of tiles up to the given tier of pyramid.
457 self.tileCountUpToTier = []
458 self.tileCountUpToTier[0] = 0
459 for i in range(1, self.numberOfTiers + 1):
460 self.tileCountUpToTier.append(
461 self.tierSizeInTiles[i - 1][0] * self.tierSizeInTiles[i - 1][1] +
462 self.tileCountUpToTier[i - 1]
463 )
464
465 def tilefilename(self, x, y, z):
466 """Returns filename for tile with given coordinates"""
467
468 tileIndex = x + y * self.tierSizeInTiles[z][0] + self.tileCountUpToTier[z]
469 return os.path.join("TileGroup%.0f" % math.floor(tileIndex / 256),
470 "%s-%s-%s.%s" % (z, x, y, self.tileformat))
471
472
473class GDALError(Exception):
474 pass
475
476
477def exit_with_error(message, details=""):
478 # Message printing and exit code kept from the way it worked using the OptionParser (in case
479 # someone parses the error output)
480 sys.stderr.write("Usage: gdal2tiles.py [options] input_file [output]\n\n")
481 sys.stderr.write("gdal2tiles.py: error: %s\n" % message)
482 if details:
483 sys.stderr.write("\n\n%s\n" % details)
484
485 sys.exit(2)
486
487
488def generate_kml(tx, ty, tz, tileext, tile_size, tileswne, options, children=None, **args):
489 """
490 Template for the KML. Returns filled string.
491 """
492 if not children:
493 children = []
494
495 args['tx'], args['ty'], args['tz'] = tx, ty, tz
496 args['tileformat'] = tileext
497 if 'tile_size' not in args:
498 args['tile_size'] = tile_size
499
500 if 'minlodpixels' not in args:
501 args['minlodpixels'] = int(args['tile_size'] / 2)
502 if 'maxlodpixels' not in args:
503 args['maxlodpixels'] = int(args['tile_size'] * 8)
504 if children == []:
505 args['maxlodpixels'] = -1
506
507 if tx is None:
508 tilekml = False
509 args['title'] = options.title
510 else:
511 tilekml = True
512 args['title'] = "%d/%d/%d.kml" % (tz, tx, ty)
513 args['south'], args['west'], args['north'], args['east'] = tileswne(tx, ty, tz)
514
515 if tx == 0:
516 args['drawOrder'] = 2 * tz + 1
517 elif tx is not None:
518 args['drawOrder'] = 2 * tz
519 else:
520 args['drawOrder'] = 0
521
522 url = options.url
523 if not url:
524 if tilekml:
525 url = "../../"
526 else:
527 url = ""
528
529 s = """<?xml version="1.0" encoding="utf-8"?>
530<kml xmlns="http://www.opengis.net/kml/2.2">
531 <Document>
532 <name>%(title)s</name>
533 <description></description>
534 <Style>
535 <ListStyle id="hideChildren">
536 <listItemType>checkHideChildren</listItemType>
537 </ListStyle>
538 </Style>""" % args
539 if tilekml:
540 s += """
541 <Region>
542 <LatLonAltBox>
543 <north>%(north).14f</north>
544 <south>%(south).14f</south>
545 <east>%(east).14f</east>
546 <west>%(west).14f</west>
547 </LatLonAltBox>
548 <Lod>
549 <minLodPixels>%(minlodpixels)d</minLodPixels>
550 <maxLodPixels>%(maxlodpixels)d</maxLodPixels>
551 </Lod>
552 </Region>
553 <GroundOverlay>
554 <drawOrder>%(drawOrder)d</drawOrder>
555 <Icon>
556 <href>%(ty)d.%(tileformat)s</href>
557 </Icon>
558 <LatLonBox>
559 <north>%(north).14f</north>
560 <south>%(south).14f</south>
561 <east>%(east).14f</east>
562 <west>%(west).14f</west>
563 </LatLonBox>
564 </GroundOverlay>
565""" % args
566
567 for cx, cy, cz in children:
568 csouth, cwest, cnorth, ceast = tileswne(cx, cy, cz)
569 s += """
570 <NetworkLink>
571 <name>%d/%d/%d.%s</name>
572 <Region>
573 <LatLonAltBox>
574 <north>%.14f</north>
575 <south>%.14f</south>
576 <east>%.14f</east>
577 <west>%.14f</west>
578 </LatLonAltBox>
579 <Lod>
580 <minLodPixels>%d</minLodPixels>
581 <maxLodPixels>-1</maxLodPixels>
582 </Lod>
583 </Region>
584 <Link>
585 <href>%s%d/%d/%d.kml</href>
586 <viewRefreshMode>onRegion</viewRefreshMode>
587 <viewFormat/>
588 </Link>
589 </NetworkLink>
590 """ % (cz, cx, cy, args['tileformat'], cnorth, csouth, ceast, cwest,
591 args['minlodpixels'], url, cz, cx, cy)
592
593 s += """ </Document>
594</kml>
595 """
596 return s
597
598
599def scale_query_to_tile(dsquery, dstile, tiledriver, options, tilefilename=''):
600 """Scales down query dataset to the tile dataset"""
601
602 querysize = dsquery.RasterXSize
603 tile_size = dstile.RasterXSize
604 tilebands = dstile.RasterCount
605
606 if options.resampling == 'average':
607
608 # Function: gdal.RegenerateOverview()
609 for i in range(1, tilebands + 1):
610 # Black border around NODATA
611 res = gdal.RegenerateOverview(dsquery.GetRasterBand(i), dstile.GetRasterBand(i),
612 'average')
613 if res != 0:
614 exit_with_error("RegenerateOverview() failed on %s, error %d" % (
615 tilefilename, res))
616
617 elif options.resampling == 'antialias' and numpy_available:
618
619 # Scaling by PIL (Python Imaging Library) - improved Lanczos
620 array = numpy.zeros((querysize, querysize, tilebands), numpy.uint8)
621 for i in range(tilebands):
622 array[:, :, i] = gdalarray.BandReadAsArray(dsquery.GetRasterBand(i + 1),
623 0, 0, querysize, querysize)
624 im = Image.fromarray(array, 'RGBA') # Always four bands
625 im1 = im.resize((tile_size, tile_size), Image.ANTIALIAS)
626 if os.path.exists(tilefilename):
627 im0 = Image.open(tilefilename)
628 im1 = Image.composite(im1, im0, im1)
629 im1.save(tilefilename, tiledriver)
630
631 else:
632
633 if options.resampling == 'near':
634 gdal_resampling = gdal.GRA_NearestNeighbour
635
636 elif options.resampling == 'bilinear':
637 gdal_resampling = gdal.GRA_Bilinear
638
639 elif options.resampling == 'cubic':
640 gdal_resampling = gdal.GRA_Cubic
641
642 elif options.resampling == 'cubicspline':
643 gdal_resampling = gdal.GRA_CubicSpline
644
645 elif options.resampling == 'lanczos':
646 gdal_resampling = gdal.GRA_Lanczos
647
648 # Other algorithms are implemented by gdal.ReprojectImage().
649 dsquery.SetGeoTransform((0.0, tile_size / float(querysize), 0.0, 0.0, 0.0,
650 tile_size / float(querysize)))
651 dstile.SetGeoTransform((0.0, 1.0, 0.0, 0.0, 0.0, 1.0))
652
653 res = gdal.ReprojectImage(dsquery, dstile, None, None, gdal_resampling)
654 if res != 0:
655 exit_with_error("ReprojectImage() failed on %s, error %d" % (tilefilename, res))
656
657
658def setup_no_data_values(input_dataset, options):
659 """
660 Extract the NODATA values from the dataset or use the passed arguments as override if any
661 """
662 in_nodata = []
663 if options.srcnodata:
664 nds = list(map(float, options.srcnodata.split(',')))
665 if len(nds) < input_dataset.RasterCount:
666 in_nodata = (nds * input_dataset.RasterCount)[:input_dataset.RasterCount]
667 else:
668 in_nodata = nds
669 else:
670 for i in range(1, input_dataset.RasterCount + 1):
671 raster_no_data = input_dataset.GetRasterBand(i).GetNoDataValue()
672 if raster_no_data is not None:
673 in_nodata.append(raster_no_data)
674
675 if options.verbose:
676 print("NODATA: %s" % in_nodata)
677
678 return in_nodata
679
680
681def setup_input_srs(input_dataset, options):
682 """
683 Determines and returns the Input Spatial Reference System (SRS) as an osr object and as a
684 WKT representation
685
686 Uses in priority the one passed in the command line arguments. If None, tries to extract them
687 from the input dataset
688 """
689
690 input_srs = None
691 input_srs_wkt = None
692
693 if options.s_srs:
694 input_srs = osr.SpatialReference()
695 input_srs.SetFromUserInput(options.s_srs)
696 input_srs_wkt = input_srs.ExportToWkt()
697 else:
698 input_srs_wkt = input_dataset.GetProjection()
699 if not input_srs_wkt and input_dataset.GetGCPCount() != 0:
700 input_srs_wkt = input_dataset.GetGCPProjection()
701 if input_srs_wkt:
702 input_srs = osr.SpatialReference()
703 input_srs.ImportFromWkt(input_srs_wkt)
704
705 input_srs.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER)
706 return input_srs, input_srs_wkt
707
708
709def setup_output_srs(input_srs, options):
710 """
711 Setup the desired SRS (based on options)
712 """
713 output_srs = osr.SpatialReference()
714 output_srs.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER)
715
716 if options.profile == 'mercator':
717 output_srs.ImportFromEPSG(3857)
718 elif options.profile == 'geodetic':
719 output_srs.ImportFromEPSG(4326)
720 else:
721 output_srs = input_srs
722
723 return output_srs
724
725
726def has_georeference(dataset):
727 return (dataset.GetGeoTransform() != (0.0, 1.0, 0.0, 0.0, 0.0, 1.0) or
728 dataset.GetGCPCount() != 0)
729
730
731def reproject_dataset(from_dataset, from_srs, to_srs, options=None):
732 """
733 Returns the input dataset in the expected "destination" SRS.
734 If the dataset is already in the correct SRS, returns it unmodified
735 """
736 if not from_srs or not to_srs:
737 raise GDALError("from and to SRS must be defined to reproject the dataset")
738
739 if (from_srs.ExportToProj4() != to_srs.ExportToProj4()) or (from_dataset.GetGCPCount() != 0):
740 to_dataset = gdal.AutoCreateWarpedVRT(from_dataset,
741 from_srs.ExportToWkt(), to_srs.ExportToWkt())
742
743 if options and options.verbose:
744 print("Warping of the raster by AutoCreateWarpedVRT (result saved into 'tiles.vrt')")
745 to_dataset.GetDriver().CreateCopy("tiles.vrt", to_dataset)
746
747 return to_dataset
748 else:
749 return from_dataset
750
751
752def add_gdal_warp_options_to_string(vrt_string, warp_options):
753 if not warp_options:
754 return vrt_string
755
756 vrt_root = ElementTree.fromstring(vrt_string)
757 options = vrt_root.find("GDALWarpOptions")
758
759 if options is None:
760 return vrt_string
761
762 for key, value in warp_options.items():
763 tb = ElementTree.TreeBuilder()
764 tb.start("Option", {"name": key})
765 tb.data(value)
766 tb.end("Option")
767 elem = tb.close()
768 options.insert(0, elem)
769
770 return ElementTree.tostring(vrt_root).decode()
771
772
773def update_no_data_values(warped_vrt_dataset, nodata_values, options=None):
774 """
775 Takes an array of NODATA values and forces them on the WarpedVRT file dataset passed
776 """
777 # TODO: gbataille - Seems that I forgot tests there
778 assert nodata_values != []
779
780 vrt_string = warped_vrt_dataset.GetMetadata("xml:VRT")[0]
781
782 vrt_string = add_gdal_warp_options_to_string(
783 vrt_string, {"INIT_DEST": "NO_DATA", "UNIFIED_SRC_NODATA": "YES"})
784
785# TODO: gbataille - check the need for this replacement. Seems to work without
786# # replace BandMapping tag for NODATA bands....
787# for i in range(len(nodata_values)):
788# s = s.replace(
789# '<BandMapping src="%i" dst="%i"/>' % ((i+1), (i+1)),
790# """
791# <BandMapping src="%i" dst="%i">
792# <SrcNoDataReal>%i</SrcNoDataReal>
793# <SrcNoDataImag>0</SrcNoDataImag>
794# <DstNoDataReal>%i</DstNoDataReal>
795# <DstNoDataImag>0</DstNoDataImag>
796# </BandMapping>
797# """ % ((i+1), (i+1), nodata_values[i], nodata_values[i]))
798
799 corrected_dataset = gdal.Open(vrt_string)
800
801 # set NODATA_VALUE metadata
802 corrected_dataset.SetMetadataItem(
803 'NODATA_VALUES', ' '.join([str(i) for i in nodata_values]))
804
805 if options and options.verbose:
806 print("Modified warping result saved into 'tiles1.vrt'")
807
808 with open("tiles1.vrt", "w") as f:
809 f.write(corrected_dataset.GetMetadata("xml:VRT")[0])
810
811 return corrected_dataset
812
813
814def add_alpha_band_to_string_vrt(vrt_string):
815 # TODO: gbataille - Old code speak of this being equivalent to gdalwarp -dstalpha
816 # To be checked
817
818 vrt_root = ElementTree.fromstring(vrt_string)
819
820 index = 0
821 nb_bands = 0
822 for subelem in list(vrt_root):
823 if subelem.tag == "VRTRasterBand":
824 nb_bands += 1
825 color_node = subelem.find("./ColorInterp")
826 if color_node is not None and color_node.text == "Alpha":
827 raise Exception("Alpha band already present")
828 else:
829 if nb_bands:
830 # This means that we are one element after the Band definitions
831 break
832
833 index += 1
834
835 tb = ElementTree.TreeBuilder()
836 tb.start("VRTRasterBand",
837 {'dataType': "Byte", "band": str(nb_bands + 1), "subClass": "VRTWarpedRasterBand"})
838 tb.start("ColorInterp", {})
839 tb.data("Alpha")
840 tb.end("ColorInterp")
841 tb.end("VRTRasterBand")
842 elem = tb.close()
843
844 vrt_root.insert(index, elem)
845
846 warp_options = vrt_root.find(".//GDALWarpOptions")
847 tb = ElementTree.TreeBuilder()
848 tb.start("DstAlphaBand", {})
849 tb.data(str(nb_bands + 1))
850 tb.end("DstAlphaBand")
851 elem = tb.close()
852 warp_options.append(elem)
853
854 # TODO: gbataille - this is a GDALWarpOptions. Why put it in a specific place?
855 tb = ElementTree.TreeBuilder()
856 tb.start("Option", {"name": "INIT_DEST"})
857 tb.data("0")
858 tb.end("Option")
859 elem = tb.close()
860 warp_options.append(elem)
861
862 return ElementTree.tostring(vrt_root).decode()
863
864
865def update_alpha_value_for_non_alpha_inputs(warped_vrt_dataset, options=None):
866 """
867 Handles dataset with 1 or 3 bands, i.e. without alpha channel, in the case the nodata value has
868 not been forced by options
869 """
870 if warped_vrt_dataset.RasterCount in [1, 3]:
871
872 vrt_string = warped_vrt_dataset.GetMetadata("xml:VRT")[0]
873
874 vrt_string = add_alpha_band_to_string_vrt(vrt_string)
875
876 warped_vrt_dataset = gdal.Open(vrt_string)
877
878 if options and options.verbose:
879 print("Modified -dstalpha warping result saved into 'tiles1.vrt'")
880
881 with open("tiles1.vrt", "w") as f:
882 f.write(warped_vrt_dataset.GetMetadata("xml:VRT")[0])
883
884 return warped_vrt_dataset
885
886
887def nb_data_bands(dataset):
888 """
889 Return the number of data (non-alpha) bands of a gdal dataset
890 """
891 alphaband = dataset.GetRasterBand(1).GetMaskBand()
892 if ((alphaband.GetMaskFlags() & gdal.GMF_ALPHA) or
893 dataset.RasterCount == 4 or
894 dataset.RasterCount == 2):
895 return dataset.RasterCount - 1
896 return dataset.RasterCount
897
898def create_base_tile(tile_job_info, tile_detail):
899
900 dataBandsCount = tile_job_info.nb_data_bands
901 output = tile_job_info.output_file_path
902 tileext = tile_job_info.tile_extension
903 tile_size = tile_job_info.tile_size
904 options = tile_job_info.options
905
906 tilebands = dataBandsCount + 1
907
908 cached_ds = getattr(threadLocal, 'cached_ds', None)
909 if cached_ds and cached_ds.GetDescription() == tile_job_info.src_file:
910 ds = cached_ds
911 else:
912 ds = gdal.Open(tile_job_info.src_file, gdal.GA_ReadOnly)
913 threadLocal.cached_ds = ds
914
915 mem_drv = gdal.GetDriverByName('MEM')
916 out_drv = gdal.GetDriverByName(tile_job_info.tile_driver)
917 alphaband = ds.GetRasterBand(1).GetMaskBand()
918
919 tx = tile_detail.tx
920 ty = tile_detail.ty
921 tz = tile_detail.tz
922 rx = tile_detail.rx
923 ry = tile_detail.ry
924 rxsize = tile_detail.rxsize
925 rysize = tile_detail.rysize
926 wx = tile_detail.wx
927 wy = tile_detail.wy
928 wxsize = tile_detail.wxsize
929 wysize = tile_detail.wysize
930 querysize = tile_detail.querysize
931
932 # Tile dataset in memory
933 tilefilename = os.path.join(
934 output, str(tz), str(tx), "%s.%s" % (ty, tileext))
935 dstile = mem_drv.Create('', tile_size, tile_size, tilebands)
936
937 data = alpha = None
938
939 if options.verbose:
940 print("\tReadRaster Extent: ",
941 (rx, ry, rxsize, rysize), (wx, wy, wxsize, wysize))
942
943 # Query is in 'nearest neighbour' but can be bigger in then the tile_size
944 # We scale down the query to the tile_size by supplied algorithm.
945
946 if rxsize != 0 and rysize != 0 and wxsize != 0 and wysize != 0:
947 alpha = alphaband.ReadRaster(rx, ry, rxsize, rysize, wxsize, wysize)
948
949 # Detect totally transparent tile and skip its creation
950 if tile_job_info.exclude_transparent and len(alpha) == alpha.count('\x00'.encode('ascii')):
951 return
952
953 data = ds.ReadRaster(rx, ry, rxsize, rysize, wxsize, wysize,
954 band_list=list(range(1, dataBandsCount + 1)))
955
956 # The tile in memory is a transparent file by default. Write pixel values into it if
957 # any
958 if data:
959 if tile_size == querysize:
960 # Use the ReadRaster result directly in tiles ('nearest neighbour' query)
961 dstile.WriteRaster(wx, wy, wxsize, wysize, data,
962 band_list=list(range(1, dataBandsCount + 1)))
963 dstile.WriteRaster(wx, wy, wxsize, wysize, alpha, band_list=[tilebands])
964
965 # Note: For source drivers based on WaveLet compression (JPEG2000, ECW,
966 # MrSID) the ReadRaster function returns high-quality raster (not ugly
967 # nearest neighbour)
968 # TODO: Use directly 'near' for WaveLet files
969 else:
970 # Big ReadRaster query in memory scaled to the tile_size - all but 'near'
971 # algo
972 dsquery = mem_drv.Create('', querysize, querysize, tilebands)
973 # TODO: fill the null value in case a tile without alpha is produced (now
974 # only png tiles are supported)
975 dsquery.WriteRaster(wx, wy, wxsize, wysize, data,
976 band_list=list(range(1, dataBandsCount + 1)))
977 dsquery.WriteRaster(wx, wy, wxsize, wysize, alpha, band_list=[tilebands])
978
979 scale_query_to_tile(dsquery, dstile, tile_job_info.tile_driver, options,
980 tilefilename=tilefilename)
981 del dsquery
982
983 del data
984
985 if options.resampling != 'antialias':
986 # Write a copy of tile to png/jpg
987 out_drv.CreateCopy(tilefilename, dstile, strict=0)
988
989 del dstile
990
991 # Create a KML file for this tile.
992 if tile_job_info.kml:
993 kmlfilename = os.path.join(output, str(tz), str(tx), '%d.kml' % ty)
994 if not options.resume or not os.path.exists(kmlfilename):
995 with open(kmlfilename, 'wb') as f:
996 f.write(generate_kml(
997 tx, ty, tz, tile_job_info.tile_extension, tile_job_info.tile_size,
998 get_tile_swne(tile_job_info, options), tile_job_info.options
999 ).encode('utf-8'))
1000
1001
1002
1003def create_overview_tiles(tile_job_info, output_folder, options):
1004 """Generation of the overview tiles (higher in the pyramid) based on existing tiles"""
1005 mem_driver = gdal.GetDriverByName('MEM')
1006 tile_driver = tile_job_info.tile_driver
1007 out_driver = gdal.GetDriverByName(tile_driver)
1008
1009 tilebands = tile_job_info.nb_data_bands + 1
1010
1011 # Usage of existing tiles: from 4 underlying tiles generate one as overview.
1012
1013 tcount = 0
1014 for tz in range(tile_job_info.tmaxz - 1, tile_job_info.tminz - 1, -1):
1015 tminx, tminy, tmaxx, tmaxy = tile_job_info.tminmax[tz]
1016 tcount += (1 + abs(tmaxx - tminx)) * (1 + abs(tmaxy - tminy))
1017
1018 ti = 0
1019
1020 if tcount == 0:
1021 return
1022
1023 if not options.quiet:
1024 print("Generating Overview Tiles:")
1025
1026 progress_bar = ProgressBar(tcount)
1027 progress_bar.start()
1028
1029 for tz in range(tile_job_info.tmaxz - 1, tile_job_info.tminz - 1, -1):
1030 tminx, tminy, tmaxx, tmaxy = tile_job_info.tminmax[tz]
1031 for ty in range(tmaxy, tminy - 1, -1):
1032 for tx in range(tminx, tmaxx + 1):
1033
1034 ti += 1
1035 tilefilename = os.path.join(output_folder,
1036 str(tz),
1037 str(tx),
1038 "%s.%s" % (ty, tile_job_info.tile_extension))
1039
1040 if options.verbose:
1041 print(ti, '/', tcount, tilefilename)
1042
1043 if options.resume and os.path.exists(tilefilename):
1044 if options.verbose:
1045 print("Tile generation skipped because of --resume")
1046 else:
1047 progress_bar.log_progress()
1048 continue
1049
1050 # Create directories for the tile
1051 if not os.path.exists(os.path.dirname(tilefilename)):
1052 os.makedirs(os.path.dirname(tilefilename))
1053
1054 dsquery = mem_driver.Create('', 2 * tile_job_info.tile_size,
1055 2 * tile_job_info.tile_size, tilebands)
1056 # TODO: fill the null value
1057 dstile = mem_driver.Create('', tile_job_info.tile_size, tile_job_info.tile_size,
1058 tilebands)
1059
1060 # TODO: Implement more clever walking on the tiles with cache functionality
1061 # probably walk should start with reading of four tiles from top left corner
1062 # Hilbert curve
1063
1064 children = []
1065 # Read the tiles and write them to query window
1066 for y in range(2 * ty, 2 * ty + 2):
1067 for x in range(2 * tx, 2 * tx + 2):
1068 minx, miny, maxx, maxy = tile_job_info.tminmax[tz + 1]
1069 if x >= minx and x <= maxx and y >= miny and y <= maxy:
1070 base_tile_path = os.path.join(output_folder, str(tz + 1), str(x),
1071 "%s.%s" % (y, tile_job_info.tile_extension))
1072 if not os.path.isfile(base_tile_path):
1073 continue
1074
1075 dsquerytile = gdal.Open(
1076 base_tile_path,
1077 gdal.GA_ReadOnly)
1078 if (ty == 0 and y == 1) or (ty != 0 and (y % (2 * ty)) != 0):
1079 tileposy = 0
1080 else:
1081 tileposy = tile_job_info.tile_size
1082 if tx:
1083 tileposx = x % (2 * tx) * tile_job_info.tile_size
1084 elif tx == 0 and x == 1:
1085 tileposx = tile_job_info.tile_size
1086 else:
1087 tileposx = 0
1088 dsquery.WriteRaster(
1089 tileposx, tileposy, tile_job_info.tile_size,
1090 tile_job_info.tile_size,
1091 dsquerytile.ReadRaster(0, 0,
1092 tile_job_info.tile_size,
1093 tile_job_info.tile_size),
1094 band_list=list(range(1, tilebands + 1)))
1095 children.append([x, y, tz + 1])
1096
1097 if children:
1098 scale_query_to_tile(dsquery, dstile, tile_driver, options,
1099 tilefilename=tilefilename)
1100 # Write a copy of tile to png/jpg
1101 if options.resampling != 'antialias':
1102 # Write a copy of tile to png/jpg
1103 out_driver.CreateCopy(tilefilename, dstile, strict=0)
1104
1105 if options.verbose:
1106 print("\tbuild from zoom", tz + 1,
1107 " tiles:", (2 * tx, 2 * ty), (2 * tx + 1, 2 * ty),
1108 (2 * tx, 2 * ty + 1), (2 * tx + 1, 2 * ty + 1))
1109
1110 # Create a KML file for this tile.
1111 if tile_job_info.kml:
1112 with open(os.path.join(
1113 output_folder,
1114 '%d/%d/%d.kml' % (tz, tx, ty)
1115 ), 'wb') as f:
1116 f.write(generate_kml(
1117 tx, ty, tz, tile_job_info.tile_extension, tile_job_info.tile_size,
1118 get_tile_swne(tile_job_info, options), options, children
1119 ).encode('utf-8'))
1120
1121 if not options.verbose and not options.quiet:
1122 progress_bar.log_progress()
1123
1124
1125def optparse_init():
1126 """Prepare the option parser for input (argv)"""
1127
1128 from optparse import OptionParser, OptionGroup
1129 usage = "Usage: %prog [options] input_file [output]"
1130 p = OptionParser(usage, version="%prog " + __version__)
1131 p.add_option("-p", "--profile", dest='profile',
1132 type='choice', choices=profile_list,
1133 help=("Tile cutting profile (%s) - default 'mercator' "
1134 "(Google Maps compatible)" % ",".join(profile_list)))
1135 p.add_option("-r", "--resampling", dest="resampling",
1136 type='choice', choices=resampling_list,
1137 help="Resampling method (%s) - default 'average'" % ",".join(resampling_list))
1138 p.add_option('-s', '--s_srs', dest="s_srs", metavar="SRS",
1139 help="The spatial reference system used for the source input data")
1140 p.add_option('-z', '--zoom', dest="zoom",
1141 help="Zoom levels to render (format:'2-5' or '10').")
1142 p.add_option('-e', '--resume', dest="resume", action="store_true",
1143 help="Resume mode. Generate only missing files.")
1144 p.add_option('-a', '--srcnodata', dest="srcnodata", metavar="NODATA",
1145 help="NODATA transparency value to assign to the input data")
1146 p.add_option('-d', '--tmscompatible', dest="tmscompatible", action="store_true",
1147 help=("When using the geodetic profile, specifies the base resolution "
1148 "as 0.703125 or 2 tiles at zoom level 0."))
1149 p.add_option("-v", "--verbose",
1150 action="store_true", dest="verbose",
1151 help="Print status messages to stdout")
1152 p.add_option("-x", "--exclude",
1153 action="store_true", dest="exclude_transparent",
1154 help="Exclude transparent tiles from result tileset")
1155 p.add_option("-q", "--quiet",
1156 action="store_true", dest="quiet",
1157 help="Disable messages and status to stdout")
1158 p.add_option("--processes",
1159 dest="nb_processes",
1160 type='int',
1161 help="Number of processes to use for tiling")
1162 p.add_option("--tilesize", dest="tilesize", default=256,
1163 type='int',
1164 help="Tile size in pixel of a tile")
1165
1166 # KML options
1167 g = OptionGroup(p, "KML (Google Earth) options",
1168 "Options for generated Google Earth SuperOverlay metadata")
1169 g.add_option("-k", "--force-kml", dest='kml', action="store_true",
1170 help=("Generate KML for Google Earth - default for 'geodetic' profile and "
1171 "'raster' in EPSG:4326. For a dataset with different projection use "
1172 "with caution!"))
1173 g.add_option("-n", "--no-kml", dest='kml', action="store_false",
1174 help="Avoid automatic generation of KML files for EPSG:4326")
1175 g.add_option("-u", "--url", dest='url',
1176 help="URL address where the generated tiles are going to be published")
1177 p.add_option_group(g)
1178
1179 # HTML options
1180 g = OptionGroup(p, "Web viewer options",
1181 "Options for generated HTML viewers a la Google Maps")
1182 g.add_option("-w", "--webviewer", dest='webviewer', type='choice', choices=webviewer_list,
1183 help="Web viewer to generate (%s) - default 'all'" % ",".join(webviewer_list))
1184 g.add_option("-t", "--title", dest='title',
1185 help="Title of the map")
1186 g.add_option("-c", "--copyright", dest='copyright',
1187 help="Copyright for the map")
1188 g.add_option("-g", "--googlekey", dest='googlekey',
1189 help="Google Maps API key from http://code.google.com/apis/maps/signup.html")
1190 g.add_option("-b", "--bingkey", dest='bingkey',
1191 help="Bing Maps API key from https://www.bingmapsportal.com/")
1192 p.add_option_group(g)
1193
1194 p.set_defaults(verbose=False, profile="mercator", kml=False, url='',
1195 webviewer='all', copyright='', resampling='average', resume=False,
1196 googlekey='INSERT_YOUR_KEY_HERE', bingkey='INSERT_YOUR_KEY_HERE',
1197 processes=1)
1198
1199 return p
1200
1201
1202def process_args(argv):
1203 parser = optparse_init()
1204 options, args = parser.parse_args(args=argv)
1205
1206 # Args should be either an input file OR an input file and an output folder
1207 if not args:
1208 exit_with_error("You need to specify at least an input file as argument to the script")
1209 if len(args) > 2:
1210 exit_with_error("Processing of several input files is not supported.",
1211 "Please first use a tool like gdal_vrtmerge.py or gdal_merge.py on the "
1212 "files: gdal_vrtmerge.py -o merged.vrt %s" % " ".join(args))
1213
1214 input_file = args[0]
1215 if not os.path.isfile(input_file):
1216 exit_with_error("The provided input file %s does not exist or is not a file" % input_file)
1217
1218 if len(args) == 2:
1219 output_folder = args[1]
1220 else:
1221 # Directory with input filename without extension in actual directory
1222 output_folder = os.path.splitext(os.path.basename(input_file))[0]
1223
1224 options = options_post_processing(options, input_file, output_folder)
1225
1226 return input_file, output_folder, options
1227
1228
1229def options_post_processing(options, input_file, output_folder):
1230 if not options.title:
1231 options.title = os.path.basename(input_file)
1232
1233 if options.url and not options.url.endswith('/'):
1234 options.url += '/'
1235 if options.url:
1236 out_path = output_folder
1237 if out_path.endswith("/"):
1238 out_path = out_path[:-1]
1239 options.url += os.path.basename(out_path) + '/'
1240
1241 # Supported options
1242 if options.resampling == 'antialias' and not numpy_available:
1243 exit_with_error("'antialias' resampling algorithm is not available.",
1244 "Install PIL (Python Imaging Library) and numpy.")
1245
1246 try:
1247 os.path.basename(input_file).encode('ascii')
1248 except UnicodeEncodeError:
1249 full_ascii = False
1250 else:
1251 full_ascii = True
1252
1253 # LC_CTYPE check
1254 if not full_ascii and 'UTF-8' not in os.environ.get("LC_CTYPE", ""):
1255 if not options.quiet:
1256 print("\nWARNING: "
1257 "You are running gdal2tiles.py with a LC_CTYPE environment variable that is "
1258 "not UTF-8 compatible, and your input file contains non-ascii characters. "
1259 "The generated sample googlemaps, openlayers or "
1260 "leaflet files might contain some invalid characters as a result\n")
1261
1262 # Output the results
1263 if options.verbose:
1264 print("Options:", options)
1265 print("Input:", input_file)
1266 print("Output:", output_folder)
1267 print("Cache: %s MB" % (gdal.GetCacheMax() / 1024 / 1024))
1268 print('')
1269
1270 return options
1271
1272
1273class TileDetail(object):
1274 tx = 0
1275 ty = 0
1276 tz = 0
1277 rx = 0
1278 ry = 0
1279 rxsize = 0
1280 rysize = 0
1281 wx = 0
1282 wy = 0
1283 wxsize = 0
1284 wysize = 0
1285 querysize = 0
1286
1287 def __init__(self, **kwargs):
1288 for key in kwargs:
1289 if hasattr(self, key):
1290 setattr(self, key, kwargs[key])
1291
1292 def __unicode__(self):
1293 return "TileDetail %s\n%s\n%s\n" % (self.tx, self.ty, self.tz)
1294
1295 def __str__(self):
1296 return "TileDetail %s\n%s\n%s\n" % (self.tx, self.ty, self.tz)
1297
1298 def __repr__(self):
1299 return "TileDetail %s\n%s\n%s\n" % (self.tx, self.ty, self.tz)
1300
1301
1302class TileJobInfo(object):
1303 """
1304 Plain object to hold tile job configuration for a dataset
1305 """
1306 src_file = ""
1307 nb_data_bands = 0
1308 output_file_path = ""
1309 tile_extension = ""
1310 tile_size = 0
1311 tile_driver = None
1312 kml = False
1313 tminmax = []
1314 tminz = 0
1315 tmaxz = 0
1316 in_srs_wkt = 0
1317 out_geo_trans = []
1318 ominy = 0
1319 is_epsg_4326 = False
1320 options = None
1321 exclude_transparent = False
1322
1323 def __init__(self, **kwargs):
1324 for key in kwargs:
1325 if hasattr(self, key):
1326 setattr(self, key, kwargs[key])
1327
1328 def __unicode__(self):
1329 return "TileJobInfo %s\n" % (self.src_file)
1330
1331 def __str__(self):
1332 return "TileJobInfo %s\n" % (self.src_file)
1333
1334 def __repr__(self):
1335 return "TileJobInfo %s\n" % (self.src_file)
1336
1337
1338class Gdal2TilesError(Exception):
1339 pass
1340
1341
1342class GDAL2Tiles(object):
1343
1344 def __init__(self, input_file, output_folder, options):
1345 """Constructor function - initialization"""
1346 self.out_drv = None
1347 self.mem_drv = None
1348 self.warped_input_dataset = None
1349 self.out_srs = None
1350 self.nativezoom = None
1351 self.tminmax = None
1352 self.tsize = None
1353 self.mercator = None
1354 self.geodetic = None
1355 self.alphaband = None
1356 self.dataBandsCount = None
1357 self.out_gt = None
1358 self.tileswne = None
1359 self.swne = None
1360 self.ominx = None
1361 self.omaxx = None
1362 self.omaxy = None
1363 self.ominy = None
1364
1365 self.input_file = None
1366 self.output_folder = None
1367
1368 self.isepsg4326 = None
1369 self.in_srs_wkt = None
1370
1371 # Tile format
1372 self.tile_size = 256
1373 if options.tilesize:
1374 self.tile_size = options.tilesize
1375 self.tiledriver = 'PNG'
1376 self.tileext = 'png'
1377 self.tmp_dir = tempfile.mkdtemp()
1378 self.tmp_vrt_filename = os.path.join(self.tmp_dir, str(uuid4()) + '.vrt')
1379
1380 # Should we read bigger window of the input raster and scale it down?
1381 # Note: Modified later by open_input()
1382 # Not for 'near' resampling
1383 # Not for Wavelet based drivers (JPEG2000, ECW, MrSID)
1384 # Not for 'raster' profile
1385 self.scaledquery = True
1386 # How big should be query window be for scaling down
1387 # Later on reset according the chosen resampling algorightm
1388 self.querysize = 4 * self.tile_size
1389
1390 # Should we use Read on the input file for generating overview tiles?
1391 # Note: Modified later by open_input()
1392 # Otherwise the overview tiles are generated from existing underlying tiles
1393 self.overviewquery = False
1394
1395 self.input_file = input_file
1396 self.output_folder = output_folder
1397 self.options = options
1398
1399 if self.options.resampling == 'near':
1400 self.querysize = self.tile_size
1401
1402 elif self.options.resampling == 'bilinear':
1403 self.querysize = self.tile_size * 2
1404
1405 # User specified zoom levels
1406 self.tminz = None
1407 self.tmaxz = None
1408 if self.options.zoom:
1409 minmax = self.options.zoom.split('-', 1)
1410 minmax.extend([''])
1411 zoom_min, zoom_max = minmax[:2]
1412 self.tminz = int(zoom_min)
1413 if zoom_max:
1414 self.tmaxz = int(zoom_max)
1415 else:
1416 self.tmaxz = int(zoom_min)
1417
1418 # KML generation
1419 self.kml = self.options.kml
1420
1421 # -------------------------------------------------------------------------
1422 def open_input(self):
1423 """Initialization of the input raster, reprojection if necessary"""
1424 gdal.AllRegister()
1425
1426 self.out_drv = gdal.GetDriverByName(self.tiledriver)
1427 self.mem_drv = gdal.GetDriverByName('MEM')
1428
1429 if not self.out_drv:
1430 raise Exception("The '%s' driver was not found, is it available in this GDAL build?" %
1431 self.tiledriver)
1432 if not self.mem_drv:
1433 raise Exception("The 'MEM' driver was not found, is it available in this GDAL build?")
1434
1435 # Open the input file
1436
1437 if self.input_file:
1438 input_dataset = gdal.Open(self.input_file, gdal.GA_ReadOnly)
1439 else:
1440 raise Exception("No input file was specified")
1441
1442 if self.options.verbose:
1443 print("Input file:",
1444 "( %sP x %sL - %s bands)" % (input_dataset.RasterXSize,
1445 input_dataset.RasterYSize,
1446 input_dataset.RasterCount))
1447
1448 if not input_dataset:
1449 # Note: GDAL prints the ERROR message too
1450 exit_with_error("It is not possible to open the input file '%s'." % self.input_file)
1451
1452 # Read metadata from the input file
1453 if input_dataset.RasterCount == 0:
1454 exit_with_error("Input file '%s' has no raster band" % self.input_file)
1455
1456 if input_dataset.GetRasterBand(1).GetRasterColorTable():
1457 exit_with_error(
1458 "Please convert this file to RGB/RGBA and run gdal2tiles on the result.",
1459 "From paletted file you can create RGBA file (temp.vrt) by:\n"
1460 "gdal_translate -of vrt -expand rgba %s temp.vrt\n"
1461 "then run:\n"
1462 "gdal2tiles temp.vrt" % self.input_file
1463 )
1464
1465 in_nodata = setup_no_data_values(input_dataset, self.options)
1466
1467 if self.options.verbose:
1468 print("Preprocessed file:",
1469 "( %sP x %sL - %s bands)" % (input_dataset.RasterXSize,
1470 input_dataset.RasterYSize,
1471 input_dataset.RasterCount))
1472
1473 in_srs, self.in_srs_wkt = setup_input_srs(input_dataset, self.options)
1474
1475 self.out_srs = setup_output_srs(in_srs, self.options)
1476
1477 # If input and output reference systems are different, we reproject the input dataset into
1478 # the output reference system for easier manipulation
1479
1480 self.warped_input_dataset = None
1481
1482 if self.options.profile in ('mercator', 'geodetic'):
1483
1484 if not in_srs:
1485 exit_with_error(
1486 "Input file has unknown SRS.",
1487 "Use --s_srs ESPG:xyz (or similar) to provide source reference system.")
1488
1489 if not has_georeference(input_dataset):
1490 exit_with_error(
1491 "There is no georeference - neither affine transformation (worldfile) "
1492 "nor GCPs. You can generate only 'raster' profile tiles.",
1493 "Either gdal2tiles with parameter -p 'raster' or use another GIS "
1494 "software for georeference e.g. gdal_transform -gcp / -a_ullr / -a_srs"
1495 )
1496
1497 if ((in_srs.ExportToProj4() != self.out_srs.ExportToProj4()) or
1498 (input_dataset.GetGCPCount() != 0)):
1499 self.warped_input_dataset = reproject_dataset(
1500 input_dataset, in_srs, self.out_srs)
1501
1502 if in_nodata:
1503 self.warped_input_dataset = update_no_data_values(
1504 self.warped_input_dataset, in_nodata, options=self.options)
1505 else:
1506 self.warped_input_dataset = update_alpha_value_for_non_alpha_inputs(
1507 self.warped_input_dataset, options=self.options)
1508
1509 if self.warped_input_dataset and self.options.verbose:
1510 print("Projected file:", "tiles.vrt", "( %sP x %sL - %s bands)" % (
1511 self.warped_input_dataset.RasterXSize,
1512 self.warped_input_dataset.RasterYSize,
1513 self.warped_input_dataset.RasterCount))
1514
1515 if not self.warped_input_dataset:
1516 self.warped_input_dataset = input_dataset
1517
1518 gdal.GetDriverByName('VRT').CreateCopy(self.tmp_vrt_filename,
1519 self.warped_input_dataset)
1520
1521 # Get alpha band (either directly or from NODATA value)
1522 self.alphaband = self.warped_input_dataset.GetRasterBand(1).GetMaskBand()
1523 self.dataBandsCount = nb_data_bands(self.warped_input_dataset)
1524
1525 # KML test
1526 self.isepsg4326 = False
1527 srs4326 = osr.SpatialReference()
1528 srs4326.ImportFromEPSG(4326)
1529 srs4326.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER)
1530 if self.out_srs and srs4326.ExportToProj4() == self.out_srs.ExportToProj4():
1531 self.kml = True
1532 self.isepsg4326 = True
1533 if self.options.verbose:
1534 print("KML autotest OK!")
1535
1536 # Read the georeference
1537 self.out_gt = self.warped_input_dataset.GetGeoTransform()
1538
1539 # Test the size of the pixel
1540
1541 # Report error in case rotation/skew is in geotransform (possible only in 'raster' profile)
1542 if (self.out_gt[2], self.out_gt[4]) != (0, 0):
1543 exit_with_error("Georeference of the raster contains rotation or skew. "
1544 "Such raster is not supported. Please use gdalwarp first.")
1545
1546 # Here we expect: pixel is square, no rotation on the raster
1547
1548 # Output Bounds - coordinates in the output SRS
1549 self.ominx = self.out_gt[0]
1550 self.omaxx = self.out_gt[0] + self.warped_input_dataset.RasterXSize * self.out_gt[1]
1551 self.omaxy = self.out_gt[3]
1552 self.ominy = self.out_gt[3] - self.warped_input_dataset.RasterYSize * self.out_gt[1]
1553 # Note: maybe round(x, 14) to avoid the gdal_translate behaviour, when 0 becomes -1e-15
1554
1555 if self.options.verbose:
1556 print("Bounds (output srs):", round(self.ominx, 13), self.ominy, self.omaxx, self.omaxy)
1557
1558 # Calculating ranges for tiles in different zoom levels
1559 if self.options.profile == 'mercator':
1560
1561 self.mercator = GlobalMercator(tile_size=self.tile_size)
1562
1563 # Function which generates SWNE in LatLong for given tile
1564 self.tileswne = self.mercator.TileLatLonBounds
1565
1566 # Generate table with min max tile coordinates for all zoomlevels
1567 self.tminmax = list(range(0, 32))
1568 for tz in range(0, 32):
1569 tminx, tminy = self.mercator.MetersToTile(self.ominx, self.ominy, tz)
1570 tmaxx, tmaxy = self.mercator.MetersToTile(self.omaxx, self.omaxy, tz)
1571 # crop tiles extending world limits (+-180,+-90)
1572 tminx, tminy = max(0, tminx), max(0, tminy)
1573 tmaxx, tmaxy = min(2**tz - 1, tmaxx), min(2**tz - 1, tmaxy)
1574 self.tminmax[tz] = (tminx, tminy, tmaxx, tmaxy)
1575
1576 # TODO: Maps crossing 180E (Alaska?)
1577
1578 # Get the minimal zoom level (map covers area equivalent to one tile)
1579 if self.tminz is None:
1580 self.tminz = self.mercator.ZoomForPixelSize(
1581 self.out_gt[1] *
1582 max(self.warped_input_dataset.RasterXSize,
1583 self.warped_input_dataset.RasterYSize) /
1584 float(self.tile_size))
1585
1586 # Get the maximal zoom level
1587 # (closest possible zoom level up on the resolution of raster)
1588 if self.tmaxz is None:
1589 self.tmaxz = self.mercator.ZoomForPixelSize(self.out_gt[1])
1590
1591 if self.options.verbose:
1592 print("Bounds (latlong):",
1593 self.mercator.MetersToLatLon(self.ominx, self.ominy),
1594 self.mercator.MetersToLatLon(self.omaxx, self.omaxy))
1595 print('MinZoomLevel:', self.tminz)
1596 print("MaxZoomLevel:",
1597 self.tmaxz,
1598 "(",
1599 self.mercator.Resolution(self.tmaxz),
1600 ")")
1601
1602 if self.options.profile == 'geodetic':
1603
1604 self.geodetic = GlobalGeodetic(self.options.tmscompatible, tile_size=self.tile_size)
1605
1606 # Function which generates SWNE in LatLong for given tile
1607 self.tileswne = self.geodetic.TileLatLonBounds
1608
1609 # Generate table with min max tile coordinates for all zoomlevels
1610 self.tminmax = list(range(0, 32))
1611 for tz in range(0, 32):
1612 tminx, tminy = self.geodetic.LonLatToTile(self.ominx, self.ominy, tz)
1613 tmaxx, tmaxy = self.geodetic.LonLatToTile(self.omaxx, self.omaxy, tz)
1614 # crop tiles extending world limits (+-180,+-90)
1615 tminx, tminy = max(0, tminx), max(0, tminy)
1616 tmaxx, tmaxy = min(2**(tz + 1) - 1, tmaxx), min(2**tz - 1, tmaxy)
1617 self.tminmax[tz] = (tminx, tminy, tmaxx, tmaxy)
1618
1619 # TODO: Maps crossing 180E (Alaska?)
1620
1621 # Get the maximal zoom level
1622 # (closest possible zoom level up on the resolution of raster)
1623 if self.tminz is None:
1624 self.tminz = self.geodetic.ZoomForPixelSize(
1625 self.out_gt[1] *
1626 max(self.warped_input_dataset.RasterXSize,
1627 self.warped_input_dataset.RasterYSize) /
1628 float(self.tile_size))
1629
1630 # Get the maximal zoom level
1631 # (closest possible zoom level up on the resolution of raster)
1632 if self.tmaxz is None:
1633 self.tmaxz = self.geodetic.ZoomForPixelSize(self.out_gt[1])
1634
1635 if self.options.verbose:
1636 print("Bounds (latlong):", self.ominx, self.ominy, self.omaxx, self.omaxy)
1637
1638 if self.options.profile == 'raster':
1639
1640 def log2(x):
1641 return math.log10(x) / math.log10(2)
1642
1643 self.nativezoom = int(
1644 max(math.ceil(log2(self.warped_input_dataset.RasterXSize / float(self.tile_size))),
1645 math.ceil(log2(self.warped_input_dataset.RasterYSize / float(self.tile_size)))))
1646
1647 if self.options.verbose:
1648 print("Native zoom of the raster:", self.nativezoom)
1649
1650 # Get the minimal zoom level (whole raster in one tile)
1651 if self.tminz is None:
1652 self.tminz = 0
1653
1654 # Get the maximal zoom level (native resolution of the raster)
1655 if self.tmaxz is None:
1656 self.tmaxz = self.nativezoom
1657
1658 # Generate table with min max tile coordinates for all zoomlevels
1659 self.tminmax = list(range(0, self.tmaxz + 1))
1660 self.tsize = list(range(0, self.tmaxz + 1))
1661 for tz in range(0, self.tmaxz + 1):
1662 tsize = 2.0**(self.nativezoom - tz) * self.tile_size
1663 tminx, tminy = 0, 0
1664 tmaxx = int(math.ceil(self.warped_input_dataset.RasterXSize / tsize)) - 1
1665 tmaxy = int(math.ceil(self.warped_input_dataset.RasterYSize / tsize)) - 1
1666 self.tsize[tz] = math.ceil(tsize)
1667 self.tminmax[tz] = (tminx, tminy, tmaxx, tmaxy)
1668
1669 # Function which generates SWNE in LatLong for given tile
1670 if self.kml and self.in_srs_wkt:
1671 ct = osr.CoordinateTransformation(in_srs, srs4326)
1672
1673 def rastertileswne(x, y, z):
1674 pixelsizex = (2**(self.tmaxz - z) * self.out_gt[1]) # X-pixel size in level
1675 west = self.out_gt[0] + x * self.tile_size * pixelsizex
1676 east = west + self.tile_size * pixelsizex
1677 south = self.ominy + y * self.tile_size * pixelsizex
1678 north = south + self.tile_size * pixelsizex
1679 if not self.isepsg4326:
1680 # Transformation to EPSG:4326 (WGS84 datum)
1681 west, south = ct.TransformPoint(west, south)[:2]
1682 east, north = ct.TransformPoint(east, north)[:2]
1683 return south, west, north, east
1684
1685 self.tileswne = rastertileswne
1686 else:
1687 self.tileswne = lambda x, y, z: (0, 0, 0, 0) # noqa
1688
1689 def generate_metadata(self):
1690 """
1691 Generation of main metadata files and HTML viewers (metadata related to particular
1692 tiles are generated during the tile processing).
1693 """
1694
1695 if not os.path.exists(self.output_folder):
1696 os.makedirs(self.output_folder)
1697
1698 if self.options.profile == 'mercator':
1699
1700 south, west = self.mercator.MetersToLatLon(self.ominx, self.ominy)
1701 north, east = self.mercator.MetersToLatLon(self.omaxx, self.omaxy)
1702 south, west = max(-85.05112878, south), max(-180.0, west)
1703 north, east = min(85.05112878, north), min(180.0, east)
1704 self.swne = (south, west, north, east)
1705
1706 # Generate googlemaps.html
1707 if self.options.webviewer in ('all', 'google') and self.options.profile == 'mercator':
1708 if (not self.options.resume or not
1709 os.path.exists(os.path.join(self.output_folder, 'googlemaps.html'))):
1710 with open(os.path.join(self.output_folder, 'googlemaps.html'), 'wb') as f:
1711 f.write(self.generate_googlemaps().encode('utf-8'))
1712
1713 # Generate openlayers.html
1714 if self.options.webviewer in ('all', 'openlayers'):
1715 if (not self.options.resume or not
1716 os.path.exists(os.path.join(self.output_folder, 'openlayers.html'))):
1717 with open(os.path.join(self.output_folder, 'openlayers.html'), 'wb') as f:
1718 f.write(self.generate_openlayers().encode('utf-8'))
1719
1720 # Generate leaflet.html
1721 if self.options.webviewer in ('all', 'leaflet'):
1722 if (not self.options.resume or not
1723 os.path.exists(os.path.join(self.output_folder, 'leaflet.html'))):
1724 with open(os.path.join(self.output_folder, 'leaflet.html'), 'wb') as f:
1725 f.write(self.generate_leaflet().encode('utf-8'))
1726
1727 elif self.options.profile == 'geodetic':
1728
1729 west, south = self.ominx, self.ominy
1730 east, north = self.omaxx, self.omaxy
1731 south, west = max(-90.0, south), max(-180.0, west)
1732 north, east = min(90.0, north), min(180.0, east)
1733 self.swne = (south, west, north, east)
1734
1735 # Generate openlayers.html
1736 if self.options.webviewer in ('all', 'openlayers'):
1737 if (not self.options.resume or not
1738 os.path.exists(os.path.join(self.output_folder, 'openlayers.html'))):
1739 with open(os.path.join(self.output_folder, 'openlayers.html'), 'wb') as f:
1740 f.write(self.generate_openlayers().encode('utf-8'))
1741
1742 elif self.options.profile == 'raster':
1743
1744 west, south = self.ominx, self.ominy
1745 east, north = self.omaxx, self.omaxy
1746
1747 self.swne = (south, west, north, east)
1748
1749 # Generate openlayers.html
1750 if self.options.webviewer in ('all', 'openlayers'):
1751 if (not self.options.resume or not
1752 os.path.exists(os.path.join(self.output_folder, 'openlayers.html'))):
1753 with open(os.path.join(self.output_folder, 'openlayers.html'), 'wb') as f:
1754 f.write(self.generate_openlayers().encode('utf-8'))
1755
1756 # Generate tilemapresource.xml.
1757 if not self.options.resume or not os.path.exists(os.path.join(self.output_folder, 'tilemapresource.xml')):
1758 with open(os.path.join(self.output_folder, 'tilemapresource.xml'), 'wb') as f:
1759 f.write(self.generate_tilemapresource().encode('utf-8'))
1760
1761 if self.kml:
1762 # TODO: Maybe problem for not automatically generated tminz
1763 # The root KML should contain links to all tiles in the tminz level
1764 children = []
1765 xmin, ymin, xmax, ymax = self.tminmax[self.tminz]
1766 for x in range(xmin, xmax + 1):
1767 for y in range(ymin, ymax + 1):
1768 children.append([x, y, self.tminz])
1769 # Generate Root KML
1770 if self.kml:
1771 if (not self.options.resume or not
1772 os.path.exists(os.path.join(self.output_folder, 'doc.kml'))):
1773 with open(os.path.join(self.output_folder, 'doc.kml'), 'wb') as f:
1774 f.write(generate_kml(
1775 None, None, None, self.tileext, self.tile_size, self.tileswne,
1776 self.options, children
1777 ).encode('utf-8'))
1778
1779 def generate_base_tiles(self):
1780 """
1781 Generation of the base tiles (the lowest in the pyramid) directly from the input raster
1782 """
1783
1784 if not self.options.quiet:
1785 print("Generating Base Tiles:")
1786
1787 if self.options.verbose:
1788 print('')
1789 print("Tiles generated from the max zoom level:")
1790 print("----------------------------------------")
1791 print('')
1792
1793 # Set the bounds
1794 tminx, tminy, tmaxx, tmaxy = self.tminmax[self.tmaxz]
1795
1796 ds = self.warped_input_dataset
1797 tilebands = self.dataBandsCount + 1
1798 querysize = self.querysize
1799
1800 if self.options.verbose:
1801 print("dataBandsCount: ", self.dataBandsCount)
1802 print("tilebands: ", tilebands)
1803
1804 tcount = (1 + abs(tmaxx - tminx)) * (1 + abs(tmaxy - tminy))
1805 ti = 0
1806
1807 tile_details = []
1808
1809 tz = self.tmaxz
1810 for ty in range(tmaxy, tminy - 1, -1):
1811 for tx in range(tminx, tmaxx + 1):
1812
1813 ti += 1
1814 tilefilename = os.path.join(
1815 self.output_folder, str(tz), str(tx), "%s.%s" % (ty, self.tileext))
1816 if self.options.verbose:
1817 print(ti, '/', tcount, tilefilename)
1818
1819 if self.options.resume and os.path.exists(tilefilename):
1820 if self.options.verbose:
1821 print("Tile generation skipped because of --resume")
1822 continue
1823
1824 # Create directories for the tile
1825 if not os.path.exists(os.path.dirname(tilefilename)):
1826 os.makedirs(os.path.dirname(tilefilename))
1827
1828 if self.options.profile == 'mercator':
1829 # Tile bounds in EPSG:3857
1830 b = self.mercator.TileBounds(tx, ty, tz)
1831 elif self.options.profile == 'geodetic':
1832 b = self.geodetic.TileBounds(tx, ty, tz)
1833
1834 # Don't scale up by nearest neighbour, better change the querysize
1835 # to the native resolution (and return smaller query tile) for scaling
1836
1837 if self.options.profile in ('mercator', 'geodetic'):
1838 rb, wb = self.geo_query(ds, b[0], b[3], b[2], b[1])
1839
1840 # Pixel size in the raster covering query geo extent
1841 nativesize = wb[0] + wb[2]
1842 if self.options.verbose:
1843 print("\tNative Extent (querysize", nativesize, "): ", rb, wb)
1844
1845 # Tile bounds in raster coordinates for ReadRaster query
1846 rb, wb = self.geo_query(ds, b[0], b[3], b[2], b[1], querysize=querysize)
1847
1848 rx, ry, rxsize, rysize = rb
1849 wx, wy, wxsize, wysize = wb
1850
1851 else: # 'raster' profile:
1852
1853 tsize = int(self.tsize[tz]) # tile_size in raster coordinates for actual zoom
1854 xsize = self.warped_input_dataset.RasterXSize # size of the raster in pixels
1855 ysize = self.warped_input_dataset.RasterYSize
1856 if tz >= self.nativezoom:
1857 querysize = self.tile_size
1858
1859 rx = (tx) * tsize
1860 rxsize = 0
1861 if tx == tmaxx:
1862 rxsize = xsize % tsize
1863 if rxsize == 0:
1864 rxsize = tsize
1865
1866 rysize = 0
1867 if ty == tmaxy:
1868 rysize = ysize % tsize
1869 if rysize == 0:
1870 rysize = tsize
1871 ry = ysize - (ty * tsize) - rysize
1872
1873 wx, wy = 0, 0
1874 wxsize = int(rxsize / float(tsize) * self.tile_size)
1875 wysize = int(rysize / float(tsize) * self.tile_size)
1876 if wysize != self.tile_size:
1877 wy = self.tile_size - wysize
1878
1879 # Read the source raster if anything is going inside the tile as per the computed
1880 # geo_query
1881 tile_details.append(
1882 TileDetail(
1883 tx=tx, ty=ty, tz=tz, rx=rx, ry=ry, rxsize=rxsize, rysize=rysize, wx=wx,
1884 wy=wy, wxsize=wxsize, wysize=wysize, querysize=querysize,
1885 )
1886 )
1887
1888 conf = TileJobInfo(
1889 src_file=self.tmp_vrt_filename,
1890 nb_data_bands=self.dataBandsCount,
1891 output_file_path=self.output_folder,
1892 tile_extension=self.tileext,
1893 tile_driver=self.tiledriver,
1894 tile_size=self.tile_size,
1895 kml=self.kml,
1896 tminmax=self.tminmax,
1897 tminz=self.tminz,
1898 tmaxz=self.tmaxz,
1899 in_srs_wkt=self.in_srs_wkt,
1900 out_geo_trans=self.out_gt,
1901 ominy=self.ominy,
1902 is_epsg_4326=self.isepsg4326,
1903 options=self.options,
1904 exclude_transparent=self.options.exclude_transparent,
1905 )
1906
1907 return conf, tile_details
1908
1909 def geo_query(self, ds, ulx, uly, lrx, lry, querysize=0):
1910 """
1911 For given dataset and query in cartographic coordinates returns parameters for ReadRaster()
1912 in raster coordinates and x/y shifts (for border tiles). If the querysize is not given, the
1913 extent is returned in the native resolution of dataset ds.
1914
1915 raises Gdal2TilesError if the dataset does not contain anything inside this geo_query
1916 """
1917 geotran = ds.GetGeoTransform()
1918 rx = int((ulx - geotran[0]) / geotran[1] + 0.001)
1919 ry = int((uly - geotran[3]) / geotran[5] + 0.001)
1920 rxsize = int((lrx - ulx) / geotran[1] + 0.5)
1921 rysize = int((lry - uly) / geotran[5] + 0.5)
1922
1923 if not querysize:
1924 wxsize, wysize = rxsize, rysize
1925 else:
1926 wxsize, wysize = querysize, querysize
1927
1928 # Coordinates should not go out of the bounds of the raster
1929 wx = 0
1930 if rx < 0:
1931 rxshift = abs(rx)
1932 wx = int(wxsize * (float(rxshift) / rxsize))
1933 wxsize = wxsize - wx
1934 rxsize = rxsize - int(rxsize * (float(rxshift) / rxsize))
1935 rx = 0
1936 if rx + rxsize > ds.RasterXSize:
1937 wxsize = int(wxsize * (float(ds.RasterXSize - rx) / rxsize))
1938 rxsize = ds.RasterXSize - rx
1939
1940 wy = 0
1941 if ry < 0:
1942 ryshift = abs(ry)
1943 wy = int(wysize * (float(ryshift) / rysize))
1944 wysize = wysize - wy
1945 rysize = rysize - int(rysize * (float(ryshift) / rysize))
1946 ry = 0
1947 if ry + rysize > ds.RasterYSize:
1948 wysize = int(wysize * (float(ds.RasterYSize - ry) / rysize))
1949 rysize = ds.RasterYSize - ry
1950
1951 return (rx, ry, rxsize, rysize), (wx, wy, wxsize, wysize)
1952
1953 def generate_tilemapresource(self):
1954 """
1955 Template for tilemapresource.xml. Returns filled string. Expected variables:
1956 title, north, south, east, west, isepsg4326, projection, publishurl,
1957 zoompixels, tile_size, tileformat, profile
1958 """
1959
1960 args = {}
1961 args['title'] = self.options.title
1962 args['south'], args['west'], args['north'], args['east'] = self.swne
1963 args['tile_size'] = self.tile_size
1964 args['tileformat'] = self.tileext
1965 args['publishurl'] = self.options.url
1966 args['profile'] = self.options.profile
1967
1968 if self.options.profile == 'mercator':
1969 args['srs'] = "EPSG:3857"
1970 elif self.options.profile == 'geodetic':
1971 args['srs'] = "EPSG:4326"
1972 elif self.options.s_srs:
1973 args['srs'] = self.options.s_srs
1974 elif self.out_srs:
1975 args['srs'] = self.out_srs.ExportToWkt()
1976 else:
1977 args['srs'] = ""
1978
1979 s = """<?xml version="1.0" encoding="utf-8"?>
1980 <TileMap version="1.0.0" tilemapservice="http://tms.osgeo.org/1.0.0">
1981 <Title>%(title)s</Title>
1982 <Abstract></Abstract>
1983 <SRS>%(srs)s</SRS>
1984 <BoundingBox minx="%(west).14f" miny="%(south).14f" maxx="%(east).14f" maxy="%(north).14f"/>
1985 <Origin x="%(west).14f" y="%(south).14f"/>
1986 <TileFormat width="%(tile_size)d" height="%(tile_size)d" mime-type="image/%(tileformat)s" extension="%(tileformat)s"/>
1987 <TileSets profile="%(profile)s">
1988""" % args # noqa
1989 for z in range(self.tminz, self.tmaxz + 1):
1990 if self.options.profile == 'raster':
1991 s += """ <TileSet href="%s%d" units-per-pixel="%.14f" order="%d"/>\n""" % (
1992 args['publishurl'], z, (2**(self.nativezoom - z) * self.out_gt[1]), z)
1993 elif self.options.profile == 'mercator':
1994 s += """ <TileSet href="%s%d" units-per-pixel="%.14f" order="%d"/>\n""" % (
1995 args['publishurl'], z, 156543.0339 / 2**z, z)
1996 elif self.options.profile == 'geodetic':
1997 s += """ <TileSet href="%s%d" units-per-pixel="%.14f" order="%d"/>\n""" % (
1998 args['publishurl'], z, 0.703125 / 2**z, z)
1999 s += """ </TileSets>
2000 </TileMap>
2001 """
2002 return s
2003
2004 def generate_googlemaps(self):
2005 """
2006 Template for googlemaps.html implementing Overlay of tiles for 'mercator' profile.
2007 It returns filled string. Expected variables:
2008 title, googlemapskey, north, south, east, west, minzoom, maxzoom, tile_size, tileformat,
2009 publishurl
2010 """
2011 args = {}
2012 args['title'] = self.options.title
2013 args['googlemapskey'] = self.options.googlekey
2014 args['south'], args['west'], args['north'], args['east'] = self.swne
2015 args['minzoom'] = self.tminz
2016 args['maxzoom'] = self.tmaxz
2017 args['tile_size'] = self.tile_size
2018 args['tileformat'] = self.tileext
2019 args['publishurl'] = self.options.url
2020 args['copyright'] = self.options.copyright
2021
2022 s = r"""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
2023 <html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
2024 <head>
2025 <title>%(title)s</title>
2026 <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
2027 <meta http-equiv='imagetoolbar' content='no'/>
2028 <style type="text/css"> v\:* {behavior:url(#default#VML);}
2029 html, body { overflow: hidden; padding: 0; height: 100%%; width: 100%%; font-family: 'Lucida Grande',Geneva,Arial,Verdana,sans-serif; }
2030 body { margin: 10px; background: #fff; }
2031 h1 { margin: 0; padding: 6px; border:0; font-size: 20pt; }
2032 #header { height: 43px; padding: 0; background-color: #eee; border: 1px solid #888; }
2033 #subheader { height: 12px; text-align: right; font-size: 10px; color: #555;}
2034 #map { height: 95%%; border: 1px solid #888; }
2035 </style>
2036 <script src='http://maps.google.com/maps?file=api&amp;v=2&amp;key=%(googlemapskey)s'></script>
2037 <script>
2038 //<![CDATA[
2039
2040 /*
2041 * Constants for given map
2042 * TODO: read it from tilemapresource.xml
2043 */
2044
2045 var mapBounds = new GLatLngBounds(new GLatLng(%(south)s, %(west)s), new GLatLng(%(north)s, %(east)s));
2046 var mapMinZoom = %(minzoom)s;
2047 var mapMaxZoom = %(maxzoom)s;
2048
2049 var opacity = 0.75;
2050 var map;
2051 var hybridOverlay;
2052
2053 /*
2054 * Create a Custom Opacity GControl
2055 * http://www.maptiler.org/google-maps-overlay-opacity-control/
2056 */
2057
2058 var CTransparencyLENGTH = 58;
2059 // maximum width that the knob can move (slide width minus knob width)
2060
2061 function CTransparencyControl( overlay ) {
2062 this.overlay = overlay;
2063 this.opacity = overlay.getTileLayer().getOpacity();
2064 }
2065 CTransparencyControl.prototype = new GControl();
2066
2067 // This function positions the slider to match the specified opacity
2068 CTransparencyControl.prototype.setSlider = function(pos) {
2069 var left = Math.round((CTransparencyLENGTH*pos));
2070 this.slide.left = left;
2071 this.knob.style.left = left+"px";
2072 this.knob.style.top = "0px";
2073 }
2074
2075 // This function reads the slider and sets the overlay opacity level
2076 CTransparencyControl.prototype.setOpacity = function() {
2077 // set the global variable
2078 opacity = this.slide.left/CTransparencyLENGTH;
2079 this.map.clearOverlays();
2080 this.map.addOverlay(this.overlay, { zPriority: 0 });
2081 if (this.map.getCurrentMapType() == G_HYBRID_MAP) {
2082 this.map.addOverlay(hybridOverlay);
2083 }
2084 }
2085
2086 // This gets called by the API when addControl(new CTransparencyControl())
2087 CTransparencyControl.prototype.initialize = function(map) {
2088 var that=this;
2089 this.map = map;
2090
2091 // Is this MSIE, if so we need to use AlphaImageLoader
2092 var agent = navigator.userAgent.toLowerCase();
2093 if ((agent.indexOf("msie") > -1) && (agent.indexOf("opera") < 1)){this.ie = true} else {this.ie = false}
2094
2095 // create the background graphic as a <div> containing an image
2096 var container = document.createElement("div");
2097 container.style.width="70px";
2098 container.style.height="21px";
2099
2100 // Handle transparent PNG files in MSIE
2101 if (this.ie) {
2102 var loader = "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='http://www.maptiler.org/img/opacity-slider.png', sizingMethod='crop');";
2103 container.innerHTML = '<div style="height:21px; width:70px; ' +loader+ '" ></div>';
2104 } else {
2105 container.innerHTML = '<div style="height:21px; width:70px; background-image: url(http://www.maptiler.org/img/opacity-slider.png)" ></div>';
2106 }
2107
2108 // create the knob as a GDraggableObject
2109 // Handle transparent PNG files in MSIE
2110 if (this.ie) {
2111 var loader = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='http://www.maptiler.org/img/opacity-slider.png', sizingMethod='crop');";
2112 this.knob = document.createElement("div");
2113 this.knob.style.height="21px";
2114 this.knob.style.width="13px";
2115 this.knob.style.overflow="hidden";
2116 this.knob_img = document.createElement("div");
2117 this.knob_img.style.height="21px";
2118 this.knob_img.style.width="83px";
2119 this.knob_img.style.filter=loader;
2120 this.knob_img.style.position="relative";
2121 this.knob_img.style.left="-70px";
2122 this.knob.appendChild(this.knob_img);
2123 } else {
2124 this.knob = document.createElement("div");
2125 this.knob.style.height="21px";
2126 this.knob.style.width="13px";
2127 this.knob.style.backgroundImage="url(http://www.maptiler.org/img/opacity-slider.png)";
2128 this.knob.style.backgroundPosition="-70px 0px";
2129 }
2130 container.appendChild(this.knob);
2131 this.slide=new GDraggableObject(this.knob, {container:container});
2132 this.slide.setDraggableCursor('pointer');
2133 this.slide.setDraggingCursor('pointer');
2134 this.container = container;
2135
2136 // attach the control to the map
2137 map.getContainer().appendChild(container);
2138
2139 // init slider
2140 this.setSlider(this.opacity);
2141
2142 // Listen for the slider being moved and set the opacity
2143 GEvent.addListener(this.slide, "dragend", function() {that.setOpacity()});
2144 //GEvent.addListener(this.container, "click", function( x, y ) { alert(x, y) });
2145
2146 return container;
2147 }
2148
2149 // Set the default position for the control
2150 CTransparencyControl.prototype.getDefaultPosition = function() {
2151 return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 47));
2152 }
2153
2154 /*
2155 * Full-screen Window Resize
2156 */
2157
2158 function getWindowHeight() {
2159 if (self.innerHeight) return self.innerHeight;
2160 if (document.documentElement && document.documentElement.clientHeight)
2161 return document.documentElement.clientHeight;
2162 if (document.body) return document.body.clientHeight;
2163 return 0;
2164 }
2165
2166 function getWindowWidth() {
2167 if (self.innerWidth) return self.innerWidth;
2168 if (document.documentElement && document.documentElement.clientWidth)
2169 return document.documentElement.clientWidth;
2170 if (document.body) return document.body.clientWidth;
2171 return 0;
2172 }
2173
2174 function resize() {
2175 var map = document.getElementById("map");
2176 var header = document.getElementById("header");
2177 var subheader = document.getElementById("subheader");
2178 map.style.height = (getWindowHeight()-80) + "px";
2179 map.style.width = (getWindowWidth()-20) + "px";
2180 header.style.width = (getWindowWidth()-20) + "px";
2181 subheader.style.width = (getWindowWidth()-20) + "px";
2182 // map.checkResize();
2183 }
2184
2185
2186 /*
2187 * Main load function:
2188 */
2189
2190 function load() {
2191
2192 if (GBrowserIsCompatible()) {
2193
2194 // Bug in the Google Maps: Copyright for Overlay is not correctly displayed
2195 var gcr = GMapType.prototype.getCopyrights;
2196 GMapType.prototype.getCopyrights = function(bounds,zoom) {
2197 return ["%(copyright)s"].concat(gcr.call(this,bounds,zoom));
2198 }
2199
2200 map = new GMap2( document.getElementById("map"), { backgroundColor: '#fff' } );
2201
2202 map.addMapType(G_PHYSICAL_MAP);
2203 map.setMapType(G_PHYSICAL_MAP);
2204
2205 map.setCenter( mapBounds.getCenter(), map.getBoundsZoomLevel( mapBounds ));
2206
2207 hybridOverlay = new GTileLayerOverlay( G_HYBRID_MAP.getTileLayers()[1] );
2208 GEvent.addListener(map, "maptypechanged", function() {
2209 if (map.getCurrentMapType() == G_HYBRID_MAP) {
2210 map.addOverlay(hybridOverlay);
2211 } else {
2212 map.removeOverlay(hybridOverlay);
2213 }
2214 } );
2215
2216 var tilelayer = new GTileLayer(GCopyrightCollection(''), mapMinZoom, mapMaxZoom);
2217 var mercator = new GMercatorProjection(mapMaxZoom+1);
2218 tilelayer.getTileUrl = function(tile,zoom) {
2219 if ((zoom < mapMinZoom) || (zoom > mapMaxZoom)) {
2220 return "http://www.maptiler.org/img/none.png";
2221 }
2222 var ymax = 1 << zoom;
2223 var y = ymax - tile.y -1;
2224 var tileBounds = new GLatLngBounds(
2225 mercator.fromPixelToLatLng( new GPoint( (tile.x)*256, (tile.y+1)*256 ) , zoom ),
2226 mercator.fromPixelToLatLng( new GPoint( (tile.x+1)*256, (tile.y)*256 ) , zoom )
2227 );
2228 if (mapBounds.intersects(tileBounds)) {
2229 return zoom+"/"+tile.x+"/"+y+".png";
2230 } else {
2231 return "http://www.maptiler.org/img/none.png";
2232 }
2233 }
2234 // IE 7-: support for PNG alpha channel
2235 // Unfortunately, the opacity for whole overlay is then not changeable, either or...
2236 tilelayer.isPng = function() { return true;};
2237 tilelayer.getOpacity = function() { return opacity; }
2238
2239 overlay = new GTileLayerOverlay( tilelayer );
2240 map.addOverlay(overlay);
2241
2242 map.addControl(new GLargeMapControl());
2243 map.addControl(new GHierarchicalMapTypeControl());
2244 map.addControl(new CTransparencyControl( overlay ));
2245 """ % args # noqa
2246 if self.kml:
2247 s += """
2248 map.addMapType(G_SATELLITE_3D_MAP);
2249 map.getEarthInstance(getEarthInstanceCB);
2250 """
2251 s += """
2252
2253 map.enableContinuousZoom();
2254 map.enableScrollWheelZoom();
2255
2256 map.setMapType(G_HYBRID_MAP);
2257 }
2258 resize();
2259 }
2260 """
2261 if self.kml:
2262 s += """
2263 function getEarthInstanceCB(object) {
2264 var ge = object;
2265
2266 if (ge) {
2267 var url = document.location.toString();
2268 url = url.substr(0,url.lastIndexOf('/'))+'/doc.kml';
2269 var link = ge.createLink("");
2270 if ("%(publishurl)s") { link.setHref("%(publishurl)s/doc.kml") }
2271 else { link.setHref(url) };
2272 var networkLink = ge.createNetworkLink("");
2273 networkLink.setName("TMS Map Overlay");
2274 networkLink.setFlyToView(true);
2275 networkLink.setLink(link);
2276 ge.getFeatures().appendChild(networkLink);
2277 } else {
2278 // alert("You should open a KML in Google Earth");
2279 // add div with the link to generated KML... - maybe JavaScript redirect to the URL of KML?
2280 }
2281 }
2282 """ % args # noqa
2283 s += """
2284 onresize=function(){ resize(); };
2285
2286 //]]>
2287 </script>
2288 </head>
2289 <body onload="load()">
2290 <div id="header"><h1>%(title)s</h1></div>
2291 <div id="subheader">Generated by <a href="http://www.klokan.cz/projects/gdal2tiles/">GDAL2Tiles</a>, Copyright &copy; 2008 <a href="http://www.klokan.cz/">Klokan Petr Pridal</a>, <a href="http://www.gdal.org/">GDAL</a> &amp; <a href="http://www.osgeo.org/">OSGeo</a> <a href="http://code.google.com/soc/">GSoC</a>
2292 <!-- PLEASE, LET THIS NOTE ABOUT AUTHOR AND PROJECT SOMEWHERE ON YOUR WEBSITE, OR AT LEAST IN THE COMMENT IN HTML. THANK YOU -->
2293 </div>
2294 <div id="map"></div>
2295 </body>
2296 </html>
2297 """ % args # noqa
2298
2299 return s
2300
2301 def generate_leaflet(self):
2302 """
2303 Template for leaflet.html implementing overlay of tiles for 'mercator' profile.
2304 It returns filled string. Expected variables:
2305 title, north, south, east, west, minzoom, maxzoom, tile_size, tileformat, publishurl
2306 """
2307
2308 args = {}
2309 args['title'] = self.options.title.replace('"', '\\"')
2310 args['htmltitle'] = self.options.title
2311 args['south'], args['west'], args['north'], args['east'] = self.swne
2312 args['centerlon'] = (args['north'] + args['south']) / 2.
2313 args['centerlat'] = (args['west'] + args['east']) / 2.
2314 args['minzoom'] = self.tminz
2315 args['maxzoom'] = self.tmaxz
2316 args['beginzoom'] = self.tmaxz
2317 args['tile_size'] = self.tile_size # not used
2318 args['tileformat'] = self.tileext
2319 args['publishurl'] = self.options.url # not used
2320 args['copyright'] = self.options.copyright.replace('"', '\\"')
2321
2322 s = """<!DOCTYPE html>
2323 <html lang="en">
2324 <head>
2325 <meta charset="utf-8">
2326 <meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no' />
2327 <title>%(htmltitle)s</title>
2328
2329 <!-- Leaflet -->
2330 <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.5/leaflet.css" />
2331 <script src="http://cdn.leafletjs.com/leaflet-0.7.5/leaflet.js"></script>
2332
2333 <style>
2334 body { margin:0; padding:0; }
2335 body, table, tr, td, th, div, h1, h2, input { font-family: "Calibri", "Trebuchet MS", "Ubuntu", Serif; font-size: 11pt; }
2336 #map { position:absolute; top:0; bottom:0; width:100%%; } /* full size */
2337 .ctl {
2338 padding: 2px 10px 2px 10px;
2339 background: white;
2340 background: rgba(255,255,255,0.9);
2341 box-shadow: 0 0 15px rgba(0,0,0,0.2);
2342 border-radius: 5px;
2343 text-align: right;
2344 }
2345 .title {
2346 font-size: 18pt;
2347 font-weight: bold;
2348 }
2349 .src {
2350 font-size: 10pt;
2351 }
2352
2353 </style>
2354
2355 </head>
2356 <body>
2357
2358 <div id="map"></div>
2359
2360 <script>
2361 /* **** Leaflet **** */
2362
2363 // Base layers
2364 // .. OpenStreetMap
2365 var osm = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors', minZoom: %(minzoom)s, maxZoom: %(maxzoom)s});
2366
2367 // .. CartoDB Positron
2368 var cartodb = L.tileLayer('http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', {attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, &copy; <a href="http://cartodb.com/attributions">CartoDB</a>', minZoom: %(minzoom)s, maxZoom: %(maxzoom)s});
2369
2370 // .. OSM Toner
2371 var toner = L.tileLayer('http://{s}.tile.stamen.com/toner/{z}/{x}/{y}.png', {attribution: 'Map tiles by <a href="http://stamen.com">Stamen Design</a>, under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>. Data by <a href="http://openstreetmap.org">OpenStreetMap</a>, under <a href="http://www.openstreetmap.org/copyright">ODbL</a>.', minZoom: %(minzoom)s, maxZoom: %(maxzoom)s});
2372
2373 // .. White background
2374 var white = L.tileLayer("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEAAQMAAABmvDolAAAAA1BMVEX///+nxBvIAAAAH0lEQVQYGe3BAQ0AAADCIPunfg43YAAAAAAAAAAA5wIhAAAB9aK9BAAAAABJRU5ErkJggg==", {minZoom: %(minzoom)s, maxZoom: %(maxzoom)s});
2375
2376 // Overlay layers (TMS)
2377 var lyr = L.tileLayer('./{z}/{x}/{y}.%(tileformat)s', {tms: true, opacity: 0.7, attribution: "%(copyright)s", minZoom: %(minzoom)s, maxZoom: %(maxzoom)s});
2378
2379 // Map
2380 var map = L.map('map', {
2381 center: [%(centerlon)s, %(centerlat)s],
2382 zoom: %(beginzoom)s,
2383 minZoom: %(minzoom)s,
2384 maxZoom: %(maxzoom)s,
2385 layers: [osm]
2386 });
2387
2388 var basemaps = {"OpenStreetMap": osm, "CartoDB Positron": cartodb, "Stamen Toner": toner, "Without background": white}
2389 var overlaymaps = {"Layer": lyr}
2390
2391 // Title
2392 var title = L.control();
2393 title.onAdd = function(map) {
2394 this._div = L.DomUtil.create('div', 'ctl title');
2395 this.update();
2396 return this._div;
2397 };
2398 title.update = function(props) {
2399 this._div.innerHTML = "%(title)s";
2400 };
2401 title.addTo(map);
2402
2403 // Note
2404 var src = 'Generated by <a href="http://www.klokan.cz/projects/gdal2tiles/">GDAL2Tiles</a>, Copyright &copy; 2008 <a href="http://www.klokan.cz/">Klokan Petr Pridal</a>, <a href="http://www.gdal.org/">GDAL</a> &amp; <a href="http://www.osgeo.org/">OSGeo</a> <a href="http://code.google.com/soc/">GSoC</a>';
2405 var title = L.control({position: 'bottomleft'});
2406 title.onAdd = function(map) {
2407 this._div = L.DomUtil.create('div', 'ctl src');
2408 this.update();
2409 return this._div;
2410 };
2411 title.update = function(props) {
2412 this._div.innerHTML = src;
2413 };
2414 title.addTo(map);
2415
2416
2417 // Add base layers
2418 L.control.layers(basemaps, overlaymaps, {collapsed: false}).addTo(map);
2419
2420 // Fit to overlay bounds (SW and NE points with (lat, lon))
2421 map.fitBounds([[%(south)s, %(east)s], [%(north)s, %(west)s]]);
2422
2423 </script>
2424
2425 </body>
2426 </html>
2427
2428 """ % args # noqa
2429
2430 return s
2431
2432 def generate_openlayers(self):
2433 """
2434 Template for openlayers.html implementing overlay of available Spherical Mercator layers.
2435
2436 It returns filled string. Expected variables:
2437 title, bingkey, north, south, east, west, minzoom, maxzoom, tile_size, tileformat, publishurl
2438 """
2439
2440 args = {}
2441 args['title'] = self.options.title
2442 args['bingkey'] = self.options.bingkey
2443 args['south'], args['west'], args['north'], args['east'] = self.swne
2444 args['minzoom'] = self.tminz
2445 args['maxzoom'] = self.tmaxz
2446 args['tile_size'] = self.tile_size
2447 args['tileformat'] = self.tileext
2448 args['publishurl'] = self.options.url
2449 args['copyright'] = self.options.copyright
2450 if self.options.tmscompatible:
2451 args['tmsoffset'] = "-1"
2452 else:
2453 args['tmsoffset'] = ""
2454 if self.options.profile == 'raster':
2455 args['rasterzoomlevels'] = self.tmaxz + 1
2456 args['rastermaxresolution'] = 2**(self.nativezoom) * self.out_gt[1]
2457
2458 s = r"""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
2459 <html xmlns="http://www.w3.org/1999/xhtml"
2460 <head>
2461 <title>%(title)s</title>
2462 <meta http-equiv='imagetoolbar' content='no'/>
2463 <style type="text/css"> v\:* {behavior:url(#default#VML);}
2464 html, body { overflow: hidden; padding: 0; height: 100%%; width: 100%%; font-family: 'Lucida Grande',Geneva,Arial,Verdana,sans-serif; }
2465 body { margin: 10px; background: #fff; }
2466 h1 { margin: 0; padding: 6px; border:0; font-size: 20pt; }
2467 #header { height: 43px; padding: 0; background-color: #eee; border: 1px solid #888; }
2468 #subheader { height: 12px; text-align: right; font-size: 10px; color: #555;}
2469 #map { height: 95%%; border: 1px solid #888; }
2470 .olImageLoadError { display: none; }
2471 .olControlLayerSwitcher .layersDiv { border-radius: 10px 0 0 10px; }
2472 </style>""" % args # noqa
2473
2474 if self.options.profile == 'mercator':
2475 s += """
2476 <script src='http://maps.google.com/maps/api/js?sensor=false&v=3.7'></script>
2477 """ % args
2478
2479 s += """
2480 <script src="http://www.openlayers.org/api/2.12/OpenLayers.js"></script>
2481 <script>
2482 var map;
2483 var mapBounds = new OpenLayers.Bounds( %(west)s, %(south)s, %(east)s, %(north)s);
2484 var mapMinZoom = %(minzoom)s;
2485 var mapMaxZoom = %(maxzoom)s;
2486 var emptyTileURL = "http://www.maptiler.org/img/none.png";
2487 OpenLayers.IMAGE_RELOAD_ATTEMPTS = 3;
2488
2489 function init(){""" % args
2490
2491 if self.options.profile == 'mercator':
2492 s += """
2493 var options = {
2494 div: "map",
2495 controls: [],
2496 projection: "EPSG:3857",
2497 displayProjection: new OpenLayers.Projection("EPSG:4326"),
2498 numZoomLevels: 20
2499 };
2500 map = new OpenLayers.Map(options);
2501
2502 // Create Google Mercator layers
2503 var gmap = new OpenLayers.Layer.Google("Google Streets",
2504 {
2505 type: google.maps.MapTypeId.ROADMAP,
2506 sphericalMercator: true
2507 });
2508 var gsat = new OpenLayers.Layer.Google("Google Satellite",
2509 {
2510 type: google.maps.MapTypeId.SATELLITE,
2511 sphericalMercator: true
2512 });
2513 var ghyb = new OpenLayers.Layer.Google("Google Hybrid",
2514 {
2515 type: google.maps.MapTypeId.HYBRID,
2516 sphericalMercator: true
2517 });
2518 var gter = new OpenLayers.Layer.Google("Google Terrain",
2519 {
2520 type: google.maps.MapTypeId.TERRAIN,
2521 sphericalMercator: true
2522 });
2523
2524 // Create Bing layers
2525 var broad = new OpenLayers.Layer.Bing({
2526 name: "Bing Roads",
2527 key: "%(bingkey)s",
2528 type: "Road",
2529 sphericalMercator: true
2530 });
2531 var baer = new OpenLayers.Layer.Bing({
2532 name: "Bing Aerial",
2533 key: "%(bingkey)s",
2534 type: "Aerial",
2535 sphericalMercator: true
2536 });
2537 var bhyb = new OpenLayers.Layer.Bing({
2538 name: "Bing Hybrid",
2539 key: "%(bingkey)s",
2540 type: "AerialWithLabels",
2541 sphericalMercator: true
2542 });
2543
2544 // Create OSM layer
2545 var osm = new OpenLayers.Layer.OSM("OpenStreetMap");
2546
2547 // create TMS Overlay layer
2548 var tmsoverlay = new OpenLayers.Layer.TMS("TMS Overlay", "",
2549 {
2550 serviceVersion: '.',
2551 layername: '.',
2552 alpha: true,
2553 type: '%(tileformat)s',
2554 isBaseLayer: false,
2555 getURL: getURL
2556 });
2557 if (OpenLayers.Util.alphaHack() == false) {
2558 tmsoverlay.setOpacity(0.7);
2559 }
2560
2561 map.addLayers([gmap, gsat, ghyb, gter,
2562 broad, baer, bhyb,
2563 osm, tmsoverlay]);
2564
2565 var switcherControl = new OpenLayers.Control.LayerSwitcher();
2566 map.addControl(switcherControl);
2567 switcherControl.maximizeControl();
2568
2569 map.zoomToExtent(mapBounds.transform(map.displayProjection, map.projection));
2570 """ % args # noqa
2571
2572 elif self.options.profile == 'geodetic':
2573 s += """
2574 var options = {
2575 div: "map",
2576 controls: [],
2577 projection: "EPSG:4326"
2578 };
2579 map = new OpenLayers.Map(options);
2580
2581 var wms = new OpenLayers.Layer.WMS("VMap0",
2582 "http://tilecache.osgeo.org/wms-c/Basic.py?",
2583 {
2584 layers: 'basic',
2585 format: 'image/png'
2586 }
2587 );
2588 var tmsoverlay = new OpenLayers.Layer.TMS("TMS Overlay", "",
2589 {
2590 serviceVersion: '.',
2591 layername: '.',
2592 alpha: true,
2593 type: '%(tileformat)s',
2594 isBaseLayer: false,
2595 getURL: getURL
2596 });
2597 if (OpenLayers.Util.alphaHack() == false) {
2598 tmsoverlay.setOpacity(0.7);
2599 }
2600
2601 map.addLayers([wms,tmsoverlay]);
2602
2603 var switcherControl = new OpenLayers.Control.LayerSwitcher();
2604 map.addControl(switcherControl);
2605 switcherControl.maximizeControl();
2606
2607 map.zoomToExtent(mapBounds);
2608 """ % args # noqa
2609
2610 elif self.options.profile == 'raster':
2611 s += """
2612 var options = {
2613 div: "map",
2614 controls: [],
2615 maxExtent: new OpenLayers.Bounds(%(west)s, %(south)s, %(east)s, %(north)s),
2616 maxResolution: %(rastermaxresolution)f,
2617 numZoomLevels: %(rasterzoomlevels)d
2618 };
2619 map = new OpenLayers.Map(options);
2620
2621 var layer = new OpenLayers.Layer.TMS("TMS Layer", "",
2622 {
2623 serviceVersion: '.',
2624 layername: '.',
2625 alpha: true,
2626 type: '%(tileformat)s',
2627 getURL: getURL
2628 });
2629
2630 map.addLayer(layer);
2631 map.zoomToExtent(mapBounds);
2632 """ % args # noqa
2633
2634 s += """
2635 map.addControls([new OpenLayers.Control.PanZoomBar(),
2636 new OpenLayers.Control.Navigation(),
2637 new OpenLayers.Control.MousePosition(),
2638 new OpenLayers.Control.ArgParser(),
2639 new OpenLayers.Control.Attribution()]);
2640 }
2641 """ % args
2642
2643 if self.options.profile == 'mercator':
2644 s += """
2645 function getURL(bounds) {
2646 bounds = this.adjustBounds(bounds);
2647 var res = this.getServerResolution();
2648 var x = Math.round((bounds.left - this.tileOrigin.lon) / (res * this.tileSize.w));
2649 var y = Math.round((bounds.bottom - this.tileOrigin.lat) / (res * this.tileSize.h));
2650 var z = this.getServerZoom();
2651 if (this.map.baseLayer.CLASS_NAME === 'OpenLayers.Layer.Bing') {
2652 z+=1;
2653 }
2654 var path = this.serviceVersion + "/" + this.layername + "/" + z + "/" + x + "/" + y + "." + this.type;
2655 var url = this.url;
2656 if (OpenLayers.Util.isArray(url)) {
2657 url = this.selectUrl(path, url);
2658 }
2659 if (mapBounds.intersectsBounds(bounds) && (z >= mapMinZoom) && (z <= mapMaxZoom)) {
2660 return url + path;
2661 } else {
2662 return emptyTileURL;
2663 }
2664 }
2665 """ % args # noqa
2666
2667 elif self.options.profile == 'geodetic':
2668 s += """
2669 function getURL(bounds) {
2670 bounds = this.adjustBounds(bounds);
2671 var res = this.getServerResolution();
2672 var x = Math.round((bounds.left - this.tileOrigin.lon) / (res * this.tileSize.w));
2673 var y = Math.round((bounds.bottom - this.tileOrigin.lat) / (res * this.tileSize.h));
2674 var z = this.getServerZoom()%(tmsoffset)s;
2675 var path = this.serviceVersion + "/" + this.layername + "/" + z + "/" + x + "/" + y + "." + this.type;
2676 var url = this.url;
2677 if (OpenLayers.Util.isArray(url)) {
2678 url = this.selectUrl(path, url);
2679 }
2680 if (mapBounds.intersectsBounds(bounds) && (z >= mapMinZoom) && (z <= mapMaxZoom)) {
2681 return url + path;
2682 } else {
2683 return emptyTileURL;
2684 }
2685 }
2686 """ % args # noqa
2687
2688 elif self.options.profile == 'raster':
2689 s += """
2690 function getURL(bounds) {
2691 bounds = this.adjustBounds(bounds);
2692 var res = this.getServerResolution();
2693 var x = Math.round((bounds.left - this.tileOrigin.lon) / (res * this.tileSize.w));
2694 var y = Math.round((bounds.bottom - this.tileOrigin.lat) / (res * this.tileSize.h));
2695 var z = this.getServerZoom();
2696 var path = this.serviceVersion + "/" + this.layername + "/" + z + "/" + x + "/" + y + "." + this.type;
2697 var url = this.url;
2698 if (OpenLayers.Util.isArray(url)) {
2699 url = this.selectUrl(path, url);
2700 }
2701 if (mapBounds.intersectsBounds(bounds) && (z >= mapMinZoom) && (z <= mapMaxZoom)) {
2702 return url + path;
2703 } else {
2704 return emptyTileURL;
2705 }
2706 }
2707 """ % args # noqa
2708
2709 s += """
2710 function getWindowHeight() {
2711 if (self.innerHeight) return self.innerHeight;
2712 if (document.documentElement && document.documentElement.clientHeight)
2713 return document.documentElement.clientHeight;
2714 if (document.body) return document.body.clientHeight;
2715 return 0;
2716 }
2717
2718 function getWindowWidth() {
2719 if (self.innerWidth) return self.innerWidth;
2720 if (document.documentElement && document.documentElement.clientWidth)
2721 return document.documentElement.clientWidth;
2722 if (document.body) return document.body.clientWidth;
2723 return 0;
2724 }
2725
2726 function resize() {
2727 var map = document.getElementById("map");
2728 var header = document.getElementById("header");
2729 var subheader = document.getElementById("subheader");
2730 map.style.height = (getWindowHeight()-80) + "px";
2731 map.style.width = (getWindowWidth()-20) + "px";
2732 header.style.width = (getWindowWidth()-20) + "px";
2733 subheader.style.width = (getWindowWidth()-20) + "px";
2734 if (map.updateSize) { map.updateSize(); };
2735 }
2736
2737 onresize=function(){ resize(); };
2738
2739 </script>
2740 </head>
2741 <body onload="init()">
2742 <div id="header"><h1>%(title)s</h1></div>
2743 <div id="subheader">Generated by <a href="http://www.klokan.cz/projects/gdal2tiles/">GDAL2Tiles</a>, Copyright &copy; 2008 <a href="http://www.klokan.cz/">Klokan Petr Pridal</a>, <a href="http://www.gdal.org/">GDAL</a> &amp; <a href="http://www.osgeo.org/">OSGeo</a> <a href="http://code.google.com/soc/">GSoC</a>
2744 <!-- PLEASE, LET THIS NOTE ABOUT AUTHOR AND PROJECT SOMEWHERE ON YOUR WEBSITE, OR AT LEAST IN THE COMMENT IN HTML. THANK YOU -->
2745 </div>
2746 <div id="map"></div>
2747 <script type="text/javascript" >resize()</script>
2748 </body>
2749 </html>""" % args # noqa
2750
2751 return s
2752
2753
2754def worker_tile_details(input_file, output_folder, options):
2755 gdal2tiles = GDAL2Tiles(input_file, output_folder, options)
2756 gdal2tiles.open_input()
2757 gdal2tiles.generate_metadata()
2758 tile_job_info, tile_details = gdal2tiles.generate_base_tiles()
2759 return tile_job_info, tile_details
2760
2761class ProgressBar(object):
2762
2763 def __init__(self, total_items):
2764 self.total_items = total_items
2765 self.nb_items_done = 0
2766 self.current_progress = 0
2767 self.STEP = 2.5
2768
2769 def start(self):
2770 sys.stdout.write("0")
2771
2772 def log_progress(self, nb_items=1):
2773 self.nb_items_done += nb_items
2774 progress = float(self.nb_items_done) / self.total_items * 100
2775 if progress >= self.current_progress + self.STEP:
2776 done = False
2777 while not done:
2778 if self.current_progress + self.STEP <= progress:
2779 self.current_progress += self.STEP
2780 if self.current_progress % 10 == 0:
2781 sys.stdout.write(str(int(self.current_progress)))
2782 if self.current_progress == 100:
2783 sys.stdout.write("\n")
2784 else:
2785 sys.stdout.write(".")
2786 else:
2787 done = True
2788 sys.stdout.flush()
2789
2790
2791def get_tile_swne(tile_job_info, options):
2792 if options.profile == 'mercator':
2793 mercator = GlobalMercator()
2794 tile_swne = mercator.TileLatLonBounds
2795 elif options.profile == 'geodetic':
2796 geodetic = GlobalGeodetic(options.tmscompatible)
2797 tile_swne = geodetic.TileLatLonBounds
2798 elif options.profile == 'raster':
2799 srs4326 = osr.SpatialReference()
2800 srs4326.ImportFromEPSG(4326)
2801 srs4326.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER)
2802 if tile_job_info.kml and tile_job_info.in_srs_wkt:
2803 in_srs = osr.SpatialReference()
2804 in_srs.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER)
2805 in_srs.ImportFromWkt(tile_job_info.in_srs_wkt)
2806 ct = osr.CoordinateTransformation(in_srs, srs4326)
2807
2808 def rastertileswne(x, y, z):
2809 pixelsizex = (2 ** (tile_job_info.tmaxz - z) * tile_job_info.out_geo_trans[1])
2810 west = tile_job_info.out_geo_trans[0] + x * tile_job_info.tile_size * pixelsizex
2811 east = west + tile_job_info.tile_size * pixelsizex
2812 south = tile_job_info.ominy + y * tile_job_info.tile_size * pixelsizex
2813 north = south + tile_job_info.tile_size * pixelsizex
2814 if not tile_job_info.is_epsg_4326:
2815 # Transformation to EPSG:4326 (WGS84 datum)
2816 west, south = ct.TransformPoint(west, south)[:2]
2817 east, north = ct.TransformPoint(east, north)[:2]
2818 return south, west, north, east
2819
2820 tile_swne = rastertileswne
2821 else:
2822 tile_swne = lambda x, y, z: (0, 0, 0, 0) # noqa
2823 else:
2824 tile_swne = lambda x, y, z: (0, 0, 0, 0) # noqa
2825
2826 return tile_swne
2827
2828
2829def single_threaded_tiling(input_file, output_folder, options):
2830 """
2831 Keep a single threaded version that stays clear of multiprocessing, for platforms that would not
2832 support it
2833 """
2834 if options.verbose:
2835 print("Begin tiles details calc")
2836 conf, tile_details = worker_tile_details(input_file, output_folder, options)
2837
2838 if options.verbose:
2839 print("Tiles details calc complete.")
2840
2841 if not options.verbose and not options.quiet:
2842 progress_bar = ProgressBar(len(tile_details))
2843 progress_bar.start()
2844
2845 for tile_detail in tile_details:
2846 create_base_tile(conf, tile_detail)
2847
2848 if not options.verbose and not options.quiet:
2849 progress_bar.log_progress()
2850
2851 if getattr(threadLocal, 'cached_ds', None):
2852 del threadLocal.cached_ds
2853
2854 create_overview_tiles(conf, output_folder, options)
2855
2856 shutil.rmtree(os.path.dirname(conf.src_file))
2857
2858
2859def multi_threaded_tiling(input_file, output_folder, options):
2860 nb_processes = options.nb_processes or 1
2861
2862 # Make sure that all processes do not consume more than GDAL_CACHEMAX
2863 os.environ['GDAL_CACHEMAX'] = '%d' % int(gdal.GetCacheMax() / nb_processes)
2864
2865 pool = Pool(processes=nb_processes)
2866
2867 if options.verbose:
2868 print("Begin tiles details calc")
2869
2870 conf, tile_details = pool.apply(worker_tile_details, [input_file, output_folder, options])
2871
2872 if options.verbose:
2873 print("Tiles details calc complete.")
2874
2875 if not options.verbose and not options.quiet:
2876 progress_bar = ProgressBar(len(tile_details))
2877 progress_bar.start()
2878
2879 # TODO: gbataille - check the confs for which each element is an array... one useless level?
2880 # TODO: gbataille - assign an ID to each job for print in verbose mode "ReadRaster Extent ..."
2881 for _ in pool.imap_unordered(partial(create_base_tile, conf), tile_details, chunksize=128):
2882 if not options.verbose and not options.quiet:
2883 progress_bar.log_progress()
2884
2885 pool.close()
2886 pool.join() # Jobs finished
2887
2888 create_overview_tiles(conf, output_folder, options)
2889
2890 shutil.rmtree(os.path.dirname(conf.src_file))
2891
2892
2893def main():
2894 # TODO: gbataille - use mkdtemp to work in a temp directory
2895 # TODO: gbataille - debug intermediate tiles.vrt not produced anymore?
2896 # TODO: gbataille - Refactor generate overview tiles to not depend on self variables
2897 argv = gdal.GeneralCmdLineProcessor(sys.argv)
2898 input_file, output_folder, options = process_args(argv[1:])
2899 nb_processes = options.nb_processes or 1
2900
2901 if nb_processes == 1:
2902 single_threaded_tiling(input_file, output_folder, options)
2903 else:
2904 multi_threaded_tiling(input_file, output_folder, options)
2905
2906
2907if __name__ == '__main__':
2908 main()
2909
2910# vim: set tabstop=4 shiftwidth=4 expandtab:
Note: See TracBrowser for help on using the repository browser.