Python xarray.open_rasterio() Examples

The following are 6 code examples of xarray.open_rasterio(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module xarray , or try the search function .
Example #1
Source File: raster.py    From intake-xarray with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _open_files(self, files):
        import xarray as xr
        das = [xr.open_rasterio(f, chunks=self.chunks, **self._kwargs)
               for f in files]
        out = xr.concat(das, dim=self.dim)

        coords = {}
        if self.pattern:
            coords = {
                k: xr.concat(
                    [xr.DataArray(
                        np.full(das[i].sizes.get(self.dim, 1), v),
                        dims=self.dim
                    ) for i, v in enumerate(values)], dim=self.dim)
                for k, values in reverse_formats(self.pattern, files).items()
            }

        return out.assign_coords(**coords).chunk(self.chunks) 
Example #2
Source File: generic_image.py    From satpy with GNU General Public License v3.0 6 votes vote down vote up
def read(self):
        """Read the image."""
        dataset = rasterio.open(self.finfo['filename'])

        # Create area definition
        if hasattr(dataset, 'crs') and dataset.crs is not None:
            self.area = utils.get_area_def_from_raster(dataset)

        data = xr.open_rasterio(dataset, chunks=(1, CHUNK_SIZE, CHUNK_SIZE))
        attrs = data.attrs.copy()

        # Rename to Satpy convention
        data = data.rename({'band': 'bands'})

        # Rename bands to [R, G, B, A], or a subset of those
        data['bands'] = BANDS[data.bands.size]

        # Mask data if alpha channel is present
        try:
            data = mask_image_data(data)
        except ValueError as err:
            logger.warning(err)

        data.attrs = attrs
        self.file_content['image'] = data 
Example #3
Source File: run_xarray.py    From recipy with Apache License 2.0 5 votes vote down vote up
def open_rasterio(self):
        """
        Use xarray.open_rasterio to read image.tiff.
        """
        file_name = os.path.join(self.data_dir, "image.tiff")
        xarray.open_rasterio(file_name) 
Example #4
Source File: testgeo.py    From hvplot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        try:
            import xarray as xr
            import rasterio  # noqa
            import geoviews  # noqa
            import cartopy.crs as ccrs
        except:
            raise SkipTest('xarray, rasterio, geoviews, or cartopy not available')
        import hvplot.xarray  # noqa
        import hvplot.pandas  # noqa
        self.da = (xr.open_rasterio(
            'https://github.com/mapbox/rasterio/raw/master/tests/data/RGB.byte.tif')
            .sel(band=1))
        self.crs = ccrs.epsg(self.da.crs.split('epsg:')[1]) 
Example #5
Source File: raster.py    From intake-xarray with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _open_dataset(self):
        import xarray as xr
        files = fsspec.open_local(self.urlpath, **self.storage_options)
        if isinstance(files, list):
            self._ds = self._open_files(files)
        else:
            self._ds = xr.open_rasterio(files, chunks=self.chunks,
                                        **self._kwargs) 
Example #6
Source File: util.py    From geoviews with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def load_tiff(filename, crs=None, apply_transform=False, nan_nodata=False, **kwargs):
    """
    Returns an RGB or Image element loaded from a geotiff file.

    The data is loaded using xarray and rasterio. If a crs attribute
    is present on the loaded data it will attempt to decode it into
    a cartopy projection otherwise it will default to a non-geographic
    HoloViews element.

    Parameters
    ----------
    filename: string
      Filename pointing to geotiff file to load
    crs: Cartopy CRS or EPSG string (optional)
      Overrides CRS inferred from the data
    apply_transform: boolean
      Whether to apply affine transform if defined on the data
    nan_nodata: boolean
      If data contains nodata values convert them to NaNs
    **kwargs:
      Keyword arguments passed to the HoloViews/GeoViews element

    Returns
    -------
    element: Image/RGB/QuadMesh element
    """
    try:
        import xarray as xr
    except:
        raise ImportError('Loading tiffs requires xarray to be installed')

    with warnings.catch_warnings():
        warnings.filterwarnings('ignore')
        da = xr.open_rasterio(filename)
    return from_xarray(da, crs, apply_transform, nan_nodata, **kwargs)