本文整理汇总了Python中rasterio.band方法的典型用法代码示例。如果您正苦于以下问题:Python rasterio.band方法的具体用法?Python rasterio.band怎么用?Python rasterio.band使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rasterio
的用法示例。
在下文中一共展示了rasterio.band方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import rasterio [as 别名]
# 或者: from rasterio import band [as 别名]
def __init__(self, band):
# access inherited methods/attributes overridden by __init__
super().__init__(band)
# rasterlayer specific attributes
self.bidx = band.bidx
self.dtype = band.dtype
self.nodata = band.ds.nodata
self.file = band.ds.files[0]
self.ds = band.ds
self.driver = band.ds.meta["driver"]
self.meta = band.ds.meta
self.cmap = "viridis"
self.norm = None
self.categorical = False
self.names = [self._make_name(band.ds.files[0])]
self.count = 1
self._close = band.ds.close
示例2: __init__
# 需要导入模块: import rasterio [as 别名]
# 或者: from rasterio import band [as 别名]
def __init__(self, feature, folder=None, *, timestamp_size=None, **kwargs):
"""
:param feature: EOPatch feature into which data will be imported
:type feature: (FeatureType, str)
:param folder: A directory containing image files or a path of an image file
:type folder: str
:param timestamp_size: In case data will be imported into time-dependant feature this parameter can be used to
specify time dimension. If not specified, time dimension will be the same as size of FeatureType.TIMESTAMP
feature. If FeatureType.TIMESTAMP does not exist it will be set to 1.
When converting data into a feature channels of given tiff image should be in order
T(1)B(1), T(1)B(2), ..., T(1)B(N), T(2)B(1), T(2)B(2), ..., T(2)B(N), ..., ..., T(M)B(N)
where T and B are the time and band indices.
:type timestamp_size: int
:param image_dtype: Type of data of new feature imported from tiff image
:type image_dtype: numpy.dtype
:param no_data_value: Values where given Geo-Tiff image does not cover EOPatch
:type no_data_value: int or float
"""
super().__init__(feature, folder=folder, **kwargs)
self.timestamp_size = timestamp_size
示例3: ConvertRaster2LatLong
# 需要导入模块: import rasterio [as 别名]
# 或者: from rasterio import band [as 别名]
def ConvertRaster2LatLong(InputRasterFile,OutputRasterFile):
"""
Convert a raster to lat long WGS1984 EPSG:4326 coordinates for global plotting
MDH
"""
# import modules
import rasterio
from rasterio.warp import reproject, calculate_default_transform as cdt, Resampling
# read the source raster
with rasterio.open(InputRasterFile) as src:
#get input coordinate system
Input_CRS = src.crs
# define the output coordinate system
Output_CRS = {'init': "epsg:4326"}
# set up the transform
Affine, Width, Height = cdt(Input_CRS,Output_CRS,src.width,src.height,*src.bounds)
kwargs = src.meta.copy()
kwargs.update({
'crs': Output_CRS,
'transform': Affine,
'affine': Affine,
'width': Width,
'height': Height
})
with rasterio.open(OutputRasterFile, 'w', **kwargs) as dst:
for i in range(1, src.count+1):
reproject(
source=rasterio.band(src, i),
destination=rasterio.band(dst, i),
src_transform=src.affine,
src_crs=src.crs,
dst_transform=Affine,
dst_crs=Output_CRS,
resampling=Resampling.bilinear)
示例4: reproject_dataset
# 需要导入模块: import rasterio [as 别名]
# 或者: from rasterio import band [as 别名]
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),
destination=rasterio.band(dst, i),
src_transform=src.transform,
src_crs=src.crs,
dst_transform=transform,
dst_crs=dst_crs,
resampling=rasterio.warp.Resampling.nearest)
return rasterio.open(out_path), out_path
示例5: _write
# 需要导入模块: import rasterio [as 别名]
# 或者: from rasterio import band [as 别名]
def _write(self, arr, file_path=None, driver="GTiff", dtype=None, nodata=None):
"""Internal function to write processed results to a file, usually a tempfile
"""
# generate a file path to a temporary file is file_path is None
file_path, tfile = _file_path_tempfile(file_path)
if dtype is None:
dtype = self.dtype
if nodata is None:
nodata = _get_nodata(dtype)
meta = self.ds.meta
meta["driver"] = driver
meta["nodata"] = nodata
meta["dtype"] = dtype
# mask any nodata values
arr = np.ma.masked_equal(arr, self.nodata)
# replace masked values with the user-specified nodata value
arr = arr.filled(fill_value=nodata)
# write to file
with rasterio.open(file_path, mode="w", **meta) as dst:
dst.write(arr.astype(dtype), 1)
src = rasterio.open(file_path)
band = rasterio.band(src, 1)
layer = pyspatialml.RasterLayer(band)
# override RasterLayer close method if temp file is used
if tfile is not None:
layer.close = tfile.close
return layer
示例6: _extract_by_indices
# 需要导入模块: import rasterio [as 别名]
# 或者: from rasterio import band [as 别名]
def _extract_by_indices(self, rows, cols):
"""Spatial query of Raster object (by-band)
"""
X = np.ma.zeros((len(rows), self.count), dtype="float32")
arr = self.read(masked=True)
X[:, 0] = arr[rows, cols]
return X
示例7: _grid_distance
# 需要导入模块: import rasterio [as 别名]
# 或者: from rasterio import band [as 别名]
def _grid_distance(shape, rows, cols):
"""Generate buffer distances to x,y coordinates.
Parameters
----------
shape : tuple
shape of numpy array (rows, cols) to create buffer distances within.
rows : 1d numpy array
array of row indexes.
cols : 1d numpy array
array of column indexes.
Returns
-------
ndarray
3d numpy array of euclidean grid distances to each x,y coordinate pair
[band, row, col].
"""
# create buffer distances
grids_buffers = np.zeros((shape[0], shape[1], rows.shape[0]),
dtype=np.float32)
for i, (y, x) in enumerate(zip(rows, cols)):
# create 2d array (image) with pick indexes set to z
point_arr = np.zeros((shape[0], shape[1]))
point_arr[y, x] = 1
buffer = ndimage.morphology.distance_transform_edt(1 - point_arr)
grids_buffers[:, :, i] = buffer
# reorder to band, row, column
grids_buffers = grids_buffers.transpose((2, 0, 1))
return grids_buffers
示例8: reprojectedRaster
# 需要导入模块: import rasterio [as 别名]
# 或者: from rasterio import band [as 别名]
def reprojectedRaster(rasterFn,ref_vectorFn):
dst_crs=gpd.read_file(ref_vectorFn).crs
print(dst_crs) #{'init': 'epsg:4326'}
dst_raster_projected=os.path.join(dataFp_1,r"svf_dstRasterProjected_b.tif")
a_T = datetime.datetime.now()
# dst_crs='EPSG:4326'
with rasterio.open(rasterFn) as src:
transform, width, height = 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,
# 'compress': "LZW",
'dtype':rasterio.float32,
})
# print(src.count)
with rasterio.open(dst_raster_projected, 'w', **kwargs) as dst:
for i in range(1, src.count + 1):
reproject(
source=rasterio.band(src, i),
destination=rasterio.band(dst, i),
src_transform=src.transform,
src_crs=src.crs,
dst_transform=transform,
dst_crs=dst_crs,
resampling=Resampling.nearest
)
b_T = datetime.datetime.now()
print("reprojected time span:", b_T-a_T)
#根据Polgyon统计raster栅格信息
示例9: reprojectedRaster
# 需要导入模块: import rasterio [as 别名]
# 或者: from rasterio import band [as 别名]
def reprojectedRaster(rasterFn,ref_vectorFn,dst_raster_projected):
dst_crs=gpd.read_file(ref_vectorFn).crs
print(dst_crs) #{'init': 'epsg:4326'}
a_T = datetime.datetime.now()
# dst_crs='EPSG:4326'
with rasterio.open(rasterFn) as src:
transform, width, height = 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,
# 'compress': "LZW",
'dtype':rasterio.uint8, #rasterio.float32
})
# print(src.count)
with rasterio.open(dst_raster_projected, 'w', **kwargs) as dst:
for i in range(1, src.count + 1):
reproject(
source=rasterio.band(src, i),
destination=rasterio.band(dst, i),
src_transform=src.transform,
src_crs=src.crs,
dst_transform=transform,
dst_crs=dst_crs,
resampling=Resampling.nearest
)
b_T = datetime.datetime.now()
print("reprojected time span:", b_T-a_T)
#根据Polgyon统计raster栅格信息
示例10: _get_bands_subset
# 需要导入模块: import rasterio [as 别名]
# 或者: from rasterio import band [as 别名]
def _get_bands_subset(self, array):
""" Reduce array by selecting a subset of bands
"""
if self.band_indices is None:
return array
if isinstance(self.band_indices, list):
if [band for band in self.band_indices if not isinstance(band, int)]:
raise ValueError('Invalid format in {} list, expected integers'.format(self.band_indices))
return array[..., self.band_indices]
if isinstance(self.band_indices, tuple):
if tuple(map(type, self.band_indices)) != (int, int):
raise ValueError('Invalid format in {} tuple, expected integers'.format(self.band_indices))
return array[..., self.band_indices[0]: self.band_indices[1] + 1]
raise ValueError('Invalid format in {}, expected tuple or list'.format(self.band_indices))
示例11: rasterio_to_gdir
# 需要导入模块: import rasterio [as 别名]
# 或者: from rasterio import band [as 别名]
def rasterio_to_gdir(gdir, input_file, output_file_name,
resampling='cubic'):
"""Reprojects a file that rasterio can read into the glacier directory.
Parameters
----------
gdir : :py:class:`oggm.GlacierDirectory`
the glacier directory
input_file : str
path to the file to reproject
output_file_name : str
name of the output file (must be in cfg.BASENAMES)
resampling : str
nearest', 'bilinear', 'cubic', 'cubic_spline', or one of
https://rasterio.readthedocs.io/en/latest/topics/resampling.html
"""
output_file = gdir.get_filepath(output_file_name)
assert '.tif' in output_file, 'output_file should end with .tif'
if not gdir.has_file('dem'):
raise InvalidWorkflowError('Need a dem.tif file to reproject to')
with rasterio.open(input_file) as src:
kwargs = src.meta.copy()
data = src.read(1)
with rasterio.open(gdir.get_filepath('dem')) as tpl:
kwargs.update({
'crs': tpl.crs,
'transform': tpl.transform,
'width': tpl.width,
'height': tpl.height
})
with rasterio.open(output_file, 'w', **kwargs) as dst:
for i in range(1, src.count + 1):
dest = np.zeros(shape=(tpl.height, tpl.width),
dtype=data.dtype)
reproject(
source=rasterio.band(src, i),
destination=dest,
src_transform=src.transform,
src_crs=src.crs,
dst_transform=tpl.transform,
dst_crs=tpl.crs,
resampling=getattr(Resampling, resampling)
)
dst.write(dest, indexes=i)
示例12: rotated_coordinates
# 需要导入模块: import rasterio [as 别名]
# 或者: from rasterio import band [as 别名]
def rotated_coordinates(layer, n_angles=8, file_path=None, driver='GTiff'):
"""Generate 2d arrays with n_angles rotated coordinates.
Parameters
----------
layer : pyspatialml.RasterLayer, or rasterio.DatasetReader
RasterLayer to use as a template.
n_angles : int, optional. Default is 8
Number of angles to rotate coordinate system by.
file_path : str, optional. Default is None
File path to save to the resulting Raster object. If not supplied then the
raster is saved to a temporary file.
driver : str, optional. Default is 'GTiff'
GDAL driver to use to save raster.
Returns
-------
pyspatialml.Raster
"""
# define x and y grid dimensions
xmin, ymin, xmax, ymax = 0, 0, layer.shape[1], layer.shape[0]
x_range = np.arange(start=xmin, stop=xmax, step=1)
y_range = np.arange(start=ymin, stop=ymax, step=1, dtype=np.float32)
X_var, Y_var, _ = np.meshgrid(x_range, y_range, n_angles)
angles = np.deg2rad(np.linspace(0, 180, n_angles, endpoint=False))
grids_directional = X_var + np.tan(angles) * Y_var
# reorder to band, row, col order
grids_directional = grids_directional.transpose((2, 0, 1))
# create new stack
file_path, tfile = _file_path_tempfile(file_path)
meta = deepcopy(layer.meta)
meta['driver'] = driver
meta['count'] = n_angles
meta['dtype'] = grids_directional.dtype
with rasterio.open(file_path, 'w', **meta) as dst:
dst.write(grids_directional)
new_raster = Raster(file_path)
names = ['angle_' + str(i+1) for i in range(n_angles)]
new_raster.rename({old: new for old, new in zip(new_raster.names, names)})
if tfile is not None:
for layer in new_raster.iloc:
layer.close = tfile.close
return new_raster
示例13: _probfun
# 需要导入模块: import rasterio [as 别名]
# 或者: from rasterio import band [as 别名]
def _probfun(img, estimator):
"""Class probabilities function.
Parameters
----------
img : tuple (window, numpy.ndarray)
A window object, and a 3d ndarray of raster data with the dimensions in
order of (band, rows, columns).
estimator : estimator object implementing 'fit'
The object to use to fit the data.
Returns
-------
numpy.ndarray
Multi band raster as a 3d numpy array containing the probabilities
associated with each class. ndarray dimensions are in the order of
(class, row, column).
"""
window, img = img
if not isinstance(img, pd.DataFrame):
# reshape each image block matrix into a 2D matrix
# first reorder into rows, cols, bands (transpose)
# then resample into 2D array (rows=sample_n, cols=band_values)
n_features, rows, cols = img.shape[0], img.shape[1], img.shape[2]
mask2d = img.mask.any(axis=0)
n_samples = rows * cols
flat_pixels = img.transpose(1, 2, 0).reshape((n_samples, n_features))
flat_pixels = flat_pixels.filled(0)
else:
flat_pixels = img
mask2d = pd.isna(flat_pixels).values
mask2d = mask2d.reshape((window.height, window.width, flat_pixels.shape[1]))
mask2d = mask2d.any(axis=2)
flat_pixels = flat_pixels.fillna(0)
flat_pixels = flat_pixels.values
# predict probabilities
result_proba = estimator.predict_proba(flat_pixels)
# reshape class probabilities back to 3D image [iclass, rows, cols]
result_proba = result_proba.reshape((window.height, window.width, result_proba.shape[1]))
# reshape band into rasterio format [band, row, col]
result_proba = result_proba.transpose(2, 0, 1)
# repeat mask for n_bands
mask3d = np.repeat(
a=mask2d[np.newaxis, :, :], repeats=result_proba.shape[0], axis=0
)
# convert proba to masked array
result_proba = np.ma.masked_array(result_proba, mask=mask3d, fill_value=np.nan)
return result_proba
示例14: _predfun_multioutput
# 需要导入模块: import rasterio [as 别名]
# 或者: from rasterio import band [as 别名]
def _predfun_multioutput(img, estimator):
"""Multi-target prediction function.
Parameters
----------
img : tuple (window, numpy.ndarray)
A window object, and a 3d ndarray of raster data with the dimensions in
order of (band, rows, columns).
estimator : estimator object implementing 'fit'
The object to use to fit the data.
Returns
-------
numpy.ndarray
3d numpy array representing the multi-target prediction result with the
dimensions in the order of (target, row, column).
"""
window, img = img
if not isinstance(img, pd.DataFrame):
# reshape each image block matrix into a 2D matrix
# first reorder into rows, cols, bands(transpose)
# then resample into 2D array (rows=sample_n, cols=band_values)
n_features, rows, cols = img.shape[0], img.shape[1], img.shape[2]
mask2d = img.mask.any(axis=0)
n_samples = rows * cols
flat_pixels = img.transpose(1, 2, 0).reshape((n_samples, n_features))
flat_pixels = flat_pixels.filled(0)
else:
flat_pixels = img
mask2d = pd.isna(flat_pixels).values
mask2d = mask2d.reshape((window.height, window.width, flat_pixels.shape[1]))
mask2d = mask2d.any(axis=2)
flat_pixels = flat_pixels.fillna(0)
flat_pixels = flat_pixels.values
# predict probabilities
result = estimator.predict(flat_pixels)
# reshape class probabilities back to 3D image [iclass, rows, cols]
result = result.reshape((window.height, window.width, result.shape[1]))
# reshape band into rasterio format [band, row, col]
result = result.transpose(2, 0, 1)
# repeat mask for n_bands
mask3d = np.repeat(a=mask2d[np.newaxis, :, :], repeats=result.shape[0], axis=0)
# convert proba to masked array
result = np.ma.masked_array(result, mask=mask3d, fill_value=np.nan)
return result
示例15: _tile_worker
# 需要导入模块: import rasterio [as 别名]
# 或者: from rasterio import band [as 别名]
def _tile_worker(tile):
"""
For each tile, and given an open rasterio src, plus a`global_args` dictionary
with attributes of `base_val`, `interval`, and a `writer_func`,
warp a continous single band raster to a 512 x 512 mercator tile,
then encode this tile into RGB.
Parameters
-----------
tile: list
[x, y, z] indices of tile
Returns
--------
tile, buffer
tuple with the input tile, and a bytearray with the data encoded into
the format created in the `writer_func`
"""
x, y, z = tile
bounds = [
c
for i in (
mercantile.xy(*mercantile.ul(x, y + 1, z)),
mercantile.xy(*mercantile.ul(x + 1, y, z)),
)
for c in i
]
toaffine = transform.from_bounds(*bounds + [512, 512])
out = np.empty((512, 512), dtype=src.meta["dtype"])
reproject(
rasterio.band(src, 1),
out,
dst_transform=toaffine,
dst_crs="epsg:3857",
resampling=Resampling.bilinear,
)
out = data_to_rgb(out, global_args["base_val"], global_args["interval"])
return tile, global_args["writer_func"](out, global_args["kwargs"].copy(), toaffine)