Skip to content

rio_tiler.utils

rio_tiler.utils

rio_tiler.utils: utility functions.

Timer

Bases: object

Time a code block.

from_start property

from_start

Return time elapsed from start.

__enter__

__enter__()

Starts timer.

__exit__

__exit__(ty, val, tb)

Stops timer.

CRS_to_uri

CRS_to_uri(crs: CRS) -> str | None

Convert CRS to URI.

CRS_to_urn

CRS_to_urn(crs: CRS) -> str | None

Convert CRS to URN.

_CRS_authority_info

_CRS_authority_info(crs: CRS) -> tuple[str, str, str] | None

_array_gdal_name

_array_gdal_name(data: ndarray) -> str

Return GDAL MEM dataset name.

_chunks

_chunks(my_list: Sequence, chuck_size: int) -> Generator[Sequence, None, None]

Yield successive n-sized chunks from l.

_get_width_height

_get_width_height(max_size, dataset_height, dataset_width) -> tuple[int, int]

Get Output Width/Height based on a max_size and dataset shape.

_missing_size

_missing_size(w: int | None = None, h: int | None = None)

Check if one and only one size (width, height) is valid.

_requested_tile_aligned_with_internal_tile

_requested_tile_aligned_with_internal_tile(src_dst: DatasetReader | DatasetWriter | WarpedVRT, bounds: BBox, bounds_crs: CRS = WEB_MERCATOR_CRS) -> bool

Check if tile is aligned with internal tiles.

_validate_shape_input

_validate_shape_input(shape: dict) -> dict

Ensure input shape is valid and reduce features to geometry

cast_to_sequence

cast_to_sequence(val: Any | None = None) -> Sequence

Cast input to sequence if not Tuple of List.

create_cutline

create_cutline(src_dst: DatasetReader | DatasetWriter | WarpedVRT, geometry: dict, geometry_crs: CRS = None, op: Callable[[float], Any] | None = None) -> str

Create WKT Polygon Cutline for GDALWarpOptions.

Ref: gdal.org/api/gdalwarp_cpp.html?highlight=vrt#_CPPv415GDALWarpOptions

Parameters:

  • src_dst (DatasetReader or DatasetWriter or WarpedVRT) –

    Rasterio dataset.

  • geometry (dict) –

    GeoJSON feature or GeoJSON geometry. By default the coordinates are considered to be in the dataset CRS. Use geometry_crs to set a specific CRS.

  • geometry_crs (CRS, default: None ) –

    Input geometry Coordinate Reference System

Returns: str: WKT geometry in form of `POLYGON ((x y, x y, ...)))

get_array_statistics

get_array_statistics(data: MaskedArray, categorical: bool = False, categories: list[float] | None = None, percentiles: list[int] | None = None, coverage: NDArray[floating] | None = None, **kwargs: Any) -> list[dict[Any, Any]]

Calculate per band array statistics.

Parameters:

  • data (MaskedArray) –

    input masked array data to get the statistics from.

  • categorical (bool, default: False ) –

    treat input data as categorical data. Defaults to False.

  • categories (list of numbers, default: None ) –

    list of categories to return value for.

  • percentiles (list of numbers, default: None ) –

    list of percentile values to calculate. Defaults to [2, 98].

  • coverage (array, default: None ) –

    Data coverage fraction.

  • kwargs (optional, default: {} ) –

    options to forward to numpy.histogram function (only applies for non-categorical data).

Returns:

  • list ( list[dict[Any, Any]] ) –

    list of array statistics (dict)

Examples:

>>> data = numpy.ma.zeros((1, 256, 256))
>>> get_array_statistics(data)
[
    {
        'min': 0.0,
        'max': 0.0,
        'mean': 0.0,
        'count': 65536.0,
        'sum': 0.0,
        'std': 0.0,
        'median': 0.0,
        'majority': 0.0,
        'minority': 0.0,
        'unique': 1.0,
        'percentile_2': 0.0,
        'percentile_98': 0.0,
        'histogram': [
            [0, 0, 0, 0, 0, 65536, 0, 0, 0, 0],
            [-0.5, -0.4, -0.3, -0.19999999999999996, -0.09999999999999998, 0.0, 0.10000000000000009, 0.20000000000000007, 0.30000000000000004, 0.4, 0.5]
        ],
        'valid_pixels': 65536.0,
        'masked_pixels': 0.0,
        'valid_percent': 100.0
    }
]

get_overview_level

get_overview_level(src_dst: DatasetReader | DatasetWriter | WarpedVRT, bounds: BBox, height: int, width: int, dst_crs: CRS = WEB_MERCATOR_CRS) -> int

Return the overview level corresponding to the tile resolution.

Freely adapted from github.com/OSGeo/gdal/blob/41993f127e6e1669fbd9e944744b7c9b2bd6c400/gdal/apps/gdalwarp_lib.cpp#L2293-L2362

Parameters:

  • src_dst (DatasetReader or DatasetWriter or WarpedVRT) –

    Rasterio dataset.

  • bounds (tuple) –

    Bounding box coordinates in target crs (dst_crs).

  • height (int) –

    Desired output height of the array for the input bounds.

  • width (int) –

    Desired output width of the array for the input bounds.

  • dst_crs (CRS, default: WEB_MERCATOR_CRS ) –

    Target Coordinate Reference System. Defaults to epsg:3857.

Returns:

  • int ( int ) –

    Overview level.

get_vrt_transform

get_vrt_transform(src_dst: DatasetReader | DatasetWriter | WarpedVRT, bounds: BBox, height: int | None = None, width: int | None = None, dst_crs: CRS = WEB_MERCATOR_CRS, window_precision: int = 6, align_bounds_with_dataset: bool = False) -> tuple[Affine, int, int]

Calculate VRT transform.

Parameters:

  • src_dst (DatasetReader or DatasetWriter or WarpedVRT) –

    Rasterio dataset.

  • bounds (tuple) –

    Bounding box coordinates in target crs (dst_crs).

  • height (int, default: None ) –

    Output height of the array for the input bounds.

  • width (int, default: None ) –

    Output width of the array for the input bounds.

  • dst_crs (CRS, default: WEB_MERCATOR_CRS ) –

    Target Coordinate Reference System. Defaults to epsg:3857.

  • align_bounds_with_dataset (bool, default: False ) –

    Align input bounds with dataset transform. Defaults to False.

Returns:

  • tuple ( tuple[Affine, int, int] ) –

    VRT transform (affine.Affine), width (int) and height (int)

has_alpha_band

has_alpha_band(src_dst: DatasetReader | DatasetWriter | WarpedVRT) -> bool

Check for alpha band or mask in source.

has_mask_band

has_mask_band(src_dst: DatasetReader | DatasetWriter | WarpedVRT) -> bool

Check for mask band in source.

inherit_rasterio_env

inherit_rasterio_env(f: Callable[_P, _R]) -> Callable[_P, _R]

Wrap a function to run in a rasterio environment like the current one.

This differs from the function rasterio.env.ensure_env_with_credentials in that this function copies the rasterio environment active at the time this function is invoked, rather than at the time the wrapped function is invoked. This enables replicating the environment from the thread active at the time this function is invoked to the thread active at the time the wrapped function is invoked.

Parameters:

  • f (Callable[_P, _R]) –

    The function to wrap.

Returns:

  • Callable[_P, _R]

    Callable[P, R]: A function wrapping f that executes f within a rasterio environment configured identically to the rasterio environment active at the time this wrapper is created. Returns f unwrapped if no rasterio environment is active when this function is called.

linear_rescale

linear_rescale(image: ndarray, in_range: IntervalTuple, out_range: IntervalTuple = (0, 255)) -> ndarray

Apply linear rescaling to a numpy array.

Parameters:

  • image (ndarray) –

    array to rescale.

  • in_range (tuple) –

    array min/max value to rescale from.

  • out_range (tuple, default: (0, 255) ) –

    output min/max bounds to rescale to. Defaults to (0, 255).

Returns:

  • ndarray

    numpy.ndarray: linear rescaled array.

mapzen_elevation_rgb

mapzen_elevation_rgb(data: ndarray) -> ndarray

Encode elevation value to RGB values compatible with Mapzen tangram.

Parameters:

  • data (ndarray) –

    Image array to encode.

Returns numpy.ndarray: Elevation encoded in a RGB array.

non_alpha_indexes

non_alpha_indexes(src_dst: DatasetReader | DatasetWriter | WarpedVRT) -> tuple

Return indexes of non-alpha bands.

normalize_bounds

normalize_bounds(bounds: BBox) -> BBox

Return BBox in correct minx, miny, maxx, maxy order.

pansharpening_brovey

pansharpening_brovey(rgb: ndarray, pan: ndarray, weight: float, pan_dtype: str) -> ndarray

Apply Brovey pansharpening method.

Brovey Method: Each resampled, multispectral pixel is multiplied by the ratio of the corresponding panchromatic pixel intensity to the sum of all the multispectral intensities.

Original code from mapbox/rio-pansharpen

render

render(data: ndarray, mask: ndarray | None = None, img_format: str = 'PNG', colormap: ColorMapType | None = None, **creation_options: Any) -> bytes

Translate numpy.ndarray to image bytes.

Parameters:

  • data (ndarray) –

    Image array to encode.

  • mask (ndarray, default: None ) –

    Mask array.

  • img_format (str, default: 'PNG' ) –

    Image format. See: for the list of supported format by GDAL: www.gdal.org/formats_list.html. Defaults to PNG.

  • colormap (dict or sequence, default: None ) –

    RGBA Color Table dictionary or sequence.

  • creation_options (optional, default: {} ) –

    Image driver creation options to forward to GDAL.

Returns bytes: image body.

Examples:

>>> with Reader("my_tif.tif") as src:
    img = src.preview()
    with open('test.jpg', 'wb') as f:
        f.write(render(img.data, img.mask, img_format="jpeg"))

resize_array

resize_array(data: ndarray, height: int, width: int, resampling_method: RIOResampling = 'nearest') -> ndarray

resize array to a given height and width.