From 68872e4220bfa351816f16f020f0d778ba928749 Mon Sep 17 00:00:00 2001 From: <> Date: Thu, 14 Nov 2024 22:00:16 +0000 Subject: [PATCH] Deployed ad0c7cd with MkDocs version: 1.6.1 --- .nojekyll | 0 404.html | 1666 ++++ advanced/benchmark.html | 292 + advanced/custom_readers/index.html | 2339 ++++++ advanced/dynamic_tiler/index.html | 1921 +++++ advanced/feature/index.html | 1762 +++++ advanced/statistics/index.html | 2006 +++++ advanced/tms/index.html | 1748 +++++ api/rio_tiler/colormap/index.html | 2556 +++++++ api/rio_tiler/constants/index.html | 1802 +++++ api/rio_tiler/errors/index.html | 2872 +++++++ api/rio_tiler/expression/index.html | 2017 +++++ api/rio_tiler/io/base/index.html | 4878 ++++++++++++ api/rio_tiler/io/rasterio/index.html | 3861 ++++++++++ api/rio_tiler/io/stac/index.html | 2445 ++++++ api/rio_tiler/io/xarray/index.html | 2795 +++++++ api/rio_tiler/models/index.html | 3707 +++++++++ api/rio_tiler/mosaic/methods/base/index.html | 2044 +++++ .../mosaic/methods/defaults/index.html | 3099 ++++++++ api/rio_tiler/mosaic/reader/index.html | 1959 +++++ api/rio_tiler/profiles/index.html | 2248 ++++++ api/rio_tiler/reader/index.html | 2522 +++++++ api/rio_tiler/tasks/index.html | 2034 +++++ api/rio_tiler/utils/index.html | 2989 ++++++++ assets/_mkdocstrings.css | 143 + assets/images/favicon.png | Bin 0 -> 1870 bytes assets/javascripts/bundle.83f73b43.min.js | 16 + assets/javascripts/bundle.83f73b43.min.js.map | 7 + assets/javascripts/lunr/min/lunr.ar.min.js | 1 + assets/javascripts/lunr/min/lunr.da.min.js | 18 + assets/javascripts/lunr/min/lunr.de.min.js | 18 + assets/javascripts/lunr/min/lunr.du.min.js | 18 + assets/javascripts/lunr/min/lunr.el.min.js | 1 + assets/javascripts/lunr/min/lunr.es.min.js | 18 + assets/javascripts/lunr/min/lunr.fi.min.js | 18 + assets/javascripts/lunr/min/lunr.fr.min.js | 18 + assets/javascripts/lunr/min/lunr.he.min.js | 1 + assets/javascripts/lunr/min/lunr.hi.min.js | 1 + assets/javascripts/lunr/min/lunr.hu.min.js | 18 + assets/javascripts/lunr/min/lunr.hy.min.js | 1 + assets/javascripts/lunr/min/lunr.it.min.js | 18 + assets/javascripts/lunr/min/lunr.ja.min.js | 1 + assets/javascripts/lunr/min/lunr.jp.min.js | 1 + assets/javascripts/lunr/min/lunr.kn.min.js | 1 + assets/javascripts/lunr/min/lunr.ko.min.js | 1 + assets/javascripts/lunr/min/lunr.multi.min.js | 1 + assets/javascripts/lunr/min/lunr.nl.min.js | 18 + assets/javascripts/lunr/min/lunr.no.min.js | 18 + assets/javascripts/lunr/min/lunr.pt.min.js | 18 + assets/javascripts/lunr/min/lunr.ro.min.js | 18 + assets/javascripts/lunr/min/lunr.ru.min.js | 18 + assets/javascripts/lunr/min/lunr.sa.min.js | 1 + .../lunr/min/lunr.stemmer.support.min.js | 1 + assets/javascripts/lunr/min/lunr.sv.min.js | 18 + assets/javascripts/lunr/min/lunr.ta.min.js | 1 + assets/javascripts/lunr/min/lunr.te.min.js | 1 + assets/javascripts/lunr/min/lunr.th.min.js | 1 + assets/javascripts/lunr/min/lunr.tr.min.js | 18 + assets/javascripts/lunr/min/lunr.vi.min.js | 1 + assets/javascripts/lunr/min/lunr.zh.min.js | 1 + assets/javascripts/lunr/tinyseg.js | 206 + assets/javascripts/lunr/wordcut.js | 6708 +++++++++++++++++ .../workers/search.6ce7567c.min.js | 42 + .../workers/search.6ce7567c.min.js.map | 7 + assets/stylesheets/main.0253249f.min.css | 1 + assets/stylesheets/main.0253249f.min.css.map | 1 + assets/stylesheets/palette.06af60db.min.css | 1 + .../stylesheets/palette.06af60db.min.css.map | 1 + colormap/index.html | 1987 +++++ contributing/index.html | 1883 +++++ .../STAC_datacube_support.ipynb | 515 ++ examples/STAC_datacube_support/index.html | 3066 ++++++++ .../Using-nonEarth-dataset.ipynb | 286 + examples/Using-nonEarth-dataset/index.html | 2738 +++++++ .../Using-rio-tiler-STACReader.ipynb | 322 + .../Using-rio-tiler-STACReader/index.html | 2784 +++++++ .../Using-rio-tiler-XarrayReader.ipynb | 2135 ++++++ .../Using-rio-tiler-XarrayReader/index.html | 4532 +++++++++++ .../Using-rio-tiler-mosaic.ipynb | 562 ++ examples/Using-rio-tiler-mosaic/index.html | 3588 +++++++++ .../Using-rio-tiler/Using-rio-tiler.ipynb | 1055 +++ examples/Using-rio-tiler/index.html | 3934 ++++++++++ examples/Using-tms/Using-tms.ipynb | 281 + examples/Using-tms/index.html | 2711 +++++++ examples/data/dataset_2d.nc | Bin 0 -> 268180 bytes examples/data/stac_netcdf.json | 111 + img/colormaps_for_oceanography.png | Bin 0 -> 73309 bytes img/custom.png | Bin 0 -> 19368 bytes img/cyclic.png | Bin 0 -> 18537 bytes img/diverging.png | Bin 0 -> 45152 bytes img/miscellaneous.png | Bin 0 -> 64899 bytes img/perceptually_uniform_sequential.png | Bin 0 -> 31187 bytes img/qualitative.png | Bin 0 -> 43011 bytes img/sequential.png | Bin 0 -> 59129 bytes img/sequential_(2).png | Bin 0 -> 55966 bytes img/vrt_tile.png | Bin 0 -> 77132 bytes index.html | 2134 ++++++ intro/index.html | 1998 +++++ migrations/v2_migration/index.html | 2236 ++++++ migrations/v3_migration/index.html | 2008 +++++ migrations/v4_migration/index.html | 2229 ++++++ migrations/v5_migration/index.html | 2001 +++++ migrations/v7_migration/index.html | 1974 +++++ models/index.html | 2770 +++++++ mosaic/index.html | 2193 ++++++ objects.inv | Bin 0 -> 2366 bytes overrides/main.html | 11 + readers/index.html | 3322 ++++++++ release-notes/index.html | 3498 +++++++++ search/search_index.json | 1 + sitemap.xml | 171 + sitemap.xml.gz | Bin 0 -> 520 bytes supported_format/index.html | 1803 +++++ 113 files changed, 123821 insertions(+) create mode 100644 .nojekyll create mode 100644 404.html create mode 100644 advanced/benchmark.html create mode 100644 advanced/custom_readers/index.html create mode 100644 advanced/dynamic_tiler/index.html create mode 100644 advanced/feature/index.html create mode 100644 advanced/statistics/index.html create mode 100644 advanced/tms/index.html create mode 100644 api/rio_tiler/colormap/index.html create mode 100644 api/rio_tiler/constants/index.html create mode 100644 api/rio_tiler/errors/index.html create mode 100644 api/rio_tiler/expression/index.html create mode 100644 api/rio_tiler/io/base/index.html create mode 100644 api/rio_tiler/io/rasterio/index.html create mode 100644 api/rio_tiler/io/stac/index.html create mode 100644 api/rio_tiler/io/xarray/index.html create mode 100644 api/rio_tiler/models/index.html create mode 100644 api/rio_tiler/mosaic/methods/base/index.html create mode 100644 api/rio_tiler/mosaic/methods/defaults/index.html create mode 100644 api/rio_tiler/mosaic/reader/index.html create mode 100644 api/rio_tiler/profiles/index.html create mode 100644 api/rio_tiler/reader/index.html create mode 100644 api/rio_tiler/tasks/index.html create mode 100644 api/rio_tiler/utils/index.html create mode 100644 assets/_mkdocstrings.css create mode 100644 assets/images/favicon.png create mode 100644 assets/javascripts/bundle.83f73b43.min.js create mode 100644 assets/javascripts/bundle.83f73b43.min.js.map create mode 100644 assets/javascripts/lunr/min/lunr.ar.min.js create mode 100644 assets/javascripts/lunr/min/lunr.da.min.js create mode 100644 assets/javascripts/lunr/min/lunr.de.min.js create mode 100644 assets/javascripts/lunr/min/lunr.du.min.js create mode 100644 assets/javascripts/lunr/min/lunr.el.min.js create mode 100644 assets/javascripts/lunr/min/lunr.es.min.js create mode 100644 assets/javascripts/lunr/min/lunr.fi.min.js create mode 100644 assets/javascripts/lunr/min/lunr.fr.min.js create mode 100644 assets/javascripts/lunr/min/lunr.he.min.js create mode 100644 assets/javascripts/lunr/min/lunr.hi.min.js create mode 100644 assets/javascripts/lunr/min/lunr.hu.min.js create mode 100644 assets/javascripts/lunr/min/lunr.hy.min.js create mode 100644 assets/javascripts/lunr/min/lunr.it.min.js create mode 100644 assets/javascripts/lunr/min/lunr.ja.min.js create mode 100644 assets/javascripts/lunr/min/lunr.jp.min.js create mode 100644 assets/javascripts/lunr/min/lunr.kn.min.js create mode 100644 assets/javascripts/lunr/min/lunr.ko.min.js create mode 100644 assets/javascripts/lunr/min/lunr.multi.min.js create mode 100644 assets/javascripts/lunr/min/lunr.nl.min.js create mode 100644 assets/javascripts/lunr/min/lunr.no.min.js create mode 100644 assets/javascripts/lunr/min/lunr.pt.min.js create mode 100644 assets/javascripts/lunr/min/lunr.ro.min.js create mode 100644 assets/javascripts/lunr/min/lunr.ru.min.js create mode 100644 assets/javascripts/lunr/min/lunr.sa.min.js create mode 100644 assets/javascripts/lunr/min/lunr.stemmer.support.min.js create mode 100644 assets/javascripts/lunr/min/lunr.sv.min.js create mode 100644 assets/javascripts/lunr/min/lunr.ta.min.js create mode 100644 assets/javascripts/lunr/min/lunr.te.min.js create mode 100644 assets/javascripts/lunr/min/lunr.th.min.js create mode 100644 assets/javascripts/lunr/min/lunr.tr.min.js create mode 100644 assets/javascripts/lunr/min/lunr.vi.min.js create mode 100644 assets/javascripts/lunr/min/lunr.zh.min.js create mode 100644 assets/javascripts/lunr/tinyseg.js create mode 100644 assets/javascripts/lunr/wordcut.js create mode 100644 assets/javascripts/workers/search.6ce7567c.min.js create mode 100644 assets/javascripts/workers/search.6ce7567c.min.js.map create mode 100644 assets/stylesheets/main.0253249f.min.css create mode 100644 assets/stylesheets/main.0253249f.min.css.map create mode 100644 assets/stylesheets/palette.06af60db.min.css create mode 100644 assets/stylesheets/palette.06af60db.min.css.map create mode 100644 colormap/index.html create mode 100644 contributing/index.html create mode 100644 examples/STAC_datacube_support/STAC_datacube_support.ipynb create mode 100644 examples/STAC_datacube_support/index.html create mode 100644 examples/Using-nonEarth-dataset/Using-nonEarth-dataset.ipynb create mode 100644 examples/Using-nonEarth-dataset/index.html create mode 100644 examples/Using-rio-tiler-STACReader/Using-rio-tiler-STACReader.ipynb create mode 100644 examples/Using-rio-tiler-STACReader/index.html create mode 100644 examples/Using-rio-tiler-XarrayReader/Using-rio-tiler-XarrayReader.ipynb create mode 100644 examples/Using-rio-tiler-XarrayReader/index.html create mode 100644 examples/Using-rio-tiler-mosaic/Using-rio-tiler-mosaic.ipynb create mode 100644 examples/Using-rio-tiler-mosaic/index.html create mode 100644 examples/Using-rio-tiler/Using-rio-tiler.ipynb create mode 100644 examples/Using-rio-tiler/index.html create mode 100644 examples/Using-tms/Using-tms.ipynb create mode 100644 examples/Using-tms/index.html create mode 100644 examples/data/dataset_2d.nc create mode 100644 examples/data/stac_netcdf.json create mode 100644 img/colormaps_for_oceanography.png create mode 100644 img/custom.png create mode 100644 img/cyclic.png create mode 100644 img/diverging.png create mode 100644 img/miscellaneous.png create mode 100644 img/perceptually_uniform_sequential.png create mode 100644 img/qualitative.png create mode 100644 img/sequential.png create mode 100644 img/sequential_(2).png create mode 100644 img/vrt_tile.png create mode 100644 index.html create mode 100644 intro/index.html create mode 100644 migrations/v2_migration/index.html create mode 100644 migrations/v3_migration/index.html create mode 100644 migrations/v4_migration/index.html create mode 100644 migrations/v5_migration/index.html create mode 100644 migrations/v7_migration/index.html create mode 100644 models/index.html create mode 100644 mosaic/index.html create mode 100644 objects.inv create mode 100644 overrides/main.html create mode 100644 readers/index.html create mode 100644 release-notes/index.html create mode 100644 search/search_index.json create mode 100644 sitemap.xml create mode 100644 sitemap.xml.gz create mode 100644 supported_format/index.html diff --git a/.nojekyll b/.nojekyll new file mode 100644 index 00000000..e69de29b diff --git a/404.html b/404.html new file mode 100644 index 00000000..94269454 --- /dev/null +++ b/404.html @@ -0,0 +1,1666 @@ + + + +
+ + + + + + + + + + + + + + + + +rio-tiler
provides multiple abstract base
+classes from which it derives its
+main readers: Reader
and
+STACReader
. You can also use these classes to build
+custom readers.
Main rio_tiler.io
Abstract Base Class.
tms: The TileMatrixSet define which default projection and map grid the reader uses. Defaults to WebMercatorQuad.
+bounds: Dataset's bounding box. Not in the __init__
method.
__init__
method.__init__
method.__init__
method.__init__
method.Important
+BaseClass Arguments outside the __init__
method and without default value HAVE TO be set in the __attrs_post_init__
step.
self.bounds
and self.crs
).Abstract methods, are method that HAVE TO be implemented in the child class.
+rio_tiler.models.Info
)Dict[str, rio_tiler.models.BandStatistics]
)rio_tiler.models.ImageData
)rio_tiler.models.ImageData
)rio_tiler.models.ImageData
)List
)rio_tiler.models.ImageData
)Example: Reader
The goal of the MultiBaseReader
is to enable joining results from multiple files (e.g STAC).
The MultiBaseReader
has the same attributes/properties/methods as the BaseReader
.
Example: STACReader
import os
+import pathlib
+from typing import Dict, Type
+
+import attr
+from morecantile import TileMatrixSet
+from rio_tiler.io.base import MultiBaseReader
+from rio_tiler.io import Reader, BaseReader
+from rio_tiler.constants import WEB_MERCATOR_TMS
+from rio_tiler.models import Info
+from rio_tiler.types import AssetInfo
+from rio_tiler.errors import InvalidAssetName
+
+@attr.s
+class AssetFileReader(MultiBaseReader):
+
+ input: str = attr.ib()
+ prefix: str = attr.ib() # we add a custom attribute
+
+ # because we add another attribute (prefix) we need to
+ # re-specify the other attribute for the class
+ reader: Type[BaseReader] = attr.ib(default=Reader)
+ reader_options: Dict = attr.ib(factory=dict)
+ tms: TileMatrixSet = attr.ib(default=WEB_MERCATOR_TMS)
+
+ # we place min/max zoom in __init__
+ minzoom: int = attr.ib(default=None)
+ maxzoom: int = attr.ib(default=None)
+
+ def __attrs_post_init__(self):
+ """Parse Sceneid and get grid bounds."""
+ self.assets = sorted(
+ [p.stem.split("_")[1] for p in pathlib.Path(self.input).glob(f"*{self.prefix}*.tif")]
+ )
+ with self.reader(self._get_asset_info(self.assets[0])["url"]) as cog:
+ self.bounds = cog.bounds
+ self.crs = cog.crs
+ self.transform = cog.transform
+ self.height = cog.height
+ self.width = cog.width
+ if self.minzoom is None:
+ self.minzoom = cog.minzoom
+
+ if self.maxzoom is None:
+ self.maxzoom = cog.maxzoom
+
+ def _get_asset_info(self, asset: str) -> AssetInfo:
+ """Validate band's name and return band's url."""
+ if asset not in self.assets:
+ raise InvalidAssetName(
+ f"'{asset}' is not valid, should be one of {self.assets}"
+ )
+
+ return AssetInfo(url=os.path.join(self.input, f"{self.prefix}{asset}.tif"))
+
+# we have a directoty with "scene_b1.tif", "scene_b2.tif"
+with AssetFileReader(input="my_dir/", prefix="scene_") as cr:
+ print(cr.assets)
+ >>> ['band1', 'band2']
+
+ info = cr.info(assets=("band1", "band2"))
+ # MultiBaseReader returns a Dict
+ assert isinstance(info, dict)
+ print(list(info))
+ >>> ['band1', 'band2']
+
+ assert isinstance(info["band1"], Info)
+ print(info["band1"].model_dump_json(exclude_none=True))
+ >>> {
+ "bounds": [
+ 199980,
+ 2690220,
+ 309780,
+ 2800020
+ ],
+ "crs": "http://www.opengis.net/def/crs/EPSG/0/32629",
+ "band_metadata": [
+ [
+ "b1",
+ {}
+ ]
+ ],
+ "band_descriptions": [
+ [
+ "b1",
+ ""
+ ]
+ ],
+ "dtype": "uint16",
+ "nodata_type": "Nodata",
+ "colorinterp": [
+ "gray"
+ ],
+ "scales": [
+ 1
+ ],
+ "offsets": [
+ 0
+ ],
+ "driver": "GTiff",
+ "count": 1,
+ "width": 549,
+ "height": 549,
+ "overviews": [
+ 2
+ ],
+ "nodata_value": 0
+ }
+ img = cr.tile(238, 218, 9, assets=("band1", "band2"))
+
+ print(img.assets)
+ >>> ['my_dir/scene_band1.tif', 'my_dir/scene_band2.tif']
+
+ # Each assets have 1 bands, so when combining each img we get a (2, 256, 256) array.
+ print(img.data.shape)
+ >>> (2, 256, 256)
+
Almost as the previous MultiBaseReader
, the MultiBandsReader
children will merge results extracted from different file but taking each file as individual bands.
The MultiBaseReader
has the same attributes/properties/methods as the BaseReader
.
Example
+import os
+import pathlib
+from typing import Dict, Type
+
+import attr
+from morecantile import TileMatrixSet
+from rio_tiler.io.base import MultiBandReader
+from rio_tiler.io import COGReader, BaseReader
+from rio_tiler.constants import WEB_MERCATOR_TMS
+
+@attr.s
+class BandFileReader(MultiBandReader):
+
+ input: str = attr.ib()
+ prefix: str = attr.ib() # we add a custom attribute
+
+ # because we add another attribute (prefix) we need to
+ # re-specify the other attribute for the class
+ reader: Type[BaseReader] = attr.ib(default=COGReader)
+ reader_options: Dict = attr.ib(factory=dict)
+ tms: TileMatrixSet = attr.ib(default=WEB_MERCATOR_TMS)
+
+ # we place min/max zoom in __init__
+ minzoom: int = attr.ib(default=None)
+ maxzoom: int = attr.ib(default=None)
+
+ def __attrs_post_init__(self):
+ """Parse Sceneid and get grid bounds."""
+ self.bands = sorted(
+ [p.stem.split("_")[1] for p in pathlib.Path(self.input).glob(f"*{self.prefix}*.tif")]
+ )
+ with self.reader(self._get_band_url(self.bands[0])) as cog:
+ self.bounds = cog.bounds
+ self.crs = cog.crs
+ self.transform = cog.transform
+ self.height = cog.height
+ self.width = cog.width
+ if self.minzoom is None:
+ self.minzoom = cog.minzoom
+
+ if self.maxzoom is None:
+ self.maxzoom = cog.maxzoom
+
+ def _get_band_url(self, band: str) -> str:
+ """Validate band's name and return band's url."""
+ return os.path.join(self.input, f"{self.prefix}{band}.tif")
+
+
+# we have a directoty with "scene_b1.tif", "scene_b2.tif"
+with BandFileReader(input="my_dir/", prefix="scene_") as cr:
+ print(cr.bands)
+ >>> ['band1', 'band2']
+
+ print(cr.info(bands=("band1", "band2")).model_dump_json(exclude_none=True))
+ >>> {
+ "bounds": [
+ 199980,
+ 2690220,
+ 309780,
+ 2800020
+ ],
+ "crs": "http://www.opengis.net/def/crs/EPSG/0/32629",
+ "band_metadata": [
+ [
+ "band1",
+ {}
+ ],
+ [
+ "band2",
+ {}
+ ]
+ ],
+ "band_descriptions": [
+ [
+ "band1",
+ ""
+ ],
+ [
+ "band2",
+ ""
+ ]
+ ],
+ "dtype": "uint16",
+ "nodata_type": "Nodata",
+ "colorinterp": [
+ "gray",
+ "gray"
+ ]
+ }
+
+ img = cr.tile(238, 218, 9, bands=("band1", "band2"))
+
+ print(img.assets)
+ >>> ['my_dir/scene_band1.tif', 'my_dir/scene_band2.tif']
+
+ print(img.data.shape)
+ >>> (2, 256, 256)
+
Note: rio-tiler-pds
readers are built using the MultiBandReader
base class.
The example was created as a response to developmentseed/titiler?235. In short, the user needed a way to keep metadata information from an asset within a STAC item.
+Sadly when we are using the STAC Reader we only keep the metadata about the item but not the assets metadata (because we built the STAC Reader with the idea that user might first want to merge assets together).
+But rio-tiler has been designed to be easily customizable.
+import attr
+from rasterio.io import DatasetReader
+from rio_tiler.io.stac import fetch, _to_pystac_item
+from rio_tiler.io import Reader
+import pystac
+
+@attr.s
+class CustomSTACReader(Reader):
+ """Custom Reader support."""
+
+ # This will keep the STAC item info within the instance
+ item: pystac.Item = attr.ib(default=None, init=False)
+
+ def __attrs_post_init__(self):
+ """Define _kwargs, open dataset and get info."""
+ # get STAC item URL and asset name
+ asset = self.input.split(":")[-1]
+ stac_url = self.input.replace(f":{asset}", "")
+
+ # Fetch the STAC item
+ self.item = pystac.Item.from_dict(fetch(stac_url), stac_url)
+
+ # Get asset url from the STAC Item
+ self.input = self.item.assets[asset].get_absolute_href()
+ super().__attrs_post_init__()
+
+with CustomSTACReader("https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json:pan") as cog:
+ print(type(cog.dataset))
+ print(cog.input)
+ print(cog.nodata)
+ print(cog.bounds)
+
+>>> rasterio.io.DatasetReader
+>>> "https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/s5_11055_6057_20070622_p10_1_lcc00_cog.tif"
+>>> 0
+>>> (-869900.0, 1370200.0, -786360.0, 1453180.0)
+
In this CustomSTACReader
, we are using a custom path schema
in form of {item-url}:{asset-name}
. When creating an instance of CustomSTACReader
, we will do the following:
input
using the asset full url.Reader
initialization (using super().__attrs_post_init__()
)from typing import Any, Dict, List
+
+import attr
+import rasterio
+from rasterio.io import DatasetReader
+from rio_tiler.io import BaseReader
+from rio_tiler.models import BandStatistics, Info, ImageData
+from morecantile import TileMatrixSet
+
+from rio_tiler.constants import BBox, WEB_MERCATOR_TMS
+
+@attr.s
+class SimpleReader(BaseReader):
+
+ input: DatasetReader = attr.ib()
+
+ # We force tms to be outside the class __init__
+ tms: TileMatrixSet = attr.ib(init=False, default=WEB_MERCATOR_TMS)
+
+ def __attrs_post_init__(self):
+ # Set bounds and crs variable
+ self.bounds = self.input.bounds
+ self.crs = self.input.crs
+ self.transform = self.input.transform
+ self.height = self.input.height
+ self.width = self.input.width
+
+ @property
+ def minzoom(self):
+ """Return dataset minzoom."""
+ return self._minzoom
+
+ @property
+ def maxzoom(self):
+ """Return dataset maxzoom."""
+ return self._maxzoom
+
+ # implement all mandatory methods
+ def info(self) -> Info:
+ raise NotImplemented
+
+ def statistics(self, **kwargs: Any) -> Dict[str, BandStatistics]:
+ raise NotImplemented
+
+ def part(self, bbox: BBox, **kwargs: Any) -> ImageData:
+ raise NotImplemented
+
+ def preview(self, **kwargs: Any) -> ImageData:
+ raise NotImplemented
+
+ def point(self, lon: float, lat: float, **kwargs: Any) -> List:
+ raise NotImplemented
+
+ def feature(self, shape: Dict, **kwargs: Any) -> ImageData:
+ raise NotImplemented
+
+ def tile(self, tile_x: int, tile_y: int, tile_z: int, **kwargs: Any) -> ImageData:
+ if not self.tile_exists(tile_x, tile_y, tile_z):
+ raise TileOutsideBounds(
+ f"Tile {tile_z}/{tile_x}/{tile_y} is outside bounds"
+ )
+
+ tile_bounds = self.tms.xy_bounds(Tile(x=tile_x, y=tile_y, z=tile_z))
+
+ return reader.part(
+ self.input,
+ tile_bounds,
+ width=256,
+ height=256,
+ bounds_crs=tms.rasterio_crs,
+ dst_crs=tms.rasterio_crs,
+ **kwargs,
+ )
+
+
+with rasterio.open("file.tif") as src:
+ with SimpleReader(src) as cog:
+ img = cog.tile(1, 1, 1)
+
rio-tiler
aims to be a lightweight plugin for rasterio
to read slippy map
+tiles from a raster sources.
Given that rio-tiler
allows for simple, efficient reading of tiles, you can
+then leverage rio-tiler
to create a dynamic tile server to display raster
+tiles on a web map.
There are couple tile servers built on top of rio-tiler:
+ +To build a simple dynamic tiling application, we can use
+FastAPI. Note that titiler
uses
+FastAPI
internally, so you might consider using titiler
instead of making
+your own API.
rio-tiler ~= 4.0
fastapi
uvicorn
Install with
+pip install fastapi uvicorn rio-tiler
+
app.py
¶"""rio-tiler tile server."""
+
+import os
+
+from fastapi import FastAPI, Query
+from starlette.requests import Request
+from starlette.responses import Response
+
+from rio_tiler.profiles import img_profiles
+from rio_tiler.io import Reader
+
+
+app = FastAPI(
+ title="rio-tiler",
+ description="A lightweight Cloud Optimized GeoTIFF tile server",
+)
+
+
+@app.get(
+ r"/{z}/{x}/{y}.png",
+ responses={
+ 200: {
+ "content": {"image/png": {}}, "description": "Return an image.",
+ }
+ },
+ response_class=Response,
+ description="Read COG and return a tile",
+)
+def tile(
+ z: int,
+ x: int,
+ y: int,
+ url: str = Query(..., description="Cloud Optimized GeoTIFF URL."),
+):
+ """Handle tile requests."""
+ with Reader(url) as cog:
+ img = cog.tile(x, y, z)
+
+ content = img.render(img_format="PNG", **img_profiles.get("png"))
+ return Response(content, media_type="image/png")
+
+
+@app.get("/tilejson.json", responses={200: {"description": "Return a tilejson"}})
+def tilejson(
+ request: Request,
+ url: str = Query(..., description="Cloud Optimized GeoTIFF URL."),
+):
+ """Return TileJSON document for a COG."""
+ tile_url = str(request.url_for("tile", z="{z}", x="{x}", y="{y}"))
+ tile_url = f"{tile_url}?url={url}"
+
+ with Reader(url) as cog:
+ return {
+ "bounds": cog.get_geographic_bounds(cog.tms.rasterio_geographic_crs),
+ "minzoom": cog.minzoom,
+ "maxzoom": cog.maxzoom,
+ "name": os.path.basename(url),
+ "tiles": [tile_url],
+ }
+
Use uvicorn
to launch the application. Note that app:app
tells uvicorn
to
+call the app
function within app.py
, so you must be in the same directory as
+app.py
.
uvicorn app:app --reload
+
Starting with rio-tiler
v2, a .feature()
method exists on rio-tiler
's readers (e.g Reader
) which enables data reading for GeoJSON defined (polygon or multipolygon) shapes.
from rio_tiler.io import Reader
+from rio_tiler.models import ImageData
+
+with Reader("my-tif.tif") as cog:
+ # Read data for a given geojson polygon
+ img: ImageData = cog.feature(geojson_feature, max_size=1024) # we limit the max_size to 1024
+
Under the hood, the .feature
method uses rasterio's rasterize
+function and the .part()
method. The below process is roughly what .feature
does for you.
from rasterio.features import rasterize, bounds as featureBounds
+
+from rio_tiler.io import Reader
+
+# Use Reader to open and read the dataset
+with Reader("my_tif.tif") as cog:
+
+ # Get BBOX of the polygon
+ bbox = featureBounds(feat)
+
+ # Read part of the data overlapping with the geometry bbox
+ # assuming that the geometry coordinates are in web mercator
+ img = cog.part(bbox, bounds_crs=f"EPSG:3857", max_size=1024)
+
+ # Rasterize geometry using the same geotransform parameters
+ cutline = rasterize(
+ [feat],
+ out_shape=(img.height, img.width),
+ transform=img.transform,
+ ...
+ )
+
+ # Apply geometry mask to imagery
+ img.array.mask = numpy.where(~cutline, img.array.mask, True)
+
Another interesting way to cut features is to use the GDALWarpVRT's cutline
+option with the .part(), .preview(), or .tile() methods:
from rio_tiler.utils import create_cutline
+
+bbox = featureBounds(feat)
+
+# Use Reader to open and read the dataset
+with Reader("my_tif.tif") as cog:
+ # Create WTT Cutline
+ cutline = create_cutline(cog.dataset, feat, geometry_crs="epsg:4326")
+
+ # Get a part of the geotiff but use the cutline to mask the data
+ bbox = featureBounds(feat)
+ img = cog.part(bbox, vrt_options={'cutline': cutline})
+
+ # Get a preview of the whole geotiff but use the cutline to mask the data
+ img = cog.preview(vrt_options={'cutline': cutline})
+
+ # Read a mercator tile and use the cutline to mask the data
+ img = cog.tile(1, 1, 1, vrt_options={'cutline': cutline})
+
Readers
¶rio-tiler
's Readers provide simple .statistics
method to retrieve dataset global statistics
with Reader("my.tif") as src:
+ stats = src.statistics()
+
+# Statistics result is in form of Dict[str, rio_tiler.models.BandStatistics]
+print(stats.keys())
+>>> ["b1", "b2", "b3"]
+
+# rio_tiler.models.BandStatistics is a pydantic model
+print(stats["1"].model_dump().keys())
+[
+ "min",
+ "max",
+ "mean",
+ "count",
+ "sum",
+ "std",
+ "median",
+ "majority",
+ "minority",
+ "unique",
+ "histogram",
+ "valid_percent",
+ "masked_pixels",
+ "valid_pixels",
+ # Percentile entries depend on user inputs
+ "percentile_2",
+ "percentile_98",
+]
+
You can get statistics from ImageData
objects which are returned by all rio-tiler reader methods (e.g. .tile()
, .preview()
, .part()
, ...)
with Reader("cog.tif") as src:
+ image = src.preview()
+ stats = image.statistics()
+
When getting statistics from a feature
, you may want to calculate values from the pixels which intersect with the geometry but also take the pixel intersection percentage into account. Starting with rio-tiler 6.2.0
, we've added a coverage
option to the statistics
utility which enable the user to pass an array representing the coverage percentage such as:
import numpy as np
+from rio_tiler.utils import get_array_statistics
+
+# Data Array
+# 1, 2
+# 3, 4
+data = np.ma.array((1, 2, 3, 4)).reshape((1, 2, 2))
+
+# Coverage Array
+# 0.5, 0
+# 1, 0.25
+coverage = np.array((0.5, 0, 1, 0.25)).reshape((2, 2))
+
+stats = get_array_statistics(data, coverage=coverage)
+assert len(stats) == 1
+assert stats[0]["min"] == 1
+assert stats[0]["max"] == 4
+assert (
+ round(stats[0]["mean"], 4) == 2.5714
+) # sum of weighted array / sum of weights | 4.5 / 1.75 = 2.57
+assert stats[0]["count"] == 1.75
+
align_bounds_with_dataset=True
¶In rio-tiler 6.3,0
a new option has been introduced to reduce artifacts and produce more precise zonal statistics. This option is available in the low-level reader.part()
method used in rio-tiler reader's .feature()
and .part()
methods.
with Reader("cog.tif") as src:
+ data = src.feature(
+ shape,
+ shape_crs=WGS84_CRS,
+ align_bounds_with_dataset=True,
+ )
+
+ coverage_array = data.get_coverage_array(
+ shape,
+ shape_crs=WGS84_CRS,
+ )
+
+ stats = data.statistics(coverage=coverage_array)
+
When passing align_bounds_with_dataset=True
to the reader.part()
method (forwarded from .feature
or .part
reader methods), rio-tiler will adjust the input geometry bounds to match the input dataset resolution/transform and avoid unnecessary resampling.
You can easily extend the rio-tiler's reader to add a .zonal_statistics()
method as:
import attr
+from typing import Any, Union, Optional, List, Dict
+
+from rio_tiler import io
+from rio_tiler.models import BandStatistics
+from rio_tiler.constants import WGS84_CRS
+
+from geojson_pydantic.features import Feature, FeatureCollection
+from geojson_pydantic.geometries import Polygon
+
+class Reader(io.Reader):
+ """Custom Reader with zonal_statistics method."""
+
+ def zonal_statistics(
+ self,
+ geojson: Union[FeatureCollection, Feature],
+ categorical: bool = False,
+ categories: Optional[List[float]] = None,
+ percentiles: Optional[List[int]] = None,
+ hist_options: Optional[Dict] = None,
+ max_size: int = None,
+ **kwargs: Any,
+ ) -> Union[FeatureCollection, Feature]:
+ """Return statistics from GeoJSON features.
+
+ Args:
+ geojson (Feature or FeatureCollection): a GeoJSON Feature or FeatureCollection.
+ categorical (bool): treat input data as categorical data. Defaults to False.
+ categories (list of numbers, optional): list of categories to return value for.
+ percentiles (list of numbers, optional): list of percentile values to calculate. Defaults to `[2, 98]`.
+ hist_options (dict, optional): Options to forward to numpy.histogram function.
+ max_size (int, optional): Limit the size of the longest dimension of the dataset read, respecting bounds X/Y aspect ratio. Defaults to None.
+ kwargs (optional): Options to forward to `self.preview`.
+
+ Returns:
+ Feature or FeatureCollection
+
+ """
+ kwargs = {**self.options, **kwargs}
+
+ hist_options = hist_options or {}
+
+ fc = geojson
+ # We transform the input Feature to a FeatureCollection
+ if isinstance(fc, Feature):
+ fc = FeatureCollection(type="FeatureCollection", features=[geojson])
+
+ for feature in fc:
+ geom = feature.model_dump(exclude_none=True)
+
+ # Get data overlapping with the feature (using Reader.feature method)
+ data = self.feature(
+ geom,
+ shape_crs=WGS84_CRS,
+ align_bounds_with_dataset=True,
+ max_size=max_size,
+ **kwargs,
+ )
+ coverage_array = data.get_coverage_array(
+ geom,
+ shape_crs=WGS84_CRS,
+ )
+
+ stats = data.statistics(
+ categorical=categorical,
+ categories=categories,
+ percentiles=percentiles,
+ hist_options=hist_options,
+ coverage=coverage_array,
+ )
+
+ # Update input feature properties and add the statistics
+ feature.properties = feature.properties or {}
+ feature.properties.update({"statistics": stats})
+
+ return fc.features[0] if isinstance(geojson, Feature) else fc
+
Starting with rio-tiler 2.0, we replaced mercantile
with morecantile
, enabling support for other TileMatrixSets than the default WebMercator grid.
import morecantile
+from rio_tiler.io import Reader
+from rasterio.crs import CRS
+from pyproj import CRS as projCRS
+
+# By default we use WebMercator TMS
+with Reader("my.tif") as cog:
+ img = cog.tile(1, 1, 1)
+ assert img.crs == CRS.from_epsg(3857) # default image output is the TMS crs (WebMercator)
+
+# Print default grids
+for name in morecantile.tms.list():
+ print(name, "-", morecantile.tms.get(name).rasterio_crs)
+
+>>> CanadianNAD83_LCC - EPSG:3978
+ EuropeanETRS89_LAEAQuad - EPSG:3035
+ LINZAntarticaMapTilegrid - EPSG:5482
+ NZTM2000Quad - EPSG:2193
+ UPSAntarcticWGS84Quad - EPSG:5042
+ UPSArcticWGS84Quad - EPSG:5041
+ UTM31WGS84Quad - EPSG:32631
+ WGS1984Quad - EPSG:4326
+ WebMercatorQuad - EPSG:3857
+ WorldCRS84Quad - OGC:CRS84
+ WorldMercatorWGS84Quad - EPSG:3395
+
+
+# Use EPSG:4326 (WGS84) grid
+wgs84_grid = morecantile.tms.get("WorldCRS84Quad")
+with Reader("my.tif", tms=wgs84_grid) as cog:
+ img = cog.tile(1, 1, 1)
+ assert img.crs == CRS.from_epsg(4326)
+
+# Create Custom grid
+extent = [-948.75, -543592.47, 5817.41, -3333128.95] # From https:///epsg.io/3031
+epsg3031TMS = morecantile.TileMatrixSet.custom(
+ extent, projCRS.from_epsg(3031), identifier="MyCustomTmsEPSG3031"
+)
+with Reader("my.tif", tms=epsg3031TMS) as cog:
+ img = cog.tile(1, 1, 1)
+ assert img.crs == CRS.from_epsg(3031)
+
rio-tiler colormap functions and classes.
+ + + + + + + + +Default Colormaps holder.
+ + +Attributes:
+data
+ (dict
)
+ –
+ colormaps. Defaults to rio_tiler.colormap.DEFAULTS_CMAPS
.
get(name: str) -> ColorMapType
+
Fetch a colormap.
+ + +Parameters:
+name
+ (str
)
+ –
+ colormap name.
+Returns + dict: colormap dictionary.
+ +List registered Colormaps.
+Returns + list: list of colormap names.
+ +register(custom_cmap: Dict[str, Union[str, Path, ColorMapType]], overwrite: bool = False) -> ColorMaps
+
Register a custom colormap.
+ + +Parameters:
+custom_cmap
+ (dict
)
+ –
+ custom colormap(s) to register.
+overwrite
+ (bool
, default:
+ False
+)
+ –
+ Overwrite existing colormap with same key. Defaults to False.
+Examples:
+>>> cmap = cmap.register({"acmap": {0: (0, 0, 0, 0), ...}})
+
>>> cmap = cmap.register({"acmap": "acmap.npy"})
+
Remove value from a colormap dict.
+ +Update the alpha value of a colormap index.
+ +_update_cmap(cmap: GDALColorMapType, values: GDALColorMapType) -> None
+
Update a colormap dict.
+ +apply_cmap(data: ndarray, colormap: ColorMapType) -> DataMaskType
+
Apply colormap on data.
+ + +Parameters:
+data
+ (ndarray
)
+ –
+ 1D image array to translate to RGB.
+colormap
+ (dict or sequence
)
+ –
+ GDAL RGBA Color Table dictionary or sequence (for intervals).
+Returns:
+tuple
( DataMaskType
+) –
+ Data (numpy.ndarray) and Mask (numpy.ndarray) values.
+Raises:
+InvalidFormat
+ –
+ If data is not a 1 band dataset (1, col, row).
+apply_discrete_cmap(data: ndarray, colormap: Union[GDALColorMapType, DiscreteColorMapType]) -> DataMaskType
+
Apply discrete colormap.
+ + +Parameters:
+data
+ (ndarray
)
+ –
+ 1D image array to translate to RGB.
+colormap
+ (GDALColorMapType or DiscreteColorMapType
)
+ –
+ Discrete ColorMap dictionary.
+Returns:
+tuple
( DataMaskType
+) –
+ Data (numpy.ndarray) and Alpha band (numpy.ndarray).
+Examples:
+>>> data = numpy.random.randint(0, 3, size=(1, 256, 256))
+ cmap = {
+ 0: (0, 0, 0, 0),
+ 1: (255, 255, 255, 255),
+ 2: (255, 0, 0, 255),
+ 3: (255, 255, 0, 255),
+ }
+ data, mask = apply_discrete_cmap(data, cmap)
+ assert data.shape == (3, 256, 256)
+
apply_intervals_cmap(data: ndarray, colormap: IntervalColorMapType) -> DataMaskType
+
Apply intervals colormap.
+ + +Parameters:
+data
+ (ndarray
)
+ –
+ 1D image array to translate to RGB.
+colormap
+ (IntervalColorMapType
)
+ –
+ Sequence of intervals and color in form of [([min, max], [r, g, b, a]), ...].
+Returns:
+tuple
( DataMaskType
+) –
+ Data (numpy.ndarray) and Alpha band (numpy.ndarray).
+Examples:
+>>> data = numpy.random.randint(0, 3, size=(1, 256, 256))
+ cmap = [
+ ((0, 1), (0, 0, 0, 0)),
+ ((1, 2), (255, 255, 255, 255)),
+ ((2, 3), (255, 0, 0, 255)),
+ ((3, 4), (255, 255, 0, 255)),
+ ]
+
data, mask = apply_intervals_cmap(data, cmap)
+assert data.shape == (3, 256, 256)
+
Parse RGB/RGBA color and return valid rio-tiler compatible RGBA colormap entry.
+ + +Parameters:
+rgba
+ (str or list of int
)
+ –
+ HEX encoded or list RGB or RGBA colors.
+Returns:
+ + + +Examples:
+>>> parse_color("#FFF")
+(255, 255, 255, 255)
+
>>> parse_color("#FF0000FF")
+(255, 0, 0, 255)
+
>>> parse_color("#FF0000")
+(255, 0, 0, 255)
+
>>> parse_color([255, 255, 255])
+(255, 255, 255, 255)
+
rio-tiler constant values.
+ + + + + + + + +Errors and warnings.
+ + + + + + + + +
+ Bases: UserWarning
Automatically removed Alpha band from output array.
+ + + + + + + +
+ Bases: RioTilerError
Can't use asset_as_band with multiple bands.
+ + + + + + + +
+ Bases: RioTilerError
ColorMap is already registered.
+ + + + + + + +
+ Bases: RioTilerError
Mosaic method returned empty array.
+ + + + + + + +
+ Bases: UserWarning
Expression and assets/indexes mixing.
+ + + + + + + +
+ Bases: RioTilerError
Invalid Asset name.
+ + + + + + + +
+ Bases: RioTilerError
Invalid band name.
+ + + + + + + +
+ Bases: RioTilerError
buffer
must be a multiple of 0.5
(e.g: 0.5, 1, 1.5, ...).
+ Bases: RioTilerError
Invalid color format.
+ + + + + + + +
+ Bases: RioTilerError
Invalid colormap name.
+ + + + + + + +
+ Bases: UserWarning
Invalid Output Datatype.
+ + + + + + + +
+ Bases: RioTilerError
Invalid Expression.
+ + + + + + + +
+ Bases: RioTilerError
Invalid image format.
+ + + + + + + +
+ Bases: RioTilerError
Invalid Geographic bounds.
+ + + + + + + +
+ Bases: RioTilerError
Invalid Pixel Selection method for mosaic.
+ + + + + + + +
+ Bases: RioTilerError
Invalid PointData.
+ + + + + + + +
+ Bases: RioTilerError
Missing Assets.
+ + + + + + + +
+ Bases: RioTilerError
Missing bands.
+ + + + + + + +
+ Bases: RioTilerError
Dataset doesn't have CRS information.
+ + + + + + + +
+ Bases: UserWarning
Dataset has no overviews.
+ + + + + + + +
+ Bases: RioTilerError
Point is outside image bounds.
+ + + + + + + +
+ Bases: Exception
Base exception class.
+ + + + + + + +
+ Bases: RioTilerError
Z-X-Y Tile is outside image bounds.
+ + + + + + + +rio-tiler.expression: Parse and Apply expression.
+ + + + + + + + +Apply rio-tiler expression.
+Args:
+blocks (sequence): expression for a specific layer.
+bands (sequence): bands names.
+data (numpy.array): array of bands.
+
Returns:
+MaskedArray
+ –
+ numpy.array: output data.
+Parse rio-tiler band math expression.
+ + +Parameters:
+expression
+ (str
)
+ –
+ band math/combination expression.
+cast
+ (bool
, default:
+ True
+)
+ –
+ cast band names to integers (convert to index values). Defaults to True.
+Returns:
+tuple
( Tuple
+) –
+ band names/indexes.
+Examples:
+>>> parse_expression("b1;b2")
+ (2, 1)
+
>>> parse_expression("B1/B2", cast=False)
+ ("2", "1")
+
rio_tiler.io.base: ABC class for rio-tiler readers.
+ + + + + + + + +
+ Bases: SpatialMixin
Rio-tiler.io BaseReader.
+ + +Attributes:
+input
+ (any
)
+ –
+ Reader's input.
+tms
+ (TileMatrixSet
)
+ –
+ TileMatrixSet grid definition. Defaults to WebMercatorQuad
.
__exit__(exc_type, exc_value, traceback)
+
Support using with Context Managers.
+ +abstractmethod
+
+
+¶abstractmethod
+
+
+¶info() -> Info
+
Return Dataset's info.
+ + +Returns:
+Info
+ –
+ rio_tile.models.Info: Dataset info.
+abstractmethod
+
+
+¶abstractmethod
+
+
+¶preview() -> ImageData
+
Read a preview of a Dataset.
+ + +Returns:
+ImageData
+ –
+ rio_tiler.models.ImageData: ImageData instance with data, mask and input spatial info.
+abstractmethod
+
+
+¶statistics() -> Dict[str, BandStatistics]
+
Return bands statistics from a dataset.
+ + +Returns:
+Dict[str, BandStatistics]
+ –
+ Dict[str, rio_tiler.models.BandStatistics]: bands statistics.
+abstractmethod
+
+
+¶Read a Map tile from the Dataset.
+ + +Parameters:
+tile_x
+ (int
)
+ –
+ Tile's horizontal index.
+tile_y
+ (int
)
+ –
+ Tile's vertical index.
+tile_z
+ (int
)
+ –
+ Tile's zoom level index.
+Returns:
+ImageData
+ –
+ rio_tiler.models.ImageData: ImageData instance with data, mask and tile spatial info.
+
+ Bases: SpatialMixin
Multi Band Reader.
+This Abstract Base Class Reader is suited for dataset that stores spectral bands as separate files (e.g. Sentinel 2).
+ + +Attributes:
+input
+ (any
)
+ –
+ input data.
+tms
+ (TileMatrixSet
)
+ –
+ TileMatrixSet grid definition. Defaults to WebMercatorQuad
.
minzoom
+ (int
)
+ –
+ Set dataset's minzoom.
+maxzoom
+ (int
)
+ –
+ Set dataset's maxzoom.
+reader_options
+ ((dict, option)
)
+ –
+ options to forward to the reader. Defaults to {}
.
__exit__(exc_type, exc_value, traceback)
+
Support using with Context Managers.
+ +abstractmethod
+
+
+¶Validate band name and construct url.
+ +feature(shape: Dict, bands: Optional[Union[Sequence[str], str]] = None, expression: Optional[str] = None, **kwargs: Any) -> ImageData
+
Read and merge parts defined by geojson feature from multiple bands.
+ + +Parameters:
+shape
+ (dict
)
+ –
+ Valid GeoJSON feature.
+bands
+ (sequence of str or str
, default:
+ None
+)
+ –
+ bands to fetch info from.
+expression
+ (str
, default:
+ None
+)
+ –
+ rio-tiler expression for the band list (e.g. b1/b2+b3).
+kwargs
+ (optional
, default:
+ {}
+)
+ –
+ Options to forward to the self.reader.feature
method.
Returns:
+ImageData
+ –
+ rio_tiler.models.ImageData: ImageData instance with data, mask and tile spatial info.
+Return metadata from multiple bands.
+ + +Parameters:
+bands
+ (sequence of str or str
, default:
+ None
+)
+ –
+ band names to fetch info from. Required keyword argument.
+Returns:
+dict
( Info
+) –
+ Multiple bands info in form of {"band1": rio_tile.models.Info}.
+Parse rio-tiler band math expression.
+ +part(bbox: BBox, bands: Optional[Union[Sequence[str], str]] = None, expression: Optional[str] = None, **kwargs: Any) -> ImageData
+
Read and merge parts from multiple bands.
+ + +Parameters:
+bbox
+ (tuple
)
+ –
+ Output bounds (left, bottom, right, top) in target crs.
+bands
+ (sequence of str or str
, default:
+ None
+)
+ –
+ bands to fetch info from.
+expression
+ (str
, default:
+ None
+)
+ –
+ rio-tiler expression for the band list (e.g. b1/b2+b3).
+kwargs
+ (optional
, default:
+ {}
+)
+ –
+ Options to forward to the 'self.reader.part' method.
+Returns:
+ImageData
+ –
+ rio_tiler.models.ImageData: ImageData instance with data, mask and tile spatial info.
+point(lon: float, lat: float, bands: Optional[Union[Sequence[str], str]] = None, expression: Optional[str] = None, **kwargs: Any) -> PointData
+
Read a pixel values from multiple bands.
+ + +Parameters:
+lon
+ (float
)
+ –
+ Longitude.
+lat
+ (float
)
+ –
+ Latitude.
+bands
+ (sequence of str or str
, default:
+ None
+)
+ –
+ bands to fetch info from.
+expression
+ (str
, default:
+ None
+)
+ –
+ rio-tiler expression for the band list (e.g. b1/b2+b3).
+kwargs
+ (optional
, default:
+ {}
+)
+ –
+ Options to forward to the self.reader.point
method.
Returns:
+PointData
+ –
+ PointData
+preview(bands: Optional[Union[Sequence[str], str]] = None, expression: Optional[str] = None, **kwargs: Any) -> ImageData
+
Read and merge previews from multiple bands.
+ + +Parameters:
+bands
+ (sequence of str or str
, default:
+ None
+)
+ –
+ bands to fetch info from.
+expression
+ (str
, default:
+ None
+)
+ –
+ rio-tiler expression for the band list (e.g. b1/b2+b3).
+kwargs
+ (optional
, default:
+ {}
+)
+ –
+ Options to forward to the self.reader.preview
method.
Returns:
+ImageData
+ –
+ rio_tiler.models.ImageData: ImageData instance with data, mask and tile spatial info.
+statistics(bands: Optional[Union[Sequence[str], str]] = None, expression: Optional[str] = None, categorical: bool = False, categories: Optional[List[float]] = None, percentiles: Optional[List[int]] = None, hist_options: Optional[Dict] = None, max_size: int = 1024, **kwargs: Any) -> Dict[str, BandStatistics]
+
Return array statistics for multiple assets.
+ + +Parameters:
+bands
+ (sequence of str or str
, default:
+ None
+)
+ –
+ bands to fetch info from. Required keyword argument.
+expression
+ (str
, default:
+ None
+)
+ –
+ rio-tiler expression for the band list (e.g. b1/b2+b3).
+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]
.
hist_options
+ (dict
, default:
+ None
+)
+ –
+ Options to forward to numpy.histogram function.
+max_size
+ (int
, default:
+ 1024
+)
+ –
+ Limit the size of the longest dimension of the dataset read, respecting bounds X/Y aspect ratio. Defaults to 1024.
+kwargs
+ (optional
, default:
+ {}
+)
+ –
+ Options to forward to the self.preview
method.
Returns:
+dict
( Dict[str, BandStatistics]
+) –
+ Multiple assets statistics in form of {"{band}/{expression}": rio_tiler.models.BandStatistics, ...}.
+tile(tile_x: int, tile_y: int, tile_z: int, bands: Optional[Union[Sequence[str], str]] = None, expression: Optional[str] = None, **kwargs: Any) -> ImageData
+
Read and merge Web Map tiles multiple bands.
+ + +Parameters:
+tile_x
+ (int
)
+ –
+ Tile's horizontal index.
+tile_y
+ (int
)
+ –
+ Tile's vertical index.
+tile_z
+ (int
)
+ –
+ Tile's zoom level index.
+bands
+ (sequence of str or str
, default:
+ None
+)
+ –
+ bands to fetch info from.
+expression
+ (str
, default:
+ None
+)
+ –
+ rio-tiler expression for the band list (e.g. b1/b2+b3).
+kwargs
+ (optional
, default:
+ {}
+)
+ –
+ Options to forward to the self.reader.tile
method.
Returns:
+ImageData
+ –
+ rio_tiler.models.ImageData: ImageData instance with data, mask and tile spatial info.
+
+ Bases: SpatialMixin
MultiBaseReader Reader.
+This Abstract Base Class Reader is suited for dataset that are composed of multiple assets (e.g. STAC).
+ + +Attributes:
+input
+ (any
)
+ –
+ input data.
+tms
+ (TileMatrixSet
)
+ –
+ TileMatrixSet grid definition. Defaults to WebMercatorQuad
.
minzoom
+ (int
)
+ –
+ Set dataset's minzoom.
+maxzoom
+ (int
)
+ –
+ Set dataset's maxzoom.
+reader_options
+ ((dict, option)
)
+ –
+ options to forward to the reader. Defaults to {}
.
__exit__(exc_type, exc_value, traceback)
+
Support using with Context Managers.
+ +abstractmethod
+
+
+¶_get_asset_info(asset: str) -> AssetInfo
+
Validate asset name and construct url.
+ +_get_reader(asset_info: AssetInfo) -> Tuple[Type[BaseReader], Dict]
+
Get Asset Reader and options.
+ +_update_statistics(img: ImageData, indexes: Optional[Indexes] = None, statistics: Optional[Sequence[Tuple[float, float]]] = None)
+
Update ImageData Statistics from AssetInfo.
+ +feature(shape: Dict, assets: Optional[Union[Sequence[str], str]] = None, expression: Optional[str] = None, asset_indexes: Optional[Dict[str, Indexes]] = None, asset_as_band: bool = False, **kwargs: Any) -> ImageData
+
Read and merge parts defined by geojson feature from multiple assets.
+ + +Parameters:
+shape
+ (dict
)
+ –
+ Valid GeoJSON feature.
+assets
+ (sequence of str or str
, default:
+ None
+)
+ –
+ assets to fetch info from.
+expression
+ (str
, default:
+ None
+)
+ –
+ rio-tiler expression for the asset list (e.g. asset1/asset2+asset3).
+asset_indexes
+ (dict
, default:
+ None
+)
+ –
+ Band indexes for each asset (e.g {"asset1": 1, "asset2": (1, 2,)}).
+kwargs
+ (optional
, default:
+ {}
+)
+ –
+ Options to forward to the self.reader.feature
method.
Returns:
+ImageData
+ –
+ rio_tiler.models.ImageData: ImageData instance with data, mask and tile spatial info.
+Return metadata from multiple assets.
+ + +Parameters:
+assets
+ (sequence of str or str
, default:
+ None
+)
+ –
+ assets to fetch info from. Required keyword argument.
+Returns:
+ + +merged_statistics(assets: Optional[Union[Sequence[str], str]] = None, expression: Optional[str] = None, asset_indexes: Optional[Dict[str, Indexes]] = None, categorical: bool = False, categories: Optional[List[float]] = None, percentiles: Optional[List[int]] = None, hist_options: Optional[Dict] = None, max_size: int = 1024, **kwargs: Any) -> Dict[str, BandStatistics]
+
Return array statistics for multiple assets.
+ + +Parameters:
+assets
+ (sequence of str or str
, default:
+ None
+)
+ –
+ assets to fetch info from.
+expression
+ (str
, default:
+ None
+)
+ –
+ rio-tiler expression for the asset list (e.g. asset1/asset2+asset3).
+asset_indexes
+ (dict
, default:
+ None
+)
+ –
+ Band indexes for each asset (e.g {"asset1": 1, "asset2": (1, 2,)}).
+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]
.
hist_options
+ (dict
, default:
+ None
+)
+ –
+ Options to forward to numpy.histogram function.
+max_size
+ (int
, default:
+ 1024
+)
+ –
+ Limit the size of the longest dimension of the dataset read, respecting bounds X/Y aspect ratio. Defaults to 1024.
+kwargs
+ (optional
, default:
+ {}
+)
+ –
+ Options to forward to the self.preview
method.
Returns:
+Dict[str, BandStatistics]
+ –
+ Dict[str, rio_tiler.models.BandStatistics]: bands statistics.
+Parse rio-tiler band math expression.
+ +part(bbox: BBox, assets: Optional[Union[Sequence[str], str]] = None, expression: Optional[str] = None, asset_indexes: Optional[Dict[str, Indexes]] = None, asset_as_band: bool = False, **kwargs: Any) -> ImageData
+
Read and merge parts from multiple assets.
+ + +Parameters:
+bbox
+ (tuple
)
+ –
+ Output bounds (left, bottom, right, top) in target crs.
+assets
+ (sequence of str or str
, default:
+ None
+)
+ –
+ assets to fetch info from.
+expression
+ (str
, default:
+ None
+)
+ –
+ rio-tiler expression for the asset list (e.g. asset1/asset2+asset3).
+asset_indexes
+ (dict
, default:
+ None
+)
+ –
+ Band indexes for each asset (e.g {"asset1": 1, "asset2": (1, 2,)}).
+kwargs
+ (optional
, default:
+ {}
+)
+ –
+ Options to forward to the self.reader.part
method.
Returns:
+ImageData
+ –
+ rio_tiler.models.ImageData: ImageData instance with data, mask and tile spatial info.
+point(lon: float, lat: float, assets: Optional[Union[Sequence[str], str]] = None, expression: Optional[str] = None, asset_indexes: Optional[Dict[str, Indexes]] = None, asset_as_band: bool = False, **kwargs: Any) -> PointData
+
Read pixel value from multiple assets.
+ + +Parameters:
+lon
+ (float
)
+ –
+ Longitude.
+lat
+ (float
)
+ –
+ Latitude.
+assets
+ (sequence of str or str
, default:
+ None
+)
+ –
+ assets to fetch info from.
+expression
+ (str
, default:
+ None
+)
+ –
+ rio-tiler expression for the asset list (e.g. asset1/asset2+asset3).
+asset_indexes
+ (dict
, default:
+ None
+)
+ –
+ Band indexes for each asset (e.g {"asset1": 1, "asset2": (1, 2,)}).
+kwargs
+ (optional
, default:
+ {}
+)
+ –
+ Options to forward to the self.reader.point
method.
Returns:
+PointData
+ –
+ PointData
+preview(assets: Optional[Union[Sequence[str], str]] = None, expression: Optional[str] = None, asset_indexes: Optional[Dict[str, Indexes]] = None, asset_as_band: bool = False, **kwargs: Any) -> ImageData
+
Read and merge previews from multiple assets.
+ + +Parameters:
+assets
+ (sequence of str or str
, default:
+ None
+)
+ –
+ assets to fetch info from.
+expression
+ (str
, default:
+ None
+)
+ –
+ rio-tiler expression for the asset list (e.g. asset1/asset2+asset3).
+asset_indexes
+ (dict
, default:
+ None
+)
+ –
+ Band indexes for each asset (e.g {"asset1": 1, "asset2": (1, 2,)}).
+kwargs
+ (optional
, default:
+ {}
+)
+ –
+ Options to forward to the self.reader.preview
method.
Returns:
+ImageData
+ –
+ rio_tiler.models.ImageData: ImageData instance with data, mask and tile spatial info.
+statistics(assets: Optional[Union[Sequence[str], str]] = None, asset_indexes: Optional[Dict[str, Indexes]] = None, asset_expression: Optional[Dict[str, str]] = None, **kwargs: Any) -> Dict[str, Dict[str, BandStatistics]]
+
Return array statistics for multiple assets.
+ + +Parameters:
+assets
+ (sequence of str or str
, default:
+ None
+)
+ –
+ assets to fetch info from.
+asset_indexes
+ (dict
, default:
+ None
+)
+ –
+ Band indexes for each asset (e.g {"asset1": 1, "asset2": (1, 2,)}).
+asset_expression
+ (dict
, default:
+ None
+)
+ –
+ rio-tiler expression for each asset (e.g. {"asset1": "b1/b2+b3", "asset2": ...}).
+kwargs
+ (optional
, default:
+ {}
+)
+ –
+ Options to forward to the self.reader.statistics
method.
Returns:
+dict
( Dict[str, Dict[str, BandStatistics]]
+) –
+ Multiple assets statistics in form of {"asset1": {"1": rio_tiler.models.BandStatistics, ...}}.
+tile(tile_x: int, tile_y: int, tile_z: int, assets: Optional[Union[Sequence[str], str]] = None, expression: Optional[str] = None, asset_indexes: Optional[Dict[str, Indexes]] = None, asset_as_band: bool = False, **kwargs: Any) -> ImageData
+
Read and merge Wep Map tiles from multiple assets.
+ + +Parameters:
+tile_x
+ (int
)
+ –
+ Tile's horizontal index.
+tile_y
+ (int
)
+ –
+ Tile's vertical index.
+tile_z
+ (int
)
+ –
+ Tile's zoom level index.
+assets
+ (sequence of str or str
, default:
+ None
+)
+ –
+ assets to fetch info from.
+expression
+ (str
, default:
+ None
+)
+ –
+ rio-tiler expression for the asset list (e.g. asset1/asset2+asset3).
+asset_indexes
+ (dict
, default:
+ None
+)
+ –
+ Band indexes for each asset (e.g {"asset1": 1, "asset2": (1, 2,)}).
+kwargs
+ (optional
, default:
+ {}
+)
+ –
+ Options to forward to the self.reader.tile
method.
Returns:
+ImageData
+ –
+ rio_tiler.models.ImageData: ImageData instance with data, mask and tile spatial info.
+Spatial Info Mixin.
+ + +Attributes:
+tms
+ (TileMatrixSet
)
+ –
+ TileMatrixSet grid definition. Defaults to WebMercatorQuad
.
cached
+ property
+
+
+¶_dst_geom_in_tms_crs
+
Return dataset geom info in TMS projection.
+cached
+ property
+
+
+¶_maxzoom: int
+
Calculate dataset maximum zoom level.
+cached
+ property
+
+
+¶_minzoom: int
+
Calculate dataset minimum zoom level.
+get_geographic_bounds(crs: CRS) -> BBox
+
Return Geographic Bounds for a Geographic CRS.
+ +Check if a tile intersects the dataset bounds.
+ + +Parameters:
+tile_x
+ (int
)
+ –
+ Tile's horizontal index.
+tile_y
+ (int
)
+ –
+ Tile's vertical index.
+tile_z
+ (int
)
+ –
+ Tile's zoom level index.
+Returns:
+bool
( bool
+) –
+ True if the tile intersects the dataset bounds.
+rio_tiler.io.rasterio: rio-tiler reader built on top Rasterio
+ + + + + + + + +
+ Bases: Reader
Non Geo Image Reader
+ + + + + + + + + +__attrs_post_init__()
+
Define _kwargs, open dataset and get info.
+ +feature(shape: Dict, indexes: Optional[Indexes] = None, expression: Optional[str] = None, max_size: Optional[int] = None, height: Optional[int] = None, width: Optional[int] = None, force_binary_mask: bool = True, resampling_method: RIOResampling = 'nearest', unscale: bool = False, post_process: Optional[Callable[[MaskedArray], MaskedArray]] = None) -> ImageData
+
Read part of an Image defined by a geojson feature.
+ +part(bbox: BBox, indexes: Optional[Union[int, Sequence]] = None, expression: Optional[str] = None, max_size: Optional[int] = None, height: Optional[int] = None, width: Optional[int] = None, force_binary_mask: bool = True, resampling_method: RIOResampling = 'nearest', unscale: bool = False, post_process: Optional[Callable[[MaskedArray], MaskedArray]] = None) -> ImageData
+
Read part of an Image.
+ + +Parameters:
+bbox
+ (tuple
)
+ –
+ Output bounds (left, bottom, right, top).
+indexes
+ (sequence of int or int
, default:
+ None
+)
+ –
+ Band indexes.
+expression
+ (str
, default:
+ None
+)
+ –
+ rio-tiler expression (e.g. b1/b2+b3).
+max_size
+ (int
, default:
+ None
+)
+ –
+ Limit the size of the longest dimension of the dataset read, respecting bounds X/Y aspect ratio.
+height
+ (int
, default:
+ None
+)
+ –
+ Output height of the array.
+width
+ (int
, default:
+ None
+)
+ –
+ Output width of the array.
+force_binary_mask
+ (bool
, default:
+ True
+)
+ –
+ Cast returned mask to binary values (0 or 255). Defaults to True
.
resampling_method
+ (RIOResampling
, default:
+ 'nearest'
+)
+ –
+ RasterIO resampling algorithm. Defaults to nearest
.
unscale
+ (bool
, default:
+ False
+)
+ –
+ Apply 'scales' and 'offsets' on output data value. Defaults to False
.
post_process
+ (callable
, default:
+ None
+)
+ –
+ Function to apply on output data and mask values.
+Returns:
+ImageData
+ –
+ rio_tiler.models.ImageData: ImageData instance with data, mask and input spatial info.
+point(x: float, y: float, indexes: Optional[Indexes] = None, expression: Optional[str] = None, unscale: bool = False, post_process: Optional[Callable[[MaskedArray], MaskedArray]] = None) -> PointData
+
Read a pixel value from an Image.
+ + +Parameters:
+x
+ (float
)
+ –
+ X coordinate.
+y
+ (float
)
+ –
+ Y coordinate.
+indexes
+ (sequence of int or int
, default:
+ None
+)
+ –
+ Band indexes.
+expression
+ (str
, default:
+ None
+)
+ –
+ rio-tiler expression (e.g. b1/b2+b3).
+unscale
+ (bool
, default:
+ False
+)
+ –
+ Apply 'scales' and 'offsets' on output data value. Defaults to False
.
post_process
+ (callable
, default:
+ None
+)
+ –
+ Function to apply on output data and mask values.
+Returns:
+PointData
+ –
+ PointData
+tile(tile_x: int, tile_y: int, tile_z: int, tilesize: int = 256, indexes: Optional[Indexes] = None, expression: Optional[str] = None, force_binary_mask: bool = True, resampling_method: RIOResampling = 'nearest', unscale: bool = False, post_process: Optional[Callable[[MaskedArray], MaskedArray]] = None) -> ImageData
+
Read a Web Map tile from an Image.
+ + +Parameters:
+tile_x
+ (int
)
+ –
+ Tile's horizontal index.
+tile_y
+ (int
)
+ –
+ Tile's vertical index.
+tile_z
+ (int
)
+ –
+ Tile's zoom level index.
+tilesize
+ (int
, default:
+ 256
+)
+ –
+ Output image size. Defaults to 256
.
indexes
+ (int or sequence of int
, default:
+ None
+)
+ –
+ Band indexes.
+expression
+ (str
, default:
+ None
+)
+ –
+ rio-tiler expression (e.g. b1/b2+b3).
+force_binary_mask
+ (bool
, default:
+ True
+)
+ –
+ Cast returned mask to binary values (0 or 255). Defaults to True
.
resampling_method
+ (RIOResampling
, default:
+ 'nearest'
+)
+ –
+ RasterIO resampling algorithm. Defaults to nearest
.
unscale
+ (bool
, default:
+ False
+)
+ –
+ Apply 'scales' and 'offsets' on output data value. Defaults to False
.
post_process
+ (callable
, default:
+ None
+)
+ –
+ Function to apply on output data and mask values.
+Returns:
+ImageData
+ –
+ rio_tiler.models.ImageData: ImageData instance with data, mask and tile spatial info.
+Fake TMS for non-geo image.
+ + + + + + + + + + + +
+ Bases: BaseReader
Rasterio Reader.
+ + +Attributes:
+input
+ (str
)
+ –
+ dataset path.
+dataset
+ (DatasetReader or DatasetWriter or WarpedVRT
)
+ –
+ Rasterio dataset.
+tms
+ (TileMatrixSet
)
+ –
+ TileMatrixSet grid definition. Defaults to WebMercatorQuad
.
colormap
+ (dict
)
+ –
+ Overwrite internal colormap.
+options
+ (dict
)
+ –
+ Options to forward to low-level reader methods.
+Examples:
+>>> with Reader(src_path) as src:
+ src.tile(...)
+
>>> # Set global options
+ with Reader(src_path, options={"unscale": True, "nodata": 0}) as src:
+ src.tile(...)
+
>>> with rasterio.open(src_path) as src_dst:
+ with WarpedVRT(src_dst, ...) as vrt_dst:
+ with Reader(None, dataset=vrt_dst) as src:
+ src.tile(...)
+
>>> with rasterio.open(src_path) as src_dst:
+ with Reader(None, dataset=src_dst) as src:
+ src.tile(...)
+
__attrs_post_init__()
+
Define _kwargs, open dataset and get info.
+ +__exit__(exc_type, exc_value, traceback)
+
Support using with Context Managers.
+ +feature(shape: Dict, dst_crs: Optional[CRS] = None, shape_crs: CRS = WGS84_CRS, indexes: Optional[Indexes] = None, expression: Optional[str] = None, max_size: Optional[int] = None, height: Optional[int] = None, width: Optional[int] = None, buffer: Optional[NumType] = None, **kwargs: Any) -> ImageData
+
Read part of a Dataset defined by a geojson feature.
+ + +Parameters:
+shape
+ (dict
)
+ –
+ Valid GeoJSON feature.
+dst_crs
+ (CRS
, default:
+ None
+)
+ –
+ Overwrite target coordinate reference system.
+shape_crs
+ (CRS
, default:
+ WGS84_CRS
+)
+ –
+ Input geojson coordinate reference system. Defaults to epsg:4326
.
indexes
+ (sequence of int or int
, default:
+ None
+)
+ –
+ Band indexes.
+expression
+ (str
, default:
+ None
+)
+ –
+ rio-tiler expression (e.g. b1/b2+b3).
+max_size
+ (int
, default:
+ None
+)
+ –
+ Limit the size of the longest dimension of the dataset read, respecting bounds X/Y aspect ratio.
+height
+ (int
, default:
+ None
+)
+ –
+ Output height of the array.
+width
+ (int
, default:
+ None
+)
+ –
+ Output width of the array.
+buffer
+ (int or float
, default:
+ None
+)
+ –
+ Buffer on each side of the given aoi. It must be a multiple of 0.5
. Output image size will be expanded to output imagesize + 2 * buffer
(e.g 0.5 = 257x257, 1.0 = 258x258).
kwargs
+ (optional
, default:
+ {}
+)
+ –
+ Options to forward to the Reader.part
method.
Returns:
+ImageData
+ –
+ rio_tiler.models.ImageData: ImageData instance with data, mask and input spatial info.
+part(bbox: BBox, dst_crs: Optional[CRS] = None, bounds_crs: CRS = WGS84_CRS, indexes: Optional[Union[int, Sequence]] = None, expression: Optional[str] = None, max_size: Optional[int] = None, height: Optional[int] = None, width: Optional[int] = None, buffer: Optional[float] = None, **kwargs: Any) -> ImageData
+
Read part of a Dataset.
+ + +Parameters:
+bbox
+ (tuple
)
+ –
+ Output bounds (left, bottom, right, top) in target crs ("dst_crs").
+dst_crs
+ (CRS
, default:
+ None
+)
+ –
+ Overwrite target coordinate reference system.
+bounds_crs
+ (CRS
, default:
+ WGS84_CRS
+)
+ –
+ Bounds Coordinate Reference System. Defaults to epsg:4326
.
indexes
+ (sequence of int or int
, default:
+ None
+)
+ –
+ Band indexes.
+expression
+ (str
, default:
+ None
+)
+ –
+ rio-tiler expression (e.g. b1/b2+b3).
+max_size
+ (int
, default:
+ None
+)
+ –
+ Limit the size of the longest dimension of the dataset read, respecting bounds X/Y aspect ratio.
+height
+ (int
, default:
+ None
+)
+ –
+ Output height of the array.
+width
+ (int
, default:
+ None
+)
+ –
+ Output width of the array.
+buffer
+ (float
, default:
+ None
+)
+ –
+ Buffer on each side of the given aoi. It must be a multiple of 0.5
. Output image size will be expanded to output imagesize + 2 * buffer
(e.g 0.5 = 257x257, 1.0 = 258x258).
kwargs
+ (optional
, default:
+ {}
+)
+ –
+ Options to forward to the rio_tiler.reader.part
function.
Returns:
+ImageData
+ –
+ rio_tiler.models.ImageData: ImageData instance with data, mask and input spatial info.
+point(lon: float, lat: float, coord_crs: CRS = WGS84_CRS, indexes: Optional[Indexes] = None, expression: Optional[str] = None, **kwargs: Any) -> PointData
+
Read a pixel value from a Dataset.
+ + +Parameters:
+lon
+ (float
)
+ –
+ Longitude.
+lat
+ (float
)
+ –
+ Latitude.
+coord_crs
+ (CRS
, default:
+ WGS84_CRS
+)
+ –
+ Coordinate Reference System of the input coords. Defaults to epsg:4326
.
indexes
+ (sequence of int or int
, default:
+ None
+)
+ –
+ Band indexes.
+expression
+ (str
, default:
+ None
+)
+ –
+ rio-tiler expression (e.g. b1/b2+b3).
+kwargs
+ (optional
, default:
+ {}
+)
+ –
+ Options to forward to the rio_tiler.reader.point
function.
Returns:
+PointData
+ –
+ PointData
+preview(indexes: Optional[Indexes] = None, expression: Optional[str] = None, max_size: int = 1024, height: Optional[int] = None, width: Optional[int] = None, **kwargs: Any) -> ImageData
+
Return a preview of a Dataset.
+ + +Parameters:
+indexes
+ (sequence of int or int
, default:
+ None
+)
+ –
+ Band indexes.
+expression
+ (str
, default:
+ None
+)
+ –
+ rio-tiler expression (e.g. b1/b2+b3).
+max_size
+ (int
, default:
+ 1024
+)
+ –
+ Limit the size of the longest dimension of the dataset read, respecting bounds X/Y aspect ratio. Defaults to 1024.
+height
+ (int
, default:
+ None
+)
+ –
+ Output height of the array.
+width
+ (int
, default:
+ None
+)
+ –
+ Output width of the array.
+kwargs
+ (optional
, default:
+ {}
+)
+ –
+ Options to forward to the self.read
method.
Returns:
+ImageData
+ –
+ rio_tiler.models.ImageData: ImageData instance with data, mask and input spatial info.
+read(indexes: Optional[Indexes] = None, expression: Optional[str] = None, **kwargs: Any) -> ImageData
+
Read the Dataset.
+ + +Parameters:
+indexes
+ (sequence of int or int
, default:
+ None
+)
+ –
+ Band indexes.
+expression
+ (str
, default:
+ None
+)
+ –
+ rio-tiler expression (e.g. b1/b2+b3).
+kwargs
+ (optional
, default:
+ {}
+)
+ –
+ Options to forward to the rio_tiler.reader.read
function.
Returns:
+ImageData
+ –
+ rio_tiler.models.ImageData: ImageData instance with data, mask and input spatial info.
+statistics(categorical: bool = False, categories: Optional[List[float]] = None, percentiles: Optional[List[int]] = None, hist_options: Optional[Dict] = None, max_size: int = 1024, indexes: Optional[Indexes] = None, expression: Optional[str] = None, **kwargs: Any) -> Dict[str, BandStatistics]
+
Return bands statistics from a dataset.
+ + +Parameters:
+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]
.
hist_options
+ (dict
, default:
+ None
+)
+ –
+ Options to forward to numpy.histogram function.
+max_size
+ (int
, default:
+ 1024
+)
+ –
+ Limit the size of the longest dimension of the dataset read, respecting bounds X/Y aspect ratio. Defaults to 1024.
+kwargs
+ (optional
, default:
+ {}
+)
+ –
+ Options to forward to self.read
.
Returns:
+Dict[str, BandStatistics]
+ –
+ Dict[str, rio_tiler.models.BandStatistics]: bands statistics.
+tile(tile_x: int, tile_y: int, tile_z: int, tilesize: int = 256, indexes: Optional[Indexes] = None, expression: Optional[str] = None, buffer: Optional[float] = None, **kwargs: Any) -> ImageData
+
Read a Web Map tile from a Dataset.
+ + +Parameters:
+tile_x
+ (int
)
+ –
+ Tile's horizontal index.
+tile_y
+ (int
)
+ –
+ Tile's vertical index.
+tile_z
+ (int
)
+ –
+ Tile's zoom level index.
+tilesize
+ (int
, default:
+ 256
+)
+ –
+ Output image size. Defaults to 256
.
indexes
+ (int or sequence of int
, default:
+ None
+)
+ –
+ Band indexes.
+expression
+ (str
, default:
+ None
+)
+ –
+ rio-tiler expression (e.g. b1/b2+b3).
+buffer
+ (float
, default:
+ None
+)
+ –
+ Buffer on each side of the given tile. It must be a multiple of 0.5
. Output tilesize will be expanded to tilesize + 2 * tile_buffer
(e.g 0.5 = 257x257, 1.0 = 258x258).
kwargs
+ (optional
, default:
+ {}
+)
+ –
+ Options to forward to the Reader.part
method.
Returns:
+ImageData
+ –
+ rio_tiler.models.ImageData: ImageData instance with data, mask and tile spatial info.
+rio_tiler.io.stac: STAC reader.
+ + + + + + + + +
+ Bases: MultiBaseReader
STAC Reader.
+ + +Attributes:
+input
+ (str
)
+ –
+ STAC Item path, URL or S3 URL.
+item
+ ((dict or Item, STAC)
)
+ –
+ Stac Item.
+tms
+ (TileMatrixSet
)
+ –
+ TileMatrixSet grid definition. Defaults to WebMercatorQuad
.
minzoom
+ (int
)
+ –
+ Set minzoom for the tiles.
+maxzoom
+ (int
)
+ –
+ Set maxzoom for the tiles.
+include_assets
+ (set of string
)
+ –
+ Only Include specific assets.
+exclude_assets
+ (set of string
)
+ –
+ Exclude specific assets.
+include_asset_types
+ (set of string
)
+ –
+ Only include some assets base on their type.
+exclude_asset_types
+ (set of string
)
+ –
+ Exclude some assets base on their type.
+default_assets
+ (list of string
)
+ –
+ Default assets to use if none are defined.
+reader
+ (BaseReader
)
+ –
+ rio-tiler Reader. Defaults to rio_tiler.io.Reader
.
reader_options
+ (dict
)
+ –
+ Additional option to forward to the Reader. Defaults to {}
.
fetch_options
+ (dict
)
+ –
+ Options to pass to rio_tiler.io.stac.fetch
function fetching the STAC Items. Defaults to {}
.
Examples:
+>>> with STACReader(stac_path) as stac:
+ stac.tile(...)
+
>>> with STACReader(stac_path, reader=MyCustomReader, reader_options={...}) as stac:
+ stac.tile(...)
+
>>> my_stac = {
+ "type": "Feature",
+ "stac_version": "1.0.0",
+ ...
+ }
+ with STACReader(None, item=my_stac) as stac:
+ # the dict will be translated to a pystac item
+ assert isinstance(stac.item, pystac.Item)
+ stac.tile(...)
+
__attrs_post_init__()
+
Fetch STAC Item and get list of valid assets.
+ +_get_asset_info(asset: str) -> AssetInfo
+
Validate asset names and return asset's info.
+ + +Parameters:
+asset
+ (str
)
+ –
+ STAC asset name.
+Returns:
+AssetInfo
( AssetInfo
+) –
+ STAC asset info.
+_get_reader(asset_info: AssetInfo) -> Tuple[Type[BaseReader], Dict]
+
Get Asset Reader.
+ +_get_assets(stac_item: Item, include: Optional[Set[str]] = None, exclude: Optional[Set[str]] = None, include_asset_types: Optional[Set[str]] = None, exclude_asset_types: Optional[Set[str]] = None) -> Iterator
+
Get valid asset list.
+ + +Parameters:
+stac_item
+ (Item
)
+ –
+ STAC Item.
+include
+ (Optional[Set[str]]
, default:
+ None
+)
+ –
+ Only Include specific assets.
+exclude
+ (Optional[Set[str]]
, default:
+ None
+)
+ –
+ Exclude specific assets.
+include_asset_types
+ (Optional[Set[str]]
, default:
+ None
+)
+ –
+ Only include some assets base on their type.
+exclude_asset_types
+ (Optional[Set[str]]
, default:
+ None
+)
+ –
+ Exclude some assets base on their type.
+Yields + str: valid STAC asset name.
+ +AWS s3 get object content.
+ +rio_tiler.io.xarray: Xarray Reader.
+ + + + + + + + +
+ Bases: BaseReader
Xarray Reader.
+ + +Attributes:
+dataset
+ (DataArray
)
+ –
+ Xarray DataArray dataset.
+tms
+ (TileMatrixSet
)
+ –
+ TileMatrixSet grid definition. Defaults to WebMercatorQuad
.
Examples:
+>>> ds = xarray.open_dataset(
+ "https://pangeo.blob.core.windows.net/pangeo-public/daymet-rio-tiler/na-wgs84.zarr",
+ engine="zarr",
+ decode_coords="all",
+ consolidated=True,
+ )
+ da = ds["tmax"]
+
with XarrayReader(da) as dst:
+ img = dst.tile(...)
+
property
+
+
+¶Return list of band names
in DataArray.
feature(shape: Dict, dst_crs: Optional[CRS] = None, shape_crs: CRS = WGS84_CRS, reproject_method: WarpResampling = 'nearest', auto_expand: bool = True, nodata: Optional[NoData] = None, max_size: Optional[int] = None, height: Optional[int] = None, width: Optional[int] = None, resampling_method: RIOResampling = 'nearest', **kwargs: Any) -> ImageData
+
Read part of a dataset defined by a geojson feature.
+ + +Parameters:
+shape
+ (dict
)
+ –
+ Valid GeoJSON feature.
+dst_crs
+ (CRS
, default:
+ None
+)
+ –
+ Overwrite target coordinate reference system.
+shape_crs
+ (CRS
, default:
+ WGS84_CRS
+)
+ –
+ Input geojson coordinate reference system. Defaults to epsg:4326
.
reproject_method
+ (WarpResampling
, default:
+ 'nearest'
+)
+ –
+ WarpKernel resampling algorithm. Defaults to nearest
.
auto_expand
+ (boolean
, default:
+ True
+)
+ –
+ When True, rioxarray's clip_box will expand clip search if only 1D raster found with clip. When False, will throw OneDimensionalRaster
error if only 1 x or y data point is found. Defaults to True.
nodata
+ (int or float
, default:
+ None
+)
+ –
+ Overwrite dataset internal nodata value.
+max_size
+ (int
, default:
+ None
+)
+ –
+ Limit the size of the longest dimension of the dataset read, respecting bounds X/Y aspect ratio.
+height
+ (int
, default:
+ None
+)
+ –
+ Output height of the array.
+width
+ (int
, default:
+ None
+)
+ –
+ Output width of the array.
+resampling_method
+ (RIOResampling
, default:
+ 'nearest'
+)
+ –
+ RasterIO resampling algorithm. Defaults to nearest
.
Returns:
+ImageData
+ –
+ rio_tiler.models.ImageData: ImageData instance with data, mask and input spatial info.
+part(bbox: BBox, dst_crs: Optional[CRS] = None, bounds_crs: CRS = WGS84_CRS, reproject_method: WarpResampling = 'nearest', auto_expand: bool = True, nodata: Optional[NoData] = None, max_size: Optional[int] = None, height: Optional[int] = None, width: Optional[int] = None, resampling_method: RIOResampling = 'nearest', **kwargs: Any) -> ImageData
+
Read part of a dataset.
+ + +Parameters:
+bbox
+ (tuple
)
+ –
+ Output bounds (left, bottom, right, top) in target crs ("dst_crs").
+dst_crs
+ (CRS
, default:
+ None
+)
+ –
+ Overwrite target coordinate reference system.
+bounds_crs
+ (CRS
, default:
+ WGS84_CRS
+)
+ –
+ Bounds Coordinate Reference System. Defaults to epsg:4326
.
reproject_method
+ (WarpResampling
, default:
+ 'nearest'
+)
+ –
+ WarpKernel resampling algorithm. Defaults to nearest
.
auto_expand
+ (boolean
, default:
+ True
+)
+ –
+ When True, rioxarray's clip_box will expand clip search if only 1D raster found with clip. When False, will throw OneDimensionalRaster
error if only 1 x or y data point is found. Defaults to True.
nodata
+ (int or float
, default:
+ None
+)
+ –
+ Overwrite dataset internal nodata value.
+max_size
+ (int
, default:
+ None
+)
+ –
+ Limit the size of the longest dimension of the dataset read, respecting bounds X/Y aspect ratio.
+height
+ (int
, default:
+ None
+)
+ –
+ Output height of the array.
+width
+ (int
, default:
+ None
+)
+ –
+ Output width of the array.
+resampling_method
+ (RIOResampling
, default:
+ 'nearest'
+)
+ –
+ RasterIO resampling algorithm. Defaults to nearest
.
Returns:
+ImageData
+ –
+ rio_tiler.models.ImageData: ImageData instance with data, mask and input spatial info.
+point(lon: float, lat: float, coord_crs: CRS = WGS84_CRS, nodata: Optional[NoData] = None, **kwargs: Any) -> PointData
+
Read a pixel value from a dataset.
+ + +Parameters:
+lon
+ (float
)
+ –
+ Longitude.
+lat
+ (float
)
+ –
+ Latitude.
+coord_crs
+ (CRS
, default:
+ WGS84_CRS
+)
+ –
+ Coordinate Reference System of the input coords. Defaults to epsg:4326
.
nodata
+ (int or float
, default:
+ None
+)
+ –
+ Overwrite dataset internal nodata value.
+Returns:
+PointData
+ –
+ PointData
+preview(max_size: int = 1024, height: Optional[int] = None, width: Optional[int] = None, nodata: Optional[NoData] = None, dst_crs: Optional[CRS] = None, reproject_method: WarpResampling = 'nearest', resampling_method: RIOResampling = 'nearest', **kwargs: Any) -> ImageData
+
Return a preview of a dataset.
+ + +Parameters:
+max_size
+ (int
, default:
+ 1024
+)
+ –
+ Limit the size of the longest dimension of the dataset read, respecting bounds X/Y aspect ratio. Defaults to 1024.
+height
+ (int
, default:
+ None
+)
+ –
+ Output height of the array.
+width
+ (int
, default:
+ None
+)
+ –
+ Output width of the array.
+nodata
+ (int or float
, default:
+ None
+)
+ –
+ Overwrite dataset internal nodata value.
+dst_crs
+ (CRS
, default:
+ None
+)
+ –
+ target coordinate reference system.
+reproject_method
+ (WarpResampling
, default:
+ 'nearest'
+)
+ –
+ WarpKernel resampling algorithm. Defaults to nearest
.
resampling_method
+ (RIOResampling
, default:
+ 'nearest'
+)
+ –
+ RasterIO resampling algorithm. Defaults to nearest
.
Returns:
+ImageData
+ –
+ rio_tiler.models.ImageData: ImageData instance with data, mask and input spatial info.
+statistics(categorical: bool = False, categories: Optional[List[float]] = None, percentiles: Optional[List[int]] = None, hist_options: Optional[Dict] = None, nodata: Optional[NoData] = None, **kwargs: Any) -> Dict[str, BandStatistics]
+
Return statistics from a dataset.
+ +tile(tile_x: int, tile_y: int, tile_z: int, tilesize: int = 256, reproject_method: WarpResampling = 'nearest', auto_expand: bool = True, nodata: Optional[NoData] = None, **kwargs: Any) -> ImageData
+
Read a Web Map tile from a dataset.
+ + +Parameters:
+tile_x
+ (int
)
+ –
+ Tile's horizontal index.
+tile_y
+ (int
)
+ –
+ Tile's vertical index.
+tile_z
+ (int
)
+ –
+ Tile's zoom level index.
+tilesize
+ (int
, default:
+ 256
+)
+ –
+ Output image size. Defaults to 256
.
reproject_method
+ (WarpResampling
, default:
+ 'nearest'
+)
+ –
+ WarpKernel resampling algorithm. Defaults to nearest
.
auto_expand
+ (boolean
, default:
+ True
+)
+ –
+ When True, rioxarray's clip_box will expand clip search if only 1D raster found with clip. When False, will throw OneDimensionalRaster
error if only 1 x or y data point is found. Defaults to True.
nodata
+ (int or float
, default:
+ None
+)
+ –
+ Overwrite dataset internal nodata value.
+Returns:
+ImageData
+ –
+ rio_tiler.models.ImageData: ImageData instance with data, mask and tile spatial info.
+rio-tiler models.
+ + + + + + + + +Image Data class.
+ + +Attributes:
+array
+ (MaskedArray
)
+ –
+ image values.
+assets
+ (list
)
+ –
+ list of assets used to construct the data values.
+bounds
+ (BoundingBox
)
+ –
+ bounding box of the data.
+crs
+ (CRS
)
+ –
+ Coordinates Reference System of the bounds.
+metadata
+ (dict
)
+ –
+ Additional metadata. Defaults to {}
.
band_names
+ (list
)
+ –
+ name of each band. Defaults to ["1", "2", "3"]
for 3 bands image.
dataset_statistics
+ (list
)
+ –
+ dataset statistics [(min, max), (min, max)]
Note: mask
should be considered as PER_BAND
so shape should be similar as the data
property
+
+
+¶data: ndarray
+
Return data part of the masked array.
+property
+
+
+¶mask: ndarray
+
Return Mask in form of rasterio dataset mask.
+property
+
+
+¶transform: Affine
+
Returns the affine transform.
+__iter__()
+
Allow for variable expansion (arr, mask = ImageData
)
Apply color-operations formula in place.
+ +apply_colormap(colormap: ColorMapType) -> ImageData
+
Apply colormap to the image data.
+ +Apply expression to the image data.
+ +classmethod
+
+
+¶Create ImageData from a sequence of ImageData objects.
+ + +Parameters:
+data
+ (sequence
)
+ –
+ sequence of ImageData.
+data_as_image() -> ndarray
+
Return the data array reshaped into an image processing/visualization software friendly order.
+(bands, rows, columns) -> (rows, columns, bands).
+ +classmethod
+
+
+¶from_bytes(data: bytes) -> Self
+
Create ImageData from bytes.
+ + +Parameters:
+data
+ (bytes
)
+ –
+ raster dataset as bytes.
+get_coverage_array(shape: Dict, shape_crs: CRS = WGS84_CRS, cover_scale: int = 10) -> NDArray[floating]
+
Post-process image data.
+ + +Parameters:
+shape
+ (Dict
)
+ –
+ GeoJSON geometry or Feature.
+shape_crs
+ (CRS
, default:
+ WGS84_CRS
+)
+ –
+ Coordinates Reference System of shape.
+cover_scale
+ (int
, default:
+ 10
+)
+ –
+ Scale used when generating coverage estimates of each +raster cell by vector feature. Coverage is generated by +rasterizing the feature at a finer resolution than the raster then using a summation to aggregate +to the raster resolution and dividing by the square of cover_scale +to get coverage value for each cell. Increasing cover_scale +will increase the accuracy of coverage values; three orders +magnitude finer resolution (cover_scale=1000) is usually enough to +get coverage estimates with <1% error in individual edge cells coverage +estimates, though much smaller values (e.g., cover_scale=10) are often +sufficient (<10% error) and require less memory.
+Returns:
+ +Note: code adapted from perrygeo/python-rasterstats!136 by @sgoodm
+ +post_process(in_range: Optional[Sequence[IntervalTuple]] = None, out_dtype: Union[str, number] = 'uint8', color_formula: Optional[str] = None, **kwargs: Any) -> ImageData
+
Post-process image data.
+ + +Parameters:
+in_range
+ (tuple
, default:
+ None
+)
+ –
+ input min/max bounds value to rescale from.
+out_dtype
+ (str
, default:
+ 'uint8'
+)
+ –
+ output datatype after rescaling. Defaults to uint8
.
color_formula
+ (str
, default:
+ None
+)
+ –
+ color-ops formula (see: vincentsarago/color-ops).
+kwargs
+ (optional
, default:
+ {}
+)
+ –
+ keyword arguments to forward to rio_tiler.utils.linear_rescale
.
Returns:
+ImageData
( ImageData
+) –
+ new ImageData object with the updated data.
+Examples:
+>>> img.post_process(in_range=((0, 16000), ))
+
>>> img.post_process(color_formula="Gamma RGB 4.1")
+
render(add_mask: bool = True, img_format: str = 'PNG', colormap: Optional[ColorMapType] = None, **kwargs) -> bytes
+
Render data to image blob.
+ + +Parameters:
+add_mask
+ (bool
, default:
+ True
+)
+ –
+ add mask to output image. Defaults to True
.
img_format
+ (str
, default:
+ 'PNG'
+)
+ –
+ output image format. Defaults to PNG
.
colormap
+ (dict or sequence
, default:
+ None
+)
+ –
+ RGBA Color Table dictionary or sequence.
+kwargs
+ (optional
, default:
+ {}
+)
+ –
+ keyword arguments to forward to rio_tiler.utils.render
.
Returns:
+bytes
( bytes
+) –
+ image.
+rescale(in_range: Sequence[IntervalTuple], out_range: Sequence[IntervalTuple] = ((0, 255)), out_dtype: Union[str, number] = 'uint8') -> Self
+
Rescale data in place.
+ +Resize data and mask.
+ +statistics(categorical: bool = False, categories: Optional[List[float]] = None, percentiles: Optional[List[int]] = None, hist_options: Optional[Dict] = None, coverage: Optional[ndarray] = None) -> Dict[str, BandStatistics]
+
Return statistics from ImageData.
+ +Point Data class.
+ + +Attributes:
+array
+ (MaskedArray
)
+ –
+ pixel values.
+band_names
+ (list
)
+ –
+ name of each band. Defaults to ["1", "2", "3"]
for 3 bands image.
coordinates
+ (tuple
)
+ –
+ Point's coordinates.
+crs
+ (CRS
)
+ –
+ Coordinates Reference System of the bounds.
+assets
+ (list
)
+ –
+ list of assets used to construct the data values.
+metadata
+ (dict
)
+ –
+ Additional metadata. Defaults to {}
.
property
+
+
+¶data: ndarray
+
Return data part of the masked array.
+property
+
+
+¶mask: ndarray
+
Return Mask in form of rasterio dataset mask.
+_validate_coordinates(attribute, value)
+
coordinates has to be a 2d list.
+ +_validate_data(attribute, value)
+
PointsData data has to be a 1d array.
+ +Apply expression to the image data.
+ +masked_and_3d(array: ndarray) -> MaskedArray
+
Makes sure we have a 3D array and mask
+ +rescale_image(array: MaskedArray, in_range: Sequence[IntervalTuple], out_range: Sequence[IntervalTuple] = ((0, 255)), out_dtype: Union[str, number] = 'uint8') -> MaskedArray
+
Rescale image data in-place.
+ +to_coordsbbox(bbox) -> Optional[BoundingBox]
+
Convert bbox to CoordsBbox nameTuple.
+ +to_masked(array: ndarray) -> MaskedArray
+
Makes sure we have a MaskedArray.
+ +rio-tiler.mosaic.methods abc class.
+ + + + + + + + +dataclass
+
+
+¶
+ Bases: ABC
Abstract base class for rio-tiler-mosaic methods objects.
+ + + + + + + + + +abstractmethod
+
+
+¶feed(array: MaskedArray)
+
Fill mosaic array.
+ + +Parameters:
+array
+ (ndarray
)
+ –
+ data
+rio_tiler.mosaic.methods.defaults: default mosaic filling methods.
+ + + + + + + + +dataclass
+
+
+¶
+ Bases: MosaicMethodBase
Stack the arrays and return the valid pixel count.
+ + + + + + + + + +property
+
+
+¶data: Optional[MaskedArray]
+
Return valid data count of the data stack.
+dataclass
+
+
+¶
+ Bases: MosaicMethodBase
Feed the mosaic array with the first pixel available.
+ + + + + + + + + +feed(array: Optional[MaskedArray])
+
Add data to the mosaic array.
+ +dataclass
+
+
+¶
+ Bases: MosaicMethodBase
Feed the mosaic array with the highest pixel values.
+ + + + + + + + + +feed(array: Optional[MaskedArray])
+
Add data to the mosaic array.
+ +dataclass
+
+
+¶
+ Bases: MosaicMethodBase
Feed the mosaic array using the last band as decision factor (highest value).
+ + + + + + + + + +feed(array: Optional[MaskedArray])
+
Add data to the mosaic array.
+ +dataclass
+
+
+¶
+ Bases: MosaicMethodBase
Feed the mosaic array using the last band as decision factor (lowest value).
+ + + + + + + + + +feed(array: Optional[MaskedArray])
+
Add data to the mosaic array.
+ +dataclass
+
+
+¶
+ Bases: MosaicMethodBase
Feed the mosaic array with the lowest pixel values.
+ + + + + + + + + +feed(array: Optional[MaskedArray])
+
Add data to the mosaic array.
+ +dataclass
+
+
+¶
+ Bases: MosaicMethodBase
Stack the arrays and return the Mean pixel value.
+ + + + + + + + + +property
+
+
+¶data: Optional[MaskedArray]
+
Return Mean of the data stack.
+dataclass
+
+
+¶
+ Bases: MosaicMethodBase
Stack the arrays and return the Median pixel value.
+ + + + + + + + + +property
+
+
+¶data: Optional[MaskedArray]
+
Return Median of the data stack.
+dataclass
+
+
+¶
+ Bases: MosaicMethodBase
Stack the arrays and return the Standard Deviation value.
+ + + + + + + + + +property
+
+
+¶data: Optional[MaskedArray]
+
Return STDDEV of the data stack.
+rio_tiler.mosaic: create tile from multiple assets.
+ + + + + + + + +mosaic_point_reader(mosaic_assets: Sequence, reader: Callable[..., PointData], *args: Any, pixel_selection: Union[Type[MosaicMethodBase], MosaicMethodBase] = FirstMethod, chunk_size: Optional[int] = None, threads: int = MAX_THREADS, allowed_exceptions: Tuple = (PointOutsideBounds), **kwargs) -> Tuple[PointData, List]
+
Merge multiple assets.
+Args:
+mosaic_assets (sequence): List of assets.
+reader (callable): Reader function. The function MUST take `(asset, *args, **kwargs)` as arguments, and MUST return a PointData object.
+args (Any): Argument to forward to the reader function.
+pixel_selection (MosaicMethod, optional): Instance of MosaicMethodBase class. Defaults to `rio_tiler.mosaic.methods.defaults.FirstMethod`.
+chunk_size (int, optional): Control the number of asset to process per loop.
+threads (int, optional): Number of threads to use. If <= 1, runs single threaded without an event loop. By default reads from the MAX_THREADS environment variable, and if not found defaults to multiprocessing.cpu_count() * 5.
+allowed_exceptions (tuple, optional): List of exceptions which will be ignored. Note: `PointOutsideBounds` is likely to be raised and should be included in the allowed_exceptions. Defaults to `(TileOutsideBounds, )`.
+kwargs (optional): Reader callable's keywords options.
+
Returns:
+ + + +Examples:
+>>> def reader(asset: str, *args, **kwargs) -> PointData:
+ with Reader(asset) as src:
+ return src.point(*args, **kwargs)
+
pt = mosaic_point_reader(["cog.tif", "cog2.tif"], reader, 0, 0)
+
mosaic_reader(mosaic_assets: Sequence, reader: Callable[..., ImageData], *args: Any, pixel_selection: Union[Type[MosaicMethodBase], MosaicMethodBase] = FirstMethod, chunk_size: Optional[int] = None, threads: int = MAX_THREADS, allowed_exceptions: Tuple = (TileOutsideBounds), **kwargs) -> Tuple[ImageData, List]
+
Merge multiple assets.
+Args:
+mosaic_assets (sequence): List of assets.
+reader (callable): Reader function. The function MUST take `(asset, *args, **kwargs)` as arguments, and MUST return an ImageData.
+args (Any): Argument to forward to the reader function.
+pixel_selection (MosaicMethod, optional): Instance of MosaicMethodBase class. Defaults to `rio_tiler.mosaic.methods.defaults.FirstMethod`.
+chunk_size (int, optional): Control the number of asset to process per loop.
+threads (int, optional): Number of threads to use. If <= 1, runs single threaded without an event loop. By default reads from the MAX_THREADS environment variable, and if not found defaults to multiprocessing.cpu_count() * 5.
+allowed_exceptions (tuple, optional): List of exceptions which will be ignored. Note: `TileOutsideBounds` is likely to be raised and should be included in the allowed_exceptions. Defaults to `(TileOutsideBounds, )`.
+kwargs (optional): Reader callable's keywords options.
+
Returns:
+ + + +Examples:
+>>> def reader(asset: str, *args, **kwargs) -> ImageData:
+ with Reader(asset) as src:
+ return src.tile(*args, **kwargs)
+
x, y, z = 10, 10, 4
+img = mosaic_reader(["cog.tif", "cog2.tif"], reader, x, y, z)
+
>>> def reader(asset: str, *args, **kwargs) -> ImageData:
+ with Reader(asset) as src:
+ return src.preview(*args, **kwargs)
+
img = mosaic_reader(["cog.tif", "cog2.tif"], reader)
+
Image file profiles.
+ + + + + + + + +
+ Bases: UserDict
GDAL Image creation options.
+ref: github.com/mapnik/mapnik/wiki/Image-IO#default-output-details.
+ + + + + + + + + + + +
+ Bases: Profile
JPEG creation options ref: www.gdal.org/frmt_jpeg.html.
+ + + + + + + + + +
+ Bases: Profile
PNG creation options ref: www.gdal.org/frmt_png.html.
+ + + + + + + + + +
+ Bases: Profile
PNG creation options ref: www.gdal.org/frmt_png.html.
+ + + + + + + + + +
+ Bases: Profile
WEBP creation options ref: www.gdal.org/frmt_webp.html.
+ + + + + + + + + +rio-tiler.reader: low level reader.
+ + + + + + + + +Apply buffer on bounds.
+ +Get Output Width/Height based on a max_size and dataset shape.
+ +part(src_dst: Union[DatasetReader, DatasetWriter, WarpedVRT], bounds: BBox, height: Optional[int] = None, width: Optional[int] = None, max_size: Optional[int] = None, dst_crs: Optional[CRS] = None, bounds_crs: Optional[CRS] = None, indexes: Optional[Indexes] = None, minimum_overlap: Optional[float] = None, padding: Optional[int] = None, buffer: Optional[float] = None, force_binary_mask: bool = True, nodata: Optional[NoData] = None, vrt_options: Optional[Dict] = None, align_bounds_with_dataset: bool = False, resampling_method: RIOResampling = 'nearest', reproject_method: WarpResampling = 'nearest', unscale: bool = False, post_process: Optional[Callable[[MaskedArray], MaskedArray]] = None) -> ImageData
+
Read part of a dataset.
+ + +Parameters:
+src_dst
+ (DatasetReader or DatasetWriter or WarpedVRT
)
+ –
+ Rasterio dataset.
+bounds
+ (tuple
)
+ –
+ Output bounds (left, bottom, right, top). By default the coordinates are considered to be in either the dataset CRS or in the dst_crs
if set. Use bounds_crs
to set a specific CRS.
height
+ (int
, default:
+ None
+)
+ –
+ Output height of the image.
+width
+ (int
, default:
+ None
+)
+ –
+ Output width of the image.
+max_size
+ (int
, default:
+ None
+)
+ –
+ Limit output size image if not width and height.
+dst_crs
+ (CRS
, default:
+ None
+)
+ –
+ Target coordinate reference system.
+bounds_crs
+ (CRS
, default:
+ None
+)
+ –
+ Overwrite bounds Coordinate Reference System.
+indexes
+ (sequence of int or int
, default:
+ None
+)
+ –
+ Band indexes.
+minimum_overlap
+ (float
, default:
+ None
+)
+ –
+ Minimum % overlap for which to raise an error with dataset not covering enough of the tile.
+padding
+ (int
, default:
+ None
+)
+ –
+ Padding to apply to each bbox edge. Helps reduce resampling artefacts along edges. Defaults to 0
.
buffer
+ (float
, default:
+ None
+)
+ –
+ Buffer to apply to each bbox edge. Defaults to 0.
.
nodata
+ (int or float
, default:
+ None
+)
+ –
+ Overwrite dataset internal nodata value.
+vrt_options
+ (dict
, default:
+ None
+)
+ –
+ Options to be passed to the rasterio.warp.WarpedVRT class.
+align_bounds_with_dataset
+ (bool
, default:
+ False
+)
+ –
+ Align input bounds with dataset transform. Defaults to False
.
resampling_method
+ (RIOResampling
, default:
+ 'nearest'
+)
+ –
+ RasterIO resampling algorithm. Defaults to nearest
.
reproject_method
+ (WarpResampling
, default:
+ 'nearest'
+)
+ –
+ WarpKernel resampling algorithm. Defaults to nearest
.
unscale
+ (bool
, default:
+ False
+)
+ –
+ Apply 'scales' and 'offsets' on output data value. Defaults to False
.
post_process
+ (callable
, default:
+ None
+)
+ –
+ Function to apply on output data and mask values.
+Returns:
+ImageData
+ –
+ ImageData
+point(src_dst: Union[DatasetReader, DatasetWriter, WarpedVRT], coordinates: Tuple[float, float], indexes: Optional[Indexes] = None, coord_crs: CRS = WGS84_CRS, force_binary_mask: bool = True, nodata: Optional[NoData] = None, vrt_options: Optional[Dict] = None, resampling_method: RIOResampling = 'nearest', reproject_method: WarpResampling = 'nearest', unscale: bool = False, post_process: Optional[Callable[[MaskedArray], MaskedArray]] = None) -> PointData
+
Read a pixel value for a point.
+ + +Parameters:
+src_dst
+ (DatasetReader or DatasetWriter or WarpedVRT
)
+ –
+ Rasterio dataset.
+coordinates
+ (tuple
)
+ –
+ Coordinates in form of (X, Y).
+indexes
+ (sequence of int or int
, default:
+ None
+)
+ –
+ Band indexes.
+coord_crs
+ (CRS
, default:
+ WGS84_CRS
+)
+ –
+ Coordinate Reference System of the input coords. Defaults to epsg:4326
.
nodata
+ (int or float
, default:
+ None
+)
+ –
+ Overwrite dataset internal nodata value.
+vrt_options
+ (dict
, default:
+ None
+)
+ –
+ Options to be passed to the rasterio.warp.WarpedVRT class.
+resampling_method
+ (RIOResampling
, default:
+ 'nearest'
+)
+ –
+ RasterIO resampling algorithm. Defaults to nearest
.
reproject_method
+ (WarpResampling
, default:
+ 'nearest'
+)
+ –
+ WarpKernel resampling algorithm. Defaults to nearest
.
unscale
+ (bool
, default:
+ False
+)
+ –
+ Apply 'scales' and 'offsets' on output data value. Defaults to False
.
post_process
+ (callable
, default:
+ None
+)
+ –
+ Function to apply on output data and mask values.
+Returns:
+PointData
+ –
+ PointData
+read(src_dst: Union[DatasetReader, DatasetWriter, WarpedVRT], dst_crs: Optional[CRS] = None, height: Optional[int] = None, width: Optional[int] = None, max_size: Optional[int] = None, indexes: Optional[Indexes] = None, window: Optional[Window] = None, force_binary_mask: bool = True, nodata: Optional[NoData] = None, vrt_options: Optional[Dict] = None, resampling_method: RIOResampling = 'nearest', reproject_method: WarpResampling = 'nearest', unscale: bool = False, post_process: Optional[Callable[[MaskedArray], MaskedArray]] = None) -> ImageData
+
Low level read function.
+ + +Parameters:
+src_dst
+ (DatasetReader or DatasetWriter or WarpedVRT
)
+ –
+ Rasterio dataset.
+dst_crs
+ (CRS
, default:
+ None
+)
+ –
+ Target coordinate reference system.
+height
+ (int
, default:
+ None
+)
+ –
+ Output height of the image.
+width
+ (int
, default:
+ None
+)
+ –
+ Output width of the image.
+max_size
+ (int
, default:
+ None
+)
+ –
+ Limit output size image if not width and height.
+indexes
+ (sequence of int or int
, default:
+ None
+)
+ –
+ Band indexes.
+window
+ (Window
, default:
+ None
+)
+ –
+ Window to read.
+nodata
+ (int or float
, default:
+ None
+)
+ –
+ Overwrite dataset internal nodata value.
+vrt_options
+ (dict
, default:
+ None
+)
+ –
+ Options to be passed to the rasterio.warp.WarpedVRT class.
+resampling_method
+ (RIOResampling
, default:
+ 'nearest'
+)
+ –
+ RasterIO resampling algorithm. Defaults to nearest
.
reproject_method
+ (WarpResampling
, default:
+ 'nearest'
+)
+ –
+ WarpKernel resampling algorithm. Defaults to nearest
.
force_binary_mask
+ (bool
, default:
+ True
+)
+ –
+ Cast returned mask to binary values (0 or 255). Defaults to True
.
unscale
+ (bool
, default:
+ False
+)
+ –
+ Apply 'scales' and 'offsets' on output data value. Defaults to False
.
post_process
+ (callable
, default:
+ None
+)
+ –
+ Function to apply on output data and mask values.
+Returns:
+ImageData
+ –
+ ImageData
+rio_tiler.tasks: tools for handling rio-tiler's future tasks.
+ + + + + + + + +Create Future Tasks.
+ +Filter Tasks to remove Exceptions.
+ + +Parameters:
+tasks
+ (sequence
)
+ –
+ Sequence of 'concurrent.futures._base.Future' or 'Callable'
+allowed_exceptions
+ (tuple
, default:
+ None
+)
+ –
+ List of exceptions which won't be raised.
+Yields:
+Generator
+ –
+ Task results.
+multi_arrays(asset_list: Sequence, reader: Callable[..., ImageData], *args: Any, threads: int = MAX_THREADS, allowed_exceptions: Optional[Tuple] = None, **kwargs: Any) -> ImageData
+
Merge arrays returned from tasks.
+ +rio_tiler.utils: utility functions.
+ + + + + + + + +Convert CRS to URI.
+ +Convert CRS to URN.
+ +Convert CRS to URI.
+Code adapted from github.com/developmentseed/morecantile/blob/1829fe12408e4a1feee7493308f3f02257ef4caf/morecantile/models.py#L148-L161
+ +Return GDAL MEM dataset name.
+ +Yield successive n-sized chunks from l.
+ +_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.
+ +Ensure input shape is valid and reduce features to geometry
+ +Cast input to sequence if not Tuple of List.
+ +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(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(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(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:
+ + +has_alpha_band(src_dst: Union[DatasetReader, DatasetWriter, WarpedVRT]) -> bool
+
Check for alpha band or mask in source.
+ +has_mask_band(src_dst: Union[DatasetReader, DatasetWriter, WarpedVRT]) -> bool
+
Check for mask band in source.
+ +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.
+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(src_dst: Union[DatasetReader, DatasetWriter, WarpedVRT]) -> Tuple
+
Return indexes of non-alpha bands.
+ +normalize_bounds(bounds: BBox) -> BBox
+
Return BBox in correct minx, miny, maxx, maxy order.
+ +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(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"))
+