-
Notifications
You must be signed in to change notification settings - Fork 1
/
util_raster.py
420 lines (355 loc) · 11 KB
/
util_raster.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
import concurrent.futures
import math
import os
import tempfile
from typing import Iterator, Union, Optional
import cv2
import geopandas as gpd
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pyproj
import pyproj.aoi
import rasterio
import rasterio.plot
import rasterio.plot
from geopandas import GeoDataFrame
def _deg2num(lon_deg, lat_deg, zoom, always_xy, floored: bool):
# lat_rad = math.radians(lat_deg)
lat_rad = lat_deg * math.pi / 180.0
n = 2 ** zoom
xtile = ((lon_deg + 180.0) / 360.0 * n)
ytile = ((1.0 - math.asinh(math.tan(lat_rad)) / math.pi) / 2.0 * n)
if floored:
xtile = int(xtile)
ytile = int(ytile)
if always_xy:
return xtile, ytile
else:
return ytile, xtile
def deg2num(
lon_deg: float,
lat_deg: float,
zoom: int,
always_xy=True,
floored=False,
) -> tuple[float, float]:
"""
:param lat_deg:
:param lon_deg:
:param zoom:
:return: xtile, ytile
"""
return _deg2num(lon_deg, lat_deg, zoom, always_xy, floored)
def _num2deg(xtile, ytile, zoom, always_xy):
n = 2 ** zoom
lon_deg = xtile / n * 360 - 180
lat_rad = math.atan(math.sinh(math.pi * (1.0 - 2.0 * ytile / n)))
# lat_deg = math.degrees(lat_rad)
lat_deg = lat_rad * 180.0 / math.pi
if always_xy:
return lon_deg, lat_deg
else:
return lat_deg, lon_deg
# return lat_deg, lon_deg
def num2deg(xtile: float, ytile: float, zoom: int, always_xy=False) -> tuple[float, float]:
"""
:param xtile:
:param ytile:
:param zoom:
:return: latitude, longitude
"""
return _num2deg(xtile, ytile, zoom, always_xy)
def _xtiles_from_lons(lons, zoom, ):
length = len(lons)
n = 2 ** zoom
xtiles = np.zeros(length, dtype=np.uint32)
for k in range(length):
xtiles[k] = ((lons[k] + 180) / 360 * n)
return xtiles
def xtiles_from_lons(lons: np.ndarray, zoom: int):
return _xtiles_from_lons(lons, zoom)
def _ytiles_from_lats(lons, zoom, ):
length = len(lons)
n = 2 ** zoom
ytiles = np.zeros(length, dtype=np.uint32)
for k in range(length):
ytiles[k] = ((lons[k] + 180) / 360 * n)
return ytiles
def ytiles_from_lats(lats: np.ndarray, zoom: int):
return _ytiles_from_lats(lats, zoom)
def _lons_from_xtiles(xtiles, zoom):
length = len(xtiles)
n = 2 ** zoom
lons = np.zeros(length, dtype=np.float64)
for k in range(length):
lons[k] = 360.0 * xtiles[k] / n - 180
return lons
def lons_from_xtiles(xtiles: np.ndarray, zoom: int):
return _lons_from_xtiles(xtiles, zoom)
def _lats_from_ytiles(ytiles, zoom):
length = len(ytiles)
n = 2 ** zoom
lats = np.zeros(length, dtype=np.float64)
rad_to_deg = 180.0 / math.pi
for k in range(length):
lats[k] = (
math.atan(math.sinh(math.pi * (1.0 - 2.0 * ytiles[k] / n))) * rad_to_deg
)
return lats
def lats_from_ytiles(ytiles: np.ndarray, zoom: int):
return _lats_from_ytiles(ytiles, zoom)
def get_utm_from_lon_lat(lon: float, lat: float) -> pyproj.crs.CRS:
buffer = .001
utm_crs_list = pyproj.database.query_utm_crs_info(
datum_name='WGS 84',
area_of_interest=pyproj.aoi.AreaOfInterest(
west_lon_degree=lon - buffer,
south_lat_degree=lat - buffer,
east_lon_degree=lon + buffer,
north_lat_degree=lat + buffer,
),
)
utm_crs = pyproj.CRS.from_epsg(utm_crs_list[0].code)
return utm_crs
def get_raster_size(
gw: float,
gs: float,
ge: float,
gn: float,
zoom: int,
mask: Optional[list[float]] = None,
) -> int:
"""
:param gw: minx
:param gs: miny
:param ge: maxx
:param gn: maxy
:param zoom: slippy tile zoom
:param mask: [miny, minx, maxy, maxx]
:return: size of raster to be generated
"""
if mask is not None:
gs = max(gs, mask[0])
gw = max(gw, mask[1])
gn = min(gn, mask[2])
ge = min(ge, mask[3])
tw, tn = deg2num(gw, gn, zoom, True, floored=True)
te, ts = deg2num(ge, gs, zoom, True, floored=True)
ts += 1
te += 1
tiles = (te - tw) * (ts - tn)
# TODO: if tile cells or dtype changes this must too
cells = 65536 * tiles
# 2 bytes per int16 cell, if the dtype changes so must this
bytes: int = cells * 2
return bytes
def get_shadow_image(
gw: float,
gs: float,
ge: float,
gn: float,
zoom: int,
basedir: str,
mask: Optional[list[float]] = None,
threshold: tuple[float, float] = (0.0, 1.0)
) -> np.ndarray:
print(gw, gs, ge, gn, zoom, basedir, mask, threshold)
if mask is not None:
gs = max(gs, mask[0])
gw = max(gw, mask[1])
gn = min(gn, mask[2])
ge = min(ge, mask[3])
# Note: python 3.9 glob.glob() does not have kwarg root_dir
tw, tn = deg2num(gw, gn, zoom, True, floored=True)
te, ts = deg2num(ge, gs, zoom, True, floored=True)
ytiles = np.arange(tn, ts + 1, dtype=np.uint32)
xtiles = np.arange(tw, te + 1, dtype=np.uint32)
r_tilecount = len(ytiles)
c_tilecount = len(xtiles)
# print(r_tilecount, c_tilecount)
# return
cslices = {
xtile: slice(l, l + 256)
for l, xtile in zip(range(0, 256 * c_tilecount, 256), xtiles)
}
rslices = {
ytile: slice(l, l + 256)
for l, ytile in zip(range(0, 256 * r_tilecount, 256), ytiles)
}
ytiles = ytiles.astype('U10')
xtiles = xtiles.astype('U10')
ytiles = np.char.add(ytiles, '.png')
xtiles = np.char.add(xtiles, os.sep)
ytiles = np.repeat(ytiles, c_tilecount)
xtiles = np.tile(xtiles, r_tilecount)
tiles = np.char.add(xtiles, ytiles)
directory = os.path.join(basedir, str(zoom)) + os.sep
directory = os.path.normpath(directory)
if not directory.endswith(os.sep):
directory += os.sep
relevant = np.char.add(directory, tiles)
paths = [
path
for path in relevant
if os.path.exists(path)
]
images: Iterator[np.ndarray] = concurrent.futures.ThreadPoolExecutor().map(lambda p: cv2.imread(p)[:, :, 0], paths)
partitions: Iterator[str] = (
os.path.normpath(path.rpartition('.')[0])
for path in paths
)
partitions: Iterator[tuple[str, str, str]] = (
partition.rpartition(os.sep)
for partition in partitions
)
xtiles_ytiles: Iterator[tuple[int, int]] = (
(
int(partition[0].rpartition(os.sep)[2]),
int(partition[2])
)
for partition in partitions
)
raster = np.zeros((256 * r_tilecount, 256 * c_tilecount), dtype=np.int16)
for (xtile, ytile), image in zip(xtiles_ytiles, images):
raster[rslices[ytile], cslices[xtile]] = image
floor = math.floor(threshold[0] * 255)
ceil = math.ceil(threshold[1] * 255)
raster[np.logical_or(
raster < floor,
raster > ceil
)] = -1
# if threshold > 0:
# cutoff = math.ceil(threshold * 255)
# image[np.logical_and(0 <= image, image < cutoff)] = nodata
return raster
def get_raster_path(
gw: float,
gs: float,
ge: float,
gn: float,
zoom: int,
basedir: str,
threshold: tuple[float, float] = (0.0, 1.0),
outdir: str = None,
outpath: str = None,
mask: Optional[list[float]] = None,
nodata: int = -1
) -> str:
if mask is not None:
gs = max(gs, mask[0])
gw = max(gw, mask[1])
gn = min(gn, mask[2])
ge = min(ge, mask[3])
tw, tn = deg2num(gw, gn, zoom, True, floored=True)
te, ts = deg2num(ge, gs, zoom, True, floored=True)
te += 1
ts += 1
if outpath is None:
if outdir is None:
outdir = tempfile.gettempdir()
if not os.path.exists(outdir):
os.makedirs(outdir)
outpath = os.path.join(outdir, f'{zoom}_{tw}_{ts}_{te}_{tn}.tif')
image = get_shadow_image(
gw,
gs,
ge,
gn,
zoom=zoom,
basedir=basedir,
threshold=threshold,
)
height, width = image.shape
# width, height = image.shape
gw, gs, = num2deg(tw, ts, zoom, True)
ge, gn = num2deg(te, tn, zoom, True)
transform = rasterio.transform.from_bounds(gw, gs, ge, gn, width, height)
with rasterio.open(
outpath,
'w',
driver='GTiff',
height=height,
width=width,
count=1,
dtype=np.int16,
nodata=nodata,
crs=4326,
transform=transform,
) as f:
f.write(image, 1)
return outpath
#
# def get_raster_affine(
# gw: float,
# gs: float,
# ge: float,
# gn: float,
# zoom: int,
# basedir: str,
# threshold: tuple[float, float] = (0.0, 1.0)
# ) -> tuple[np.ndarray, tuple]:
# "Returns the array and the Affnie transformation"
# tw, tn = deg2num(gw, gn, zoom, True)
# te, ts = deg2num(ge, gs, zoom, True)
# te += 1
# ts += 1
#
# # if outdir is None:
# # outdir = tempfile.gettempdir()
# # if not os.path.exists(outdir):
# # os.makedirs(outdir)
# # # outpath = os.path.join(outdir, f'{zoom}_{tw}_{ts}_{te}_{tn}.tif')
#
# image = get_shadow_image(
# gw,
# gs,
# ge,
# gn,
# zoom=zoom,
# basedir=basedir,
# threshold=threshold,
# )
# height, width = image.shape
# gw, ts = num2deg(tw, ts, zoom, True)
# ge, tn = num2deg(te, tn, zoom, True)
#
# image = image / 255
# transform = rasterio.transform.from_bounds(gw, gs, ge, gn, width, height)
# return image, transform
def overlay(
gdf: Union[GeoDataFrame, str],
raster: str,
figsize: tuple = (15, 15),
statistic: str = 'weighted',
**kwargs,
) -> None:
"""
Plot an overlay of the Surface GDF and shadow raster file
:param gdf: GeoDataFrame or path to a GeoDataFrame
:param raster: raster file
:param figsize: ax figsize
:param statistic: the statistic to plot ("weighted" is from sum/count)
:param kwargs: kwargs to pass to plt.plot()
:return: None
"""
if isinstance(gdf, str):
gdf = gpd.read_feather(gdf)
if statistic == 'weighted' and 'weighted' not in gdf:
gdf['weighted'] = (
pd.Series.astype(gdf['sum'], float)
/ (gdf['count'] + gdf['nodata'])
).astype(float)
raster = rasterio.open(raster)
fig, ax = plt.subplots(figsize=figsize)
rasterio.plot.show(raster, ax=ax)
gdf.plot(column=statistic, cmap='rainbow', ax=ax, )
if __name__ == '__main__':
# tiles = get_shadow_image(
# *(40.702844950247666, -74.02244810805952)[::-1],
# *(40.78270102430847, -73.93524412566495)[::-1],
# 16,
# '/home/arstneio/Downloads/shadows/test/16-winter/'
# )
print()
# cells = get_cells_from_tiles(tiles, os.path.join('/home/arstneio/Downloads/shadows/nyc-sep-22/', str(16)))