-
Notifications
You must be signed in to change notification settings - Fork 1
/
DataLoader.py
273 lines (225 loc) · 9.68 KB
/
DataLoader.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
import sys
import os
import time
import numpy as np
from enum import Enum
import fiona
import fiona.transform
import shapely
import shapely.geometry
import rasterio
import rasterio.mask
import rasterio.merge
import rasterio.warp
import rtree
import cv2
import pickle
import glob
import GeoTools
class GeoDataTypes(Enum):
NAIP = 1
NLCD = 2
LANDSAT_LEAFON = 3
LANDSAT_LEAFOFF = 4
BUILDINGS = 5
LANDCOVER = 6
# ------------------------------------------------------------------------------
# Le's methods for finding which NAIP tiles exist for a given "filename id"
#
# E.g. given "m_3907638_nw_18_1_20150815.mrf", find all files from other years that
# match "m_3907638_nw_18_1*"
#
# TODO: Make this lookup faster, currently O(n) where n is total number of tiles 100k-1000k
# ------------------------------------------------------------------------------
def naip2id(naip):
return '_'.join(naip.split('/')[-1].split('_')[:-1])
def get_naip_same_loc(naip):
if naip2id(naip) in naip_d:
return naip_d[naip2id(naip)]
return [naip,]
assert all([os.path.exists(fn) for fn in [
"data/list_all_naip.txt",
]])
naip_d = {}
fdid = open('data/list_all_naip.txt', 'r')
while True:
line = fdid.readline().strip()
if not line:
break
naipid = naip2id(line)
if naipid in naip_d:
naip_d[naipid] += [line,]
else:
naip_d[naipid] = [line,]
fdid.close()
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
# Caleb's methods for finding which NAIP tiles are assosciated with an input extent
#
# TODO: Assume that the tile_index.dat file is already created, make a separate script
# for generating it
# ------------------------------------------------------------------------------
assert all([os.path.exists(fn) for fn in [
"data/tile_index.dat",
"data/tile_index.idx",
"data/tiles.p"
]])
TILES = pickle.load(open("data/tiles.p", "rb"))
def lookup_tile_by_geom(geom):
tile_index = rtree.index.Index("data/tile_index")
# Add some margin
#minx, miny, maxx, maxy = shape(geom).buffer(50).bounds
minx, miny, maxx, maxy = shapely.geometry.shape(geom).bounds
geom = shapely.geometry.mapping(shapely.geometry.box(minx, miny, maxx, maxy, ccw=True))
geom = shapely.geometry.shape(geom)
intersected_indices = list(tile_index.intersection(geom.bounds))
for idx in intersected_indices:
intersected_fn = TILES[idx][0]
intersected_geom = TILES[idx][1]
if intersected_geom.contains(geom):
return intersected_fn
if len(intersected_indices) > 0:
raise ValueError("Error, there are overlaps with tile index, but no tile completely contains selection")
else:
raise ValueError("No tile intersections")
# ------------------------------------------------------------------------------
def get_data_by_extent(naip_fn, extent, geo_data_type):
if geo_data_type == GeoDataTypes.NAIP:
fn = naip_fn
elif geo_data_type == GeoDataTypes.NLCD:
fn = naip_fn.replace("/esri-naip/", "/resampled-nlcd/")[:-4] + "_nlcd.tif"
elif geo_data_type == GeoDataTypes.LANDSAT_LEAFON:
fn = naip_fn.replace("/esri-naip/data/v1/", "/resampled-landsat8/data/leaf_on/")[:-4] + "_landsat.tif"
elif geo_data_type == GeoDataTypes.LANDSAT_LEAFOFF:
fn = naip_fn.replace("/esri-naip/data/v1/", "/resampled-landsat8/data/leaf_off/")[:-4] + "_landsat.tif"
elif geo_data_type == GeoDataTypes.BUILDINGS:
fn = naip_fn.replace("/esri-naip/", "/resampled-buildings/")[:-4] + "_building.tif"
elif geo_data_type == GeoDataTypes.LANDCOVER:
# TODO: Add existence check
fn = naip_fname.replace("/esri-naip/", "/resampled-lc/")[:-4] + "_lc.tif"
else:
raise ValueError("GeoDataType not recognized")
f = rasterio.open(fn, "r")
geom = GeoTools.extent_to_transformed_geom(extent, f.crs["init"])
pad_rad = 15 # TODO: this might need to be changed for much larger inputs
buffed_geom = shapely.geometry.shape(geom).buffer(pad_rad)
minx, miny, maxx, maxy = buffed_geom.bounds
geom = shapely.geometry.mapping(shapely.geometry.box(minx, miny, maxx, maxy, ccw=True))
out_image, out_transform = rasterio.mask.mask(f, [geom], crop=True)
src_crs = f.crs.copy()
f.close()
dst_crs = {"init": "EPSG:%s" % (extent["spatialReference"]["latestWkid"])}
dst_transform, width, height = rasterio.warp.calculate_default_transform(
src_crs,
dst_crs,
width=out_image.shape[2], height=out_image.shape[1],
left=buffed_geom.bounds[0],
bottom=buffed_geom.bounds[1],
right=buffed_geom.bounds[2],
top=buffed_geom.bounds[3],
resolution=1
)
dst_image = np.zeros((out_image.shape[0], height, width), np.uint8)
rasterio.warp.reproject(
source=out_image,
destination=dst_image,
src_transform=out_transform,
src_crs=src_crs,
dst_transform=dst_transform,
dst_crs=dst_crs,
resampling=rasterio.warp.Resampling.nearest
)
# Calculate the correct padding
w = extent["xmax"] - extent["xmin"]
padding = int(np.round((dst_image.shape[1] - w) / 2))
return dst_image, padding
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
# Le's methods for predicting entire tile worth of data
#
# NOTE: I have not refactored these --Caleb
# ------------------------------------------------------------------------------
def naip_fn_to_pred_tile_fn(naip_fn):
return os.path.basename(naip_fn).split('.mrf')[0] + '_tilepred'
def find_tile_and_load_pred(centerp):
geom, naip_fn = center_to_tile_geom(centerp)
naip_key = naip_fn_to_pred_tile_fn(naip_fn)
fnames = []
usernames = []
for paths in glob.glob('img/*/{}_geotif.tif'.format(naip_key)):
fnames.append(paths[len('img/'):-len('_geotif.tif')])
usernames.append(os.path.basename(os.path.dirname(paths)))
return fnames, usernames
def find_tile_and_save_pred(centerp, tif_names, username):
datasets = [rasterio.open(fn, "r") for fn in tif_names[::-1]]
# Get geom and CRS
# Assumes the CRS of the tile is the same as the CRSes of patches
geom, naip_fn = center_to_tile_geom(centerp)
fid = rasterio.open(naip_fn, "r")
tile_crs = fid.crs.copy()
fid.close()
geom = fiona.transform.transform_geom("EPSG:3857", tile_crs["init"], geom)
# Merge all geospatial patches
tile, tile_transform = rasterio.merge.merge(datasets, shapely.geometry.shape(geom).bounds, nodata=0)
for fid in datasets:
fid.close()
# Save the resulting tile
if not os.path.exists('img/{}'.format(username)):
os.makedirs('img/{}'.format(username))
fname_tif = 'img/{}/{}_geotif.tif'.format(username, naip_fn_to_pred_tile_fn(naip_fn))
fid = rasterio.open(fname_tif, 'w', driver='GTiff',
width=tile.shape[2], height=tile.shape[1], count=tile.shape[0], dtype=np.uint8,
transform=tile_transform, crs=tile_crs, nodata=0)
for ch in range(tile.shape[0]):
fid.write(tile[ch, ...], ch+1)
fid.close()
# Get pngs in CRS EPSG3857 for display purpose
dst_CRS = "EPSG:3857"
png_tile_bounds = shapely.geometry.shape(geom).bounds
dest_transform, width, height = rasterio.warp.calculate_default_transform(
tile_crs, rasterio.crs.CRS({"init": dst_CRS}),
width=tile.shape[2], height=tile.shape[1],
left=png_tile_bounds[0], bottom=png_tile_bounds[1],
right=png_tile_bounds[2], top=png_tile_bounds[3])
tile_dest = np.zeros((tile.shape[0], height, width), np.uint8)
rasterio.warp.reproject(
source=tile,
destination=tile_dest,
src_transform=tile_transform,
src_crs=tile_crs,
dst_transform=dest_transform,
dst_crs=rasterio.crs.CRS({"init": dst_CRS}),
resampling=rasterio.warp.Resampling.nearest
)
tile_dest = np.swapaxes(tile_dest, 0, 1)
tile_dest = np.swapaxes(tile_dest, 1, 2)
mask = np.max(tile_dest, axis=2, keepdims=True) > 0
tile_dest = tile_dest.astype(np.float32) / 255.0
im_soft = np.round(255*pic(tile_dest, hard=False)).astype(np.uint8)
im_hard = np.round(255*pic(tile_dest, hard=True)).astype(np.uint8) * mask
fname_png = 'img/{}/{}_soft.png'.format(username, naip_fn_to_pred_tile_fn(naip_fn))
cv2.imwrite(fname_png, cv2.cvtColor(im_soft, cv2.COLOR_RGB2BGR))
fname_png = 'img/{}/{}_hard.png'.format(username, naip_fn_to_pred_tile_fn(naip_fn))
cv2.imwrite(fname_png, cv2.cvtColor(im_hard, cv2.COLOR_RGB2BGR))
return fname_tif
def center_to_tile_geom(centerp):
xctr = centerp["xcenter"]
yctr = centerp["ycenter"]
geom = {
"type": "Polygon",
"coordinates": [[(xctr-1, yctr-1), (xctr+1, yctr-1), (xctr+1, yctr+1), (xctr-1, yctr+1), (xctr-1, yctr-1)]]
}
# The map navigator uses EPSG:3857 and Caleb's indices use EPSG:4269
geom = fiona.transform.transform_geom("EPSG:3857", "EPSG:4269", geom)
geom = shapely.geometry.shape(geom)
tile_index = rtree.index.Index("data/tile_index")
intersected_indices = list(tile_index.intersection(geom.bounds))
for idx in intersected_indices:
intersected_fn = TILES[idx][0]
intersected_geom = TILES[idx][1]
geom = shapely.geometry.mapping(intersected_geom)
geom = fiona.transform.transform_geom("EPSG:4269", "EPSG:3857", geom)
return geom, intersected_fn
print('No tile intersecton')
return None, None
# ------------------------------------------------------------------------------