Skip to content

rio_tiler.utils

rio_tiler.utils

rio_tiler.utils: utility functions.

CRS_to_uri

CRS_to_uri(crs: CRS) -> Optional[str]

Convert CRS to URI.

CRS_to_urn

CRS_to_urn(crs: CRS) -> Optional[str]

Convert CRS to URN.

_CRS_authority_info

_CRS_authority_info(crs: CRS) -> Optional[Tuple[str, str, str]]

_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.

_requested_tile_aligned_with_internal_tile

_requested_tile_aligned_with_internal_tile(src_dst: Union[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: Optional[Any] = None) -> Sequence

Cast input to sequence if not Tuple of List.

create_cutline

create_cutline(src_dst: Union[DatasetReader, DatasetWriter, WarpedVRT], geometry: Dict, geometry_crs: CRS = None, op: Optional[Callable[[float], Any]] = 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: Optional[List[float]] = None, percentiles: Optional[List[int]] = None, coverage: Optional[NDArray[floating]] = 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:

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: Union[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: Union[DatasetReader, DatasetWriter, WarpedVRT], bounds: BBox, height: Optional[int] = None, width: Optional[int] = 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: Union[DatasetReader, DatasetWriter, WarpedVRT]) -> bool

Check for alpha band or mask in source.

has_mask_band

has_mask_band(src_dst: Union[DatasetReader, DatasetWriter, WarpedVRT]) -> bool

Check for mask band in source.

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: Union[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: Optional[ndarray] = None, img_format: str = 'PNG', colormap: Optional[ColorMapType] = 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.