· 5 years ago · Jun 12, 2020, 10:36 AM
1import concurrent.futures
2from collections import defaultdict
3from typing import Tuple, List, DefaultDict
4
5import imageio
6import mercantile
7import numpy as np
8import rasterio as rio
9import requests
10from affine import Affine
11from rasterio import transform, MemoryFile
12from rasterio.coords import BoundingBox
13from rasterio.errors import RasterioIOError
14from rasterio.windows import Window
15
16import boto3
17
18s3 = boto3.resource("s3")
19
20
21def get_tiles_from_field_metadata(rgb_key: str, channel: str, zooms: int) -> List[List[int]]:
22 # Tiles per defined zoom level with mercantile API.
23 response = requests.get(f"https://jgau9m9qpf.execute-api.us-east-1.amazonaws.com/bondville"
24 f"/metadata/{rgb_key}/{channel}/")
25 west, south, east, north = response.json()['bounds']
26 tiles = list(mercantile.tiles(west, south, east, north, zooms))
27 final_tiles = [[tile.x, tile.y, tile.z] for tile in tiles]
28 return final_tiles
29
30
31def get_resulting_image_shape(rgb_key: str, channel: str, zooms: int,
32 tile_size: tuple = (256, 256)) -> Tuple[int, int]:
33 # Final resulting image shape (height, width).
34 tiles = get_tiles_from_field_metadata(rgb_key, channel, zooms)
35 combined_arrays_by_x = combine_image_data_by_x(tiles)
36
37 image_width, image_height = len(combined_arrays_by_x.keys()) * tile_size[0], None
38 for k in combined_arrays_by_x:
39 image_height = len(combined_arrays_by_x[k]) * tile_size[1]
40 break
41 return image_width, image_height
42
43
44def combine_image_data_by_x(tiles: List[List[int]]) -> DefaultDict[int, List[List[int]]]:
45 # Get dict of image array combined by x value.
46 initial_x = tiles[0][0]
47 combined_arrays_by_x = defaultdict(list)
48 for tile in tiles:
49 local_x = tile[0]
50 if local_x == initial_x:
51 xyz_array = [tile[0], tile[1], tile[2]]
52 combined_arrays_by_x[local_x].append(xyz_array)
53 else:
54 initial_x = local_x
55 xyz_array = [tile[0], tile[1], tile[2]]
56 combined_arrays_by_x[initial_x].append(xyz_array)
57 return combined_arrays_by_x
58
59
60def get_tile_bounds(tile: list) -> BoundingBox:
61 # Returns BoundingBox object for each given tile.
62 return BoundingBox(*mercantile.xy_bounds(tile))
63
64
65def transform_from_bounds(bounds, tile_size) -> Affine:
66 return transform.from_bounds(*bounds, *tile_size)
67
68
69def get_resulting_image_bounds(rgb_key: str, channel: str, zooms: int) -> BoundingBox:
70 # Final resulting image boundary (x_min, y_min, x_max, y_max).
71 tiles = get_tiles_from_field_metadata(rgb_key, channel, zooms)
72 x_min, y_min, x_max, y_max = [], [], [], []
73 for index, tile in enumerate(tiles):
74 bbox = get_tile_bounds(tiles[index])
75 x_min.append(bbox.left)
76 y_min.append(bbox.bottom)
77 x_max.append(bbox.right)
78 y_max.append(bbox.top)
79
80 return BoundingBox(min(x_min), min(y_min), max(x_max), max(y_max))
81
82
83def construct_url(rgb_key: str, x: int, y: int, z: int):
84 # Makes api calls to rgb tile endpoint.
85 return f"https://jgau9m9qpf.execute-api.us-east-1.amazonaws.com/bondville/" \
86 f"{rgb_key}/{x}/{y}/{z}.png?&r=red&g=green&b=blue" \
87 f"&r_range=%5B2048.0%2C8735.0%5D&g_range=%5B2048.0%2C8735.0%5D&b_range=%5B2048.0%2C8735.0%5D"
88
89
90def get_image_data_array(rgb_key: str, x: int, y: int, z: int):
91 # Construct tile data each time calling api with respective x, y, z coordinates.
92 image_data = imageio.imread(construct_url(rgb_key, x, y, z))
93 return image_data
94
95
96def write_image_for_one_tile(d, image_data, image_width, image_height, g_transform,
97 no_data, window, count=3, mode='r+', driver='GTiff', crs='epsg:3857'):
98 # Write image data per tile basis.
99 # with rio.open(d, mode,
100 # driver=driver,
101 # width=image_width,
102 # height=image_height,
103 # crs=crs,
104 # transform=g_transform,
105 # nodata=no_data,
106 # count=count,
107 # dtype=image_data.dtype
108 # ) as dst:
109 d.write(np.transpose(np.moveaxis(image_data, [0, 2, 1], [1, 2, 0])), window=window)
110
111 # with d.open(**dst_profile) as dst:
112 # dst.write(np.transpose(np.moveaxis(image_data, [0, 2, 1], [1, 2, 0])), window=window)
113
114
115def thread_function(d_file, row_offset: int, column_offset: int, tile: list, width: int,
116 height: int, g_transform: Affine, no_data_v: int):
117 # Thread function in order to pass to ThreadPullExecutor
118 image_data_ = get_image_data_array("rgb/flight/9BINMT6XB", tile[2], tile[0], tile[1])
119 tile_window = Window(column_offset, row_offset, 256, 256)
120 write_image_for_one_tile(d_file, image_data_, width,
121 height, g_transform, no_data_v,
122 tile_window)
123 # try:
124 # write_image_for_one_tile(d_file, image_data_, width,
125 # height, g_transform, no_data_v,
126 # tile_window)
127 # except RasterioIOError:
128 # write_image_for_one_tile(d_file, image_data_, width,
129 # height, g_transform, no_data_v,
130 # tile_window, mode='w')
131
132
133if __name__ == "__main__":
134 resulting_tiles = get_tiles_from_field_metadata('flight/9BINMT6XB', 'red', 18)
135 res_image_width, res_image_height = get_resulting_image_shape('flight/9BINMT6XB', 'red', 18)
136 res_bounds = get_resulting_image_bounds('flight/9BINMT6XB', 'red', 18)
137 geo_transform = transform_from_bounds(res_bounds, (res_image_width, res_image_height))
138 tiles_map = combine_image_data_by_x(resulting_tiles)
139
140 # Please refer here to come with solution to "error setting certificate verify locations".
141 # https://github.com/mapbox/rasterio/issues/1289
142 s3_destination = 'intelinair-infra'
143
144 # s3_destination = 'temp.tif'
145 no_data_value = 0
146 dst_profile = {
147 'driver': "GTiff",
148 'count': 3,
149 'height': res_image_height,
150 'width': res_image_width,
151 'dtype': "uint8",
152 'nodata': no_data_value,
153 'crs': "epsg:3857",
154 'transform': geo_transform,
155 }
156
157 mem_file = MemoryFile()
158 with mem_file.open(**dst_profile) as f:
159
160 col_off = -256
161
162 for key, x_tiles in tiles_map.items():
163 col_off += 256
164 row_off = -256
165
166 with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
167 futures = []
168 for x_tile in x_tiles:
169 row_off += 256
170 futures.append(executor.submit(thread_function, f, row_off, col_off,
171 x_tile, res_image_width, res_image_height,
172 geo_transform, no_data_value))
173 concurrent.futures.wait(futures)
174
175 obj = s3.Object(s3_destination, 'file.tif')
176 mem_file.seek(0)
177 obj.put(Body=mem_file.read())
178
179 # The below commented part is the sequential implementation of raster creation.
180 # for x_tile in x_tiles:
181 # row_off += 256
182 # image_data_ = get_image_data_array("rgb/flight/9BINMT6XB", x_tile[2],
183 # x_tile[0], x_tile[1])
184 # tile_window = Window(col_off, row_off, 256, 256)
185 # write_image_for_one_tile(s3_destination, image_data_, res_image_width,
186 # res_image_height, geo_transform, no_data_value,
187 # tile_window)
188 # try:
189 # write_image_for_one_tile(s3_destination, image_data_, res_image_width,
190 # res_image_height, geo_transform, no_data_value,
191 # tile_window)
192 # except RasterioIOError:
193 # write_image_for_one_tile(s3_destination, image_data_, res_image_width,
194 # res_image_height, geo_transform, no_data_value,
195 # tile_window, mode='w')
196
197# The below commented part is the raster generation other solution with numpy array vertical and
198# horizontal concatenation but with no geographic data applied.
199# Also the deletion of black pixels for the resulting image with addition of alpha channel.
200
201
202# def image_from_array(array: np.ndarray, file_name: str, extension: str, mode: str = 'RGB',
203# compress_level: int = 1):
204# # Convert array to PIL Image.
205#
206# # Make black pixels transparent, adding alpha channel to image, and converting all the pixels
207# # which rbg values are black to transparent.
208#
209# rgb_img = Image.fromarray(array, mode)
210# rgb_alpha_image = rgb_img.convert('RGBA')
211# pixel_data = list(rgb_alpha_image.getdata())
212# for i, pixel in enumerate(pixel_data):
213# if pixel[:3] == (0, 0, 0):
214# pixel_data[i] = (0, 0, 0, 0)
215#
216# rgb_alpha_image.putdata(pixel_data)
217# rgb_alpha_image.save(file_name, extension, compress_level=compress_level)
218
219# def create_raster(file_name: str, extension: str):
220# # Generating final raster image using concatenation.
221# image_data_dict = combine_image_data_by_x()
222# horizontally_concatenated_array = []
223#
224# # Concatenating horizontally each row.
225# for im_data_row in image_data_dict.values():
226# temp_array = im_data_row[0]
227# for im_index in range(1, len(im_data_row)):
228# temp_array = np.concatenate((temp_array, im_data_row[im_index]))
229# horizontally_concatenated_array.append(temp_array)
230#
231# # Concatenating vertically
232# final_resulting_array = horizontally_concatenated_array[0]
233# for row in range(1, len(horizontally_concatenated_array)):
234# final_resulting_array = np.concatenate((final_resulting_array,
235# horizontally_concatenated_array[row]), axis=1)
236# image_from_array(final_resulting_array, file_name, extension)