How to use the rasterio.warp.calculate_default_transform 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 mapbox / rasterio / tests / test_warp.py View on Github external
def test_calculate_default_transform_single_resolution():
    with rasterio.open("tests/data/RGB.byte.tif") as src:
        target_resolution = 0.1
        target_transform = Affine(
            target_resolution,
            0.0,
            -78.95864996545055,
            0.0,
            -target_resolution,
            25.550873767433984,
        )
        dst_transform, width, height = calculate_default_transform(
            src.crs,
            CRS.from_epsg(4326),
            src.width,
            src.height,
            *src.bounds,
            resolution=target_resolution
        )

        assert dst_transform.almost_equals(target_transform)
        assert width == 24
        assert height == 20
github mapbox / rasterio / tests / test_warp_transform.py View on Github external
def test_one_of_gcps_bounds():
    """at least one of gcps or bounds parameters must be provided"""
    with pytest.raises(ValueError):
        calculate_default_transform(
            'epsg:4326', 'epsg:3857', width=1, height=1)
github DHI-GRAS / terracotta / terracotta / scripts / optimize_rasters.py View on Github external
def _get_vrt(src: DatasetReader, rs_method: int) -> WarpedVRT:
    from terracotta.drivers.raster_base import RasterDriver
    target_crs = RasterDriver._TARGET_CRS
    vrt_transform, vrt_width, vrt_height = calculate_default_transform(
        src.crs, target_crs, src.width, src.height, *src.bounds
    )
    vrt = WarpedVRT(
        src, crs=target_crs, resampling=rs_method, transform=vrt_transform,
        width=vrt_width, height=vrt_height
    )
    return vrt
github opendatacube / odc-tools / old / dea / geom / __init__.py View on Github external
def rio_default_transform(src, dst_crs):
    """ Wrapper for rasterio.warp.calculate_default_transform
        that accepts GeoBox objects
    """
    from rasterio.warp import calculate_default_transform

    bb = src.extent.boundingbox

    return calculate_default_transform(str(src.crs),
                                       str(dst_crs),
                                       src.width,
                                       src.height,
                                       left=bb.left,
                                       right=bb.right,
                                       top=bb.top,
                                       bottom=bb.bottom)
github stevenpawley / Pyspatialml / pyspatialml / raster.py View on Github external
file_path, tfile = _file_path_tempfile(file_path)
        
        if nodata is None:
            nodata = _get_nodata(self.meta['dtype'])
        
        dtype = self.meta['dtype']

        resampling_methods = [i.name for i in rasterio.enums.Resampling]
        if resampling not in resampling_methods:
            raise ValueError(
                'Invalid resampling method.' +
                'Resampling method must be one of {0}:'.format(
                    resampling_methods))

        dst_transform, dst_width, dst_height = calculate_default_transform(
            src_crs=self.crs,
            dst_crs=crs,
            width=self.width,
            height=self.height,
            left=self.bounds.left,
            right=self.bounds.right,
            bottom=self.bounds.bottom,
            top=self.bounds.top)

        meta = deepcopy(self.meta)
        meta['nodata'] = nodata
        meta['width'] = dst_width
        meta['height'] = dst_height
        meta['transform'] = dst_transform
        meta['crs'] = crs
github corteva / rioxarray / rioxarray / rioxarray.py View on Github external
src_data_array, src_crs, dst_crs, dst_resolution=None, dst_shape=None
):
    """Determine the affine of the new projected `xarray.DataArray`"""
    src_bounds = src_data_array.rio.bounds()
    src_height, src_width = src_data_array.rio.shape
    dst_height, dst_width = dst_shape if dst_shape is not None else (None, None)
    resolution_or_width_height = {
        k: v
        for k, v in [
            ("resolution", dst_resolution),
            ("dst_height", dst_height),
            ("dst_width", dst_width),
        ]
        if v is not None
    }
    dst_affine, dst_width, dst_height = rasterio.warp.calculate_default_transform(
        src_crs,
        dst_crs,
        src_width,
        src_height,
        *src_bounds,
        **resolution_or_width_height,
    )
    return dst_affine, dst_width, dst_height
github mojodna / marblecutter / skadi.py View on Github external
def paste((data_src, src_crs, src_transform), data, bounds, resampling=Resampling.lanczos):
    """ "Reproject" src data into the correct position within a larger image"""

    ((left, right), (bottom, top)) = warp.transform(SKADI_CRS, src_crs, bounds[::2], bounds[1::2])
    bounds = (left, bottom, right, top)
    height, width = data_src.shape[1:]
    transform_dst, _, _ = warp.calculate_default_transform(
        src_crs, src_crs, width, height, *bounds)

    print('paste height: ', height)
    print('paste width: ', width)
    print('paste bounds: ', bounds)

    data_dst = np.empty(
        data.shape,
        dtype=data.dtype,
    )

    nodata = _nodata(data_dst.dtype)

    warp.reproject(
        source=data_src,
        destination=data_dst,
github cogeotiff / rio-cogeo / rio_cogeo / utils.py View on Github external
src: rasterio.io.DatasetReader
        Rasterio io.DatasetReader object
    lat: float, optional
        Center latitude of the dataset. This is only needed in case you want to
        apply latitude correction factor to ensure consitent maximum zoom level
        (default: 0.0).
    tilesize: int, optional
        Mercator tile size (default: 256).

    Returns
    -------
    max_zoom: int
        Max zoom level.

    """
    dst_affine, w, h = calculate_default_transform(
        src_dst.crs, "epsg:3857", src_dst.width, src_dst.height, *src_dst.bounds
    )

    native_resolution = max(abs(dst_affine[0]), abs(dst_affine[4]))

    # Correction factor for web-mercator projection latitude distortion
    latitude_correction_factor = math.cos(math.radians(lat))
    corrected_resolution = native_resolution * latitude_correction_factor

    max_zoom = zoom_for_pixelsize(corrected_resolution, tilesize=tilesize)
    return max_zoom
github treigerm / WaterNet / waterNet / geo_util.py View on Github external
def reproject_dataset(geotiff_path):
    """Project a GeoTIFF to the WGS84 coordinate reference system.
    See https://mapbox.github.io/rasterio/topics/reproject.html"""

    # We want to project the GeoTIFF coordinate reference system (crs)
    # to WGS84 (e.g. into the familiar Lat/Lon pairs). WGS84 is analogous
    # to EPSG:4326
    dst_crs = 'EPSG:4326'

    with rasterio.open(geotiff_path) as src:
        transform, width, height = rasterio.warp.calculate_default_transform(
            src.crs, dst_crs, src.width, src.height, *src.bounds)
        kwargs = src.meta.copy()
        kwargs.update({
            'crs': dst_crs,
            'transform': transform,
            'width': width,
            'height': height
        })

        satellite_img_name = get_file_name(geotiff_path)
        out_file_name = "{}_wgs84.tif".format(satellite_img_name)
        out_path = os.path.join(WGS84_DIR, out_file_name)
        with rasterio.open(out_path, 'w', **kwargs) as dst:
            for i in range(1, src.count + 1):
                rasterio.warp.reproject(
                    source=rasterio.band(src, i),
github CosmiQ / solaris / solaris / utils / geo.py View on Github external
def _reproject(input_data, input_type, input_crs, target_crs, dest_path,
               resampling_method='bicubic'):

    if input_type == 'vector':
        output = input_data.to_crs(epsg=target_crs)
        if dest_path is not None:
            output.to_file(dest_path, driver='GeoJSON')

    elif input_type == 'raster':

        if isinstance(input_data, rasterio.DatasetReader):
            transform, width, height = calculate_default_transform(
                CRS.from_epsg(input_crs), CRS.from_epsg(target_crs),
                input_data.width, input_data.height, *input_data.bounds
                )
            kwargs = input_data.meta.copy()
            kwargs.update({'crs': target_crs,
                           'transform': transform,
                           'width': width,
                           'height': height})

            if dest_path is not None:
                with rasterio.open(dest_path, 'w', **kwargs) as dst:
                    for band_idx in range(1, input_data.count + 1):
                        rasterio.warp.reproject(
                            source=rasterio.band(input_data, band_idx),
                            destination=rasterio.band(dst, band_idx),
                            src_transform=input_data.transform,