forked from jonasstein/scanaerial
-
Notifications
You must be signed in to change notification settings - Fork 0
/
canvas.py
177 lines (145 loc) · 6.13 KB
/
canvas.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
if __name__ == "__main__":
exit(0)
from PIL import Image, ImageFilter
try:
from urllib.request import urlopen
from urllib.error import URLError
from urllib.error import HTTPError
except ImportError:
from urllib2 import urlopen
from urllib2 import URLError
from urllib2 import HTTPError
import io
import datetime
import sys
from time import clock
from debug import debug
#
import projections
time_str = {0:" first ", 1:" second ", 2:" third and last "}
class WmsCanvas:
def __init__(self, wms_url = None, proj = "EPSG:4326", zoom = 4, tile_size = None, mode = "RGBA", bing_api = False):
self.wms_url = wms_url
self.bing_api = bing_api
self.zoom = zoom
self.proj = proj
self.mode = mode
self.tile_height = 256
self.tile_width = 256
if tile_size:
self.tile_width, self.tile_height = tile_size
self.tiles = {}
def __setitem__ (self, x, v):
x, y = x
tile_x = x // self.tile_height
x = x % self.tile_height
tile_y = y // self.tile_width
y = y % self.tile_width
try:
self.tiles[(tile_x, tile_y)]["pix"][x, y] = v
except KeyError:
self.FetchTile(tile_x, tile_y)
self.tiles[(tile_x, tile_y)]["pix"][x, y] = v
def __getitem__ (self, x):
x, y = x
tile_x = x // self.tile_height
x = x % self.tile_height
tile_y = y // self.tile_width
y = y % self.tile_width
for i in range(0, 3):
try:
return self.tiles[(tile_x, tile_y)]["pix"][x, y]
except KeyError:
self.FetchTile(tile_x, tile_y)
raise KeyError("internal error while fetching tile")
def ConstructTileUrl (self, x, y):
if self.bing_api:
return self.wms_url.replace("{quadkey}", self.ConstructQuadkey(x, y))
a, b, c, d = projections.from4326(projections.bbox_by_tile(self.zoom, x, y, self.proj), self.proj)
return self.wms_url + "width=%s&height=%s&srs=%s&bbox=%s,%s,%s,%s" % (self.tile_width, self.tile_height, self.proj, a, b, c, d)
def baseN(self, num, b, numerals="0123456789abcdefghijklmnopqrstuvwxyz"):
"""Convert num into string with base b"""
return ((num == 0) and numerals[0]) or (self.baseN(num // b, b, numerals).lstrip(numerals[0]) + numerals[num % b])
def ConstructQuadkey (self, tileX, tileY):
"""return Bing quadkey for given integer tile
see (http://msdn.microsoft.com/en-us/library/bb259689.aspx)"""
tileX2 = self.baseN(tileX, 2)
tileY2 = self.baseN(tileY, 2)
pad = max(len(tileX2), len(tileY2))
tileX2 = "0"*(pad - len(tileX2)) + tileX2
tileY2 = "0"*(pad - len(tileY2)) + tileY2
quadkey2 = ""
for x in range(pad):
quadkey2 = quadkey2 + tileY2[x] + tileX2[x]
quadkey = int(quadkey2, 2)
quadkey4 = self.baseN(quadkey, 4)
return quadkey4
def FetchTile(self, x, y):
dl_done = False
server_error = False
if (x, y) in self.tiles:
return
tile_data = ""
if self.wms_url:
remote = self.ConstructTileUrl (x, y)
start = clock()
for dl_retrys in range(0, 3):
try:
contents = urlopen(remote).read()
except URLError as detail:
server_error = True
debug("error while fetching tile (" + str(x) + ", " + str(y) + ": " + str(detail))
debug("retry download" + time_str[dl_retrys] + "time")
continue
except HTTPError as detail:
server_error = True
debug("error while fetching tile (" + str(x) + ", " + str(y) + ": " + str(detail))
debug("retry download" + time_str[dl_retrys] + "time")
continue
debug("Download took %s sec" % str(clock() - start))
try:
tile_data = Image.open(io.BytesIO(contents))
except:
debug("error while loading tile image-data corrupt")
debug("retry download" + time_str[dl_retrys] + "time")
continue
dl_done = True
break
if not dl_done:
if server_error:
raise URLError(detail)
tile_data = Image.new(self.mode, (self.tile_width, self.tile_height))
debug("could not be loaded, blanking tile")
if tile_data.mode != self.mode:
tile_data = tile_data.convert(self.mode)
self.tiles[(x, y)] = {}
self.tiles[(x, y)]["im"] = tile_data
self.tiles[(x, y)]["pix"] = tile_data.load()
def PixelAs4326(self, x, y):
scale = 1.0
if self.bing_api:
scale = 0.5
return projections.coords_by_tile(self.zoom, scale * x / self.tile_width, scale * y / self.tile_height, self.proj)
def PixelFrom4326(self, lon, lat):
a, b = projections.tile_by_coords(lon, lat, self.zoom, self.proj)
if self.bing_api:
a = a*2
b = b*2
return a * self.tile_width, b * self.tile_height
def MaxFilter(self, size = 3):
for tile in self.tiles:
self.tiles[tile]["pix"] = self.tiles[tile]["im"].filter(ImageFilter.MedianFilter(size)).load()