def rgb(some_keys: Sequence[str], rgb_values: Sequence[str], tile_xyz: Tuple[int, int, int] = None, *, stretch_ranges: ListOfRanges = None, tile_size: Tuple[int, int] = None) -> BinaryIO: """Return RGB image as PNG Red, green, and blue channels correspond to the given values `rgb_values` of the key missing from `some_keys`. """ import numpy as np # make sure all stretch ranges contain two values if stretch_ranges is None: stretch_ranges = [None, None, None] if len(stretch_ranges) != 3: raise exceptions.InvalidArgumentsError( 'stretch_ranges argument must contain 3 values') stretch_ranges_ = [ stretch_range or (None, None) for stretch_range in stretch_ranges ] if len(rgb_values) != 3: raise exceptions.InvalidArgumentsError( 'rgb_values argument must contain 3 values') settings = get_settings() if tile_size is None: tile_size_ = settings.DEFAULT_TILE_SIZE else: tile_size_ = tile_size driver = get_driver(settings.DRIVER_PATH, provider=settings.DRIVER_PROVIDER) with driver.connect(): key_names = driver.key_names if len(some_keys) != len(key_names) - 1: raise exceptions.InvalidArgumentsError( 'must specify all keys except last one') def get_band_future(band_key: str) -> Future: band_keys = (*some_keys, band_key) return xyz.get_tile_data(driver, band_keys, tile_xyz=tile_xyz, tile_size=tile_size_, asynchronous=True) futures = [get_band_future(key) for key in rgb_values] band_items = zip(rgb_values, stretch_ranges_, futures) out_arrays = [] for i, (band_key, band_stretch_override, band_data_future) in enumerate(band_items): keys = (*some_keys, band_key) metadata = driver.get_metadata(keys) band_stretch_range = list(metadata['range']) scale_min, scale_max = band_stretch_override if scale_min is not None: band_stretch_range[0] = scale_min if scale_max is not None: band_stretch_range[1] = scale_max if band_stretch_range[1] < band_stretch_range[0]: raise exceptions.InvalidArgumentsError( 'Upper stretch bound must be higher than lower bound') band_data = band_data_future.result() out_arrays.append(image.to_uint8(band_data, *band_stretch_range)) out = np.ma.stack(out_arrays, axis=-1) return image.array_to_png(out)
def array_to_png(img_data: Array, colormap: Union[str, Palette, None] = None) -> BinaryIO: """Encode an 8bit array as PNG""" from terracotta.cmaps import get_cmap transparency: Union[Tuple[int, int, int], int, bytes] settings = get_settings() compress_level = settings.PNG_COMPRESS_LEVEL if img_data.ndim == 3: # encode RGB image if img_data.shape[-1] != 3: raise ValueError('3D input arrays must have three bands') if colormap is not None: raise ValueError( 'Colormap argument cannot be given for multi-band data') mode = 'RGB' transparency = (0, 0, 0) palette = None elif img_data.ndim == 2: # encode paletted image mode = 'L' if colormap is None: palette = None transparency = 0 else: if isinstance(colormap, str): # get and apply colormap by name try: cmap_vals = get_cmap(colormap) except ValueError as exc: raise exceptions.InvalidArgumentsError( f'Encountered invalid color map {colormap}') from exc palette = np.concatenate( (np.zeros(3, dtype='uint8'), cmap_vals[:, :-1].flatten())) transparency_arr = np.concatenate( (np.zeros(1, dtype='uint8'), cmap_vals[:, -1])) else: # explicit mapping if len(colormap) > 255: raise exceptions.InvalidArgumentsError( 'Explicit color map must contain less than 256 values') colormap_array = np.asarray(colormap, dtype='uint8') if colormap_array.ndim != 2 or colormap_array.shape[1] != 4: raise ValueError( 'Explicit color mapping must have shape (n, 4)') rgb, alpha = colormap_array[:, :-1], colormap_array[:, -1] palette = np.concatenate( (np.zeros(3, dtype='uint8'), rgb.flatten(), np.zeros(3 * (256 - len(colormap) - 1), dtype='uint8'))) # PIL expects paletted transparency as raw bytes transparency_arr = np.concatenate( (np.zeros(1, dtype='uint8'), alpha, np.zeros(256 - len(colormap) - 1, dtype='uint8'))) assert transparency_arr.shape == (256, ) assert transparency_arr.dtype == 'uint8' transparency = transparency_arr.tobytes() assert palette.shape == (3 * 256, ), palette.shape else: raise ValueError('Input array must have 2 or 3 dimensions') if isinstance(img_data, np.ma.MaskedArray): img_data = img_data.filled(0) img = Image.fromarray(img_data, mode=mode) if palette is not None: img.putpalette(palette) sio = BytesIO() img.save(sio, 'png', compress_level=compress_level, transparency=transparency) sio.seek(0) return sio
def compute(expression: str, some_keys: Sequence[str], operand_keys: Mapping[str, str], stretch_range: Tuple[Number, Number], tile_xyz: Tuple[int, int, int] = None, *, colormap: str = None, tile_size: Tuple[int, int] = None) -> BinaryIO: """Return singleband image computed from one or more images as PNG Expects a Python expression that returns a NumPy array. Operands in the expression are replaced by the images with keys as defined by some_keys (all but the last key) and operand_keys (last key). Contrary to singleband and rgb handlers, stretch_range must be given. Example: >>> operands = { ... 'v1': 'B08', ... 'v2': 'B04' ... } >>> compute('v1 * v2', ['S2', '20171101'], operands, [0, 1000]) <binary image containing product of bands 4 and 8> """ from terracotta.expressions import evaluate_expression if not stretch_range[1] > stretch_range[0]: raise exceptions.InvalidArgumentsError( 'Upper stretch bounds must be larger than lower bounds') settings = get_settings() if tile_size is None: tile_size_ = settings.DEFAULT_TILE_SIZE else: tile_size_ = tile_size driver = get_driver(settings.DRIVER_PATH, provider=settings.DRIVER_PROVIDER) with driver.connect(): key_names = driver.key_names if len(some_keys) != len(key_names) - 1: raise exceptions.InvalidArgumentsError( 'must specify all keys except last one') def get_band_future(band_key: str) -> Future: band_keys = (*some_keys, band_key) return xyz.get_tile_data(driver, band_keys, tile_xyz=tile_xyz, tile_size=tile_size_, asynchronous=True) futures = { var: get_band_future(key) for var, key in operand_keys.items() } operand_data = { var: future.result() for var, future in futures.items() } try: out = evaluate_expression(expression, operand_data) except ValueError as exc: # make sure error message gets propagated raise exceptions.InvalidArgumentsError( f'error while executing expression: {exc!s}') out = image.to_uint8(out, *stretch_range) return image.array_to_png(out, colormap=colormap)