def test_encode_failrange(): testdata = np.zeros((2)) testdata[1] = 256 ** 3 + 1 with pytest.raises(ValueError): data_to_rgb(testdata, 0, 1)
def test_encode_failrange(): testdata = np.zeros((2)) testdata[1] = 256**3 + 1 with pytest.raises(ValueError): data_to_rgb(testdata, 0, 1)
def test_encode_data_roundtrip(): minrand, maxrand = np.sort(np.random.randint(-427, 8848, 2)) testdata = np.round( (np.sum(np.dstack(np.indices((512, 512), dtype=np.float64)), axis=2) / (511. + 511.)) * maxrand, 2) + minrand baseval = -1000 interval = 0.1 rtripped = _decode(data_to_rgb(testdata.copy(), baseval, interval), baseval, interval) assert testdata.min() == rtripped.min() assert testdata.max() == rtripped.max()
def tile( tile_z, tile_x, tile_y, tileformat, indexes=1, shadder=None, colormap=None, range=None, ): """Handle tile requests""" if tileformat == "jpg": tileformat = "jpeg" if colormap and shadder: return ("NOK", "text/plain", "Cannot pass shadder and colormap options") address = f"s3://elevation-tiles-prod/geotiff/{tile_z}/{tile_x}/{tile_y}.tif" data, mask = main.tile(address, tile_x, tile_y, tile_z, indexes=indexes, tilesize=512) if shadder: tileformat = "png" if shadder == "mapbox": tile = encoders.data_to_rgb(data[0], -10000, 1) elif shadder == "mapzen": tile = mapzen_elevation_rgb.data_to_rgb(data) else: return ("NOK", "text/plain", f"Invalid shadder mode: {shadder}") else: if not range: range = "0,10000" histoCut = list(map(int, range.split(','))) tile = numpy.where( mask, linear_rescale(data, in_range=histoCut, out_range=[0, 255]), 0) options = dict(mask=mask) if colormap: options.update(color_map=get_colormap(name=colormap)) img = array_to_img(tile, **options) return ("OK", f"image/{tileformat}", img_to_buffer(img, tileformat))
def test_encode_data_roundtrip(): minrand, maxrand = np.sort(np.random.randint(-427, 8848, 2)) testdata = np.round((np.sum( np.dstack( np.indices((512, 512), dtype=np.float64)), axis=2) / (511. + 511.)) * maxrand, 2) + minrand baseval = -1000 interval = 0.1 rtripped = _decode(data_to_rgb(testdata.copy(), baseval, interval), baseval, interval) assert testdata.min() == rtripped.min() assert testdata.max() == rtripped.max()
def _tile_worker(tile): """ For each tile, and given an open rasterio src, plus a`global_args` dictionary with attributes of `base_val`, `interval`, and a `writer_func`, warp a continous single band raster to a 512 x 512 mercator tile, then encode this tile into RGB. Parameters ----------- tile: list [x, y, z] indices of tile Returns -------- tile, buffer tuple with the input tile, and a bytearray with the data encoded into the format created in the `writer_func` """ x, y, z = tile bounds = [ c for i in ( mercantile.xy(*mercantile.ul(x, y + 1, z)), mercantile.xy(*mercantile.ul(x + 1, y, z)), ) for c in i ] toaffine = transform.from_bounds(*bounds + [512, 512]) out = np.empty((512, 512), dtype=src.meta["dtype"]) reproject( rasterio.band(src, 1), out, dst_transform=toaffine, dst_crs="epsg:3857", resampling=Resampling.bilinear, ) out = data_to_rgb(out, global_args["base_val"], global_args["interval"]) return tile, global_args["writer_func"](out, global_args["kwargs"].copy(), toaffine)
def _tile_worker(tile): """ For each tile, and given an open rasterio src, plus a`global_args` dictionary with attributes of `base_val`, `interval`, and a `writer_func`, warp a continous single band raster to a 512 x 512 mercator tile, then encode this tile into RGB. Parameters ----------- tile: list [x, y, z] indices of tile Returns -------- tile, buffer tuple with the input tile, and a bytearray with the data encoded into the format created in the `writer_func` """ x, y, z = tile bounds = [c for i in (mercantile.xy(*mercantile.ul(x, y + 1, z)), mercantile.xy(*mercantile.ul(x + 1, y, z))) for c in i] toaffine = transform.from_bounds(*bounds + [512, 512]) out = np.empty((512, 512), dtype=src.meta['dtype']) reproject( rasterio.band(src, 1), out, dst_transform=toaffine, dst_crs="epsg:3857", resampling=RESAMPLING.bilinear) out = data_to_rgb(out, global_args['base_val'], global_args['interval']) return tile, global_args['writer_func'](out, global_args['kwargs'].copy(), toaffine)
def tile( z, x, y, scale=1, ext="png", url=None, indexes=None, expr=None, nodata=None, rescale=None, color_formula=None, color_map=None, dem=None, ): """Handle tile requests.""" if ext == "jpg": driver = "jpeg" elif ext == "jp2": driver = "JP2OpenJPEG" else: driver = ext if indexes and expr: raise TilerError("Cannot pass indexes and expression") if not url: raise TilerError("Missing 'url' parameter") if indexes: indexes = tuple(int(s) for s in re.findall(r"\d+", indexes)) tilesize = scale * 256 if nodata is not None: nodata = numpy.nan if nodata == "nan" else float(nodata) if expr is not None: tile, mask = expression(url, x, y, z, expr, tilesize=tilesize) else: tile, mask = main.tile(url, x, y, z, indexes=indexes, tilesize=tilesize) if dem: if dem == "mapbox": tile = encoders.data_to_rgb(tile, -10000, 1) elif dem == "mapzen": tile = mapzen_elevation_rgb.data_to_rgb(tile) else: return ("NOK", "text/plain", 'Invalid "dem" mode') else: rtile, rmask = _postprocess(tile, mask, tilesize, rescale=rescale, color_formula=color_formula) if color_map: color_map = get_colormap(color_map, format="gdal") options = img_profiles.get(driver, {}) return ( "OK", f"image/{ext}", array_to_image(rtile, rmask, img_format=driver, color_map=color_map, **options), )
def _rgb_worker(data, window, ij, g_args): return data_to_rgb(data[0][g_args["bidx"] - 1], g_args["base_val"], g_args["interval"])
def tiles( z, x, y, scale=1, ext="png", url=None, nodata=None, indexes=None, rescale=None, color_ops=None, color_map=None, dem=None, ): """ Handle Raster /tiles requests. Note: All the querystring parameters are translated to function keywords and passed as string value by lambda_proxy Attributes ---------- z : int, required Mercator tile ZOOM level. x : int, required Mercator tile X index. y : int, required Mercator tile Y index. scale : int Output scale factor (default: 1). ext : str Image format to return (default: png). url : str, required Dataset url to read from. indexes : str, optional, (defaults: None) Comma separated band index number (e.g "1,2,3"). nodata, str, optional Custom nodata value if not preset in dataset. rescale : str, optional Min and Max data bounds to rescale data from. color_ops : str, optional rio-color compatible color formula color_map : str, optional Rio-tiler compatible colormap name ("cfastie" or "schwarzwald") dem : str, optional Create Mapbox or Mapzen RGBA encoded elevation image Returns ------- status : str Status of the request (e.g. OK, NOK). MIME type : str response body MIME type (e.g. image/jpeg). body : bytes Image body. """ if not url: raise TilerError("Missing 'url' parameter") if indexes: indexes = tuple(int(s) for s in re.findall(r"\d+", indexes)) if nodata is not None and isinstance(nodata, str): nodata = numpy.nan if nodata == "nan" else float(nodata) tilesize = 256 * scale tile, mask = main.tile(url, x, y, z, indexes=indexes, tilesize=tilesize, nodata=nodata) if dem: if dem == "mapbox": tile = encoders.data_to_rgb(tile, -10000, 1) elif dem == "mapzen": tile = mapzen_elevation_rgb.data_to_rgb(tile) else: return ("NOK", "text/plain", 'Invalid "dem" mode') else: rtile, rmask = _postprocess_tile(tile, mask, rescale=rescale, color_ops=color_ops) if color_map: color_map = get_colormap(color_map, format="gdal") driver = "jpeg" if ext == "jpg" else ext options = img_profiles.get(driver, {}) return ( "OK", f"image/{ext}", array_to_image(rtile, rmask, img_format=driver, color_map=color_map, **options), )
def tile( z: int, x: int, y: int, scale: int = 1, ext: str = None, url: str = None, indexes: Union[str, Tuple[int]] = None, expr: str = None, nodata: Union[str, int, float] = None, rescale: str = None, color_formula: str = None, color_map: str = None, dem: str = None, ) -> Tuple[str, str, BinaryIO]: """Handle tile requests.""" driver = "jpeg" if ext == "jpg" else ext if indexes and expr: raise TilerError("Cannot pass indexes and expression") if not url: raise TilerError("Missing 'url' parameter") if isinstance(indexes, str): indexes = tuple(int(s) for s in re.findall(r"\d+", indexes)) if nodata is not None: nodata = numpy.nan if nodata == "nan" else float(nodata) tilesize = scale * 256 if expr is not None: tile, mask = expression(url, x, y, z, expr=expr, tilesize=tilesize, nodata=nodata) else: tile, mask = main.tile(url, x, y, z, indexes=indexes, tilesize=tilesize, nodata=nodata) if dem: if dem == "mapbox": tile = encoders.data_to_rgb(tile, -10000, 1) elif dem == "mapzen": tile = mapzen_elevation_rgb.data_to_rgb(tile) else: return ("NOK", "text/plain", 'Invalid "dem" mode') else: rtile, rmask = _postprocess(tile, mask, rescale=rescale, color_formula=color_formula) if color_map: color_map = get_colormap(color_map, format="gdal") options = img_profiles.get(driver, {}) return ( "OK", f"image/{ext}", array_to_image(rtile, rmask, img_format=driver, color_map=color_map, **options), )
def _rgb_worker(data, window, ij, g_args): return data_to_rgb(data[0][g_args['bidx'] - 1], g_args['base_val'], g_args['interval'])