How to use the rasterio.crs.CRS function in rasterio

To help you get started, we’ve selected a few rasterio examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github opendatacube / datacube-core / tests / drivers / test_rio_reader.py View on Github external
def test_rd_internals_crs():
    from rasterio.crs import CRS as RioCRS

    assert _dc_crs(None) is None
    assert _dc_crs(RioCRS()) is None
    assert _dc_crs(RioCRS.from_epsg(3857)).epsg == 3857
    assert _dc_crs(RioCRS.from_wkt(SAMPLE_WKT_WITHOUT_AUTHORITY)).epsg is None
github cogeotiff / rio-tiler / rio_tiler / landsat8.py View on Github external
def _landsat_stats(
    band,
    address_prefix,
    metadata,
    overview_level=None,
    max_size=1024,
    percentiles=(2, 98),
    dst_crs=CRS({"init": "EPSG:4326"}),
    histogram_bins=10,
    histogram_range=None,
):
    """
    Retrieve landsat dataset statistics.

    Attributes
    ----------
    band : str
        Landsat band number
    address_prefix : str
        A Landsat AWS S3 dataset prefix.
    metadata : dict
        Landsat metadata
    overview_level : int, optional
        Overview (decimation) level to fetch.
github data61 / landshark / landshark / tifwrite.py View on Github external
def _make_writer(directory: str,
                 label: str,
                 dtype: np.dtype,
                 image_spec: ImageSpec
                 ) -> BatchWriter:
    crs = rs.crs.CRS(**image_spec.crs)
    params = {
        "driver": "GTiff",
        "width": image_spec.width,
        "height": image_spec.height,
        "count": 1,
        "dtype": dtype,
        "crs": crs,
        "transform": image_spec.affine
    }
    fname = os.path.join(directory, label + ".tif")
    f = rs.open(fname, "w", **params)
    writer = BatchWriter(f, width=image_spec.width, height=image_spec.height,
                         dtype=dtype)
    return writer
github CosmiQ / solaris / solaris / vector / polygon.py View on Github external
if im is not None:
        im = _check_rasterio_im_load(im)
        bbox = transform_bounds(im.crs, gdf.crs, *im.bounds)
        bbox_crs = im.crs
    # use transform_bounds in case the crs is different - no effect if not
    if isinstance(bbox, Polygon):
        bbox = bbox.bounds
    if bbox_crs is None:
        try:
            bbox_crs = gdf.crs
        except AttributeError:
            raise ValueError('If `im` and `bbox_crs` are not provided, `gdf`'
                             'must provide a coordinate reference system.')
    else:
        bbox_crs = _check_crs(bbox_crs)
        bbox_crs = CRS.from_epsg(bbox_crs)
    bbox = transform_bounds(bbox_crs, gdf.crs, *bbox)
    try:
        intersectors = list(sindex.intersection(bbox))
    except RTreeError:
        intersectors = []

    return gdf.iloc[intersectors, :]
github ceholden / yatsm / yatsm / gis / convert.py View on Github external
    'crs': lambda crs: CRS(crs).to_string(),
    'bounds': bounds_to_str,
github modflowpy / flopy / flopy / utils / rasters.py View on Github external
elif array.dtype in Raster.FLOAT64:
            dtype = "float64"
        elif array.dtype in Raster.INT8:
            dtype = "int8"
        elif array.dtype in Raster.INT16:
            dtype = "int16"
        elif array.dtype in Raster.INT32:
            dtype = "int32"
        elif array.dtype in Raster.INT64:
            dtype = "int64"
        else:
            raise TypeError("dtype cannot be determined from Raster")

        meta['dtype'] = dtype

        if isinstance(crs, CRS):
            pass
        elif isinstance(crs, int):
            crs = CRS.from_epsg(crs)
        elif isinstance(crs, str):
            crs = CRS.from_string(crs)
        else:
            TypeError("crs type not understood, provide an epsg or proj4")

        meta['crs'] = crs

        count, height, width = array.shape
        meta['count'] = count
        meta['height'] = height
        meta['width'] = width

        if not isinstance(transform, affine.Affine):
github opendatacube / datacube-core / datacube / utils / geometry / _warp.py View on Github external
from typing import Union, Optional
import rasterio.warp
import rasterio.crs
import numpy as np
from affine import Affine
from . import GeoBox

Resampling = Union[str, int, rasterio.warp.Resampling]  # pylint: disable=invalid-name
Nodata = Optional[Union[int, float]]  # pylint: disable=invalid-name
_WRP_CRS = rasterio.crs.CRS.from_epsg(3857)


def resampling_s2rio(name: str) -> rasterio.warp.Resampling:
    """
    Convert from string to rasterio.warp.Resampling enum, raises ValueError on bad input.
    """
    try:
        return getattr(rasterio.warp.Resampling, name.lower())
    except AttributeError:
        raise ValueError('Bad resampling parameter: {}'.format(name))


def is_resampling_nn(resampling: Resampling) -> bool:
    """
    :returns: True if resampling mode is nearest neighbour
    :returns: False otherwise
github mojodna / marblecutter / marblecutter / tiling.py View on Github external
# coding=utf-8
from __future__ import absolute_import

import logging

import mercantile
from affine import Affine
from rasterio.crs import CRS

from . import Bounds, render

LOG = logging.getLogger(__name__)
TILE_SHAPE = (256, 256)
WEB_MERCATOR_CRS = CRS.from_epsg(3857)
WGS84_CRS = CRS.from_epsg(4326)


def render_tile(tile, catalog, transformation=None, format=None, scale=1, expand=True):
    """Render a tile into Web Mercator.

    Arguments:
        tile {mercantile.Tile} -- Tile to render.
        catalog {catalogs.Catalog} -- Catalog to load sources from.

    Keyword Arguments:
        transformation {Transformation} -- Transformation to apply. (default: {None})
        format {function} -- Output format. (default: {None})
        scale {int} -- Output scale factor. (default: {1})
        expand {bool} -- Whether to expand single-band, paletted sources to RGBA. (default: {True})
github icepack / icepack / icepack / grid / geotiff.py View on Github external
missing : float, optional
        No data value (default -9999)
    crs : int, string, or rasterio.crs.CRS, optional
        Coordinate reference system, specified either as a string, an EPSG
        code, or a CRS object from rasterio
    """
    ny, nx = q.shape
    x0, y0 = q.coordinate(0, 0)
    x1 = q.coordinate(0, 1)[0]
    dx = x1 - x0
    transform = rasterio.Affine(dx, 0, x0, 0, -dx, y0 + dx * ny)

    if isinstance(crs, int):
        crs = rasterio.crs.CRS.from_epsg(crs)
    elif isinstance(crs, str):
        crs = rasterio.crs.CRS.from_string(crs)

    with rasterio.open(filename, 'w', driver='GTiff', dtype=q.data.dtype.type,
        count=1, width=nx, height=ny, transform=transform, crs=crs) as dataset:
        dataset.write(np.flipud(q.data), 1)
github cogeotiff / rio-tiler / rio_tiler / utils.py View on Github external
def _tile_read(
    src_dst,
    bounds,
    tilesize,
    indexes=None,
    nodata=None,
    resampling_method="bilinear",
    tile_edge_padding=2,
    dst_crs=CRS({"init": "EPSG:3857"}),
    bounds_crs=None,
    minimum_tile_cover=None,
    warp_vrt_option={},
):
    """
    Read data and mask.

    Attributes
    ----------
    src_dst : rasterio.io.DatasetReader
        rasterio.io.DatasetReader object
    bounds : list
        Output bounds (left, bottom, right, top) in target crs ("dst_crs").
    tilesize : int
        Output image size
    indexes : list of ints or a single int, optional, (defaults: None)