本文整理汇总了Python中rasterio.transform.guard_transform函数的典型用法代码示例。如果您正苦于以下问题:Python guard_transform函数的具体用法?Python guard_transform怎么用?Python guard_transform使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了guard_transform函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: reproject
def reproject(
source, destination,
src_transform=None, src_crs=None,
dst_transform=None, dst_crs=None,
resampling=RESAMPLING.nearest,
**kwargs):
"""Reproject a source raster to a destination.
If the source and destination are ndarrays, coordinate reference
system definitions and affine transformation parameters are required
for reprojection.
If the source and destination are rasterio Bands, shorthand for
bands of datasets on disk, the coordinate reference systems and
transforms will be read from the appropriate datasets.
"""
if src_transform:
src_transform = guard_transform(src_transform).to_gdal()
if dst_transform:
dst_transform = guard_transform(dst_transform).to_gdal()
_reproject(
source, destination,
src_transform, src_crs,
dst_transform, dst_crs,
resampling, **kwargs)
示例2: test_guard_transform_gdal_TypeError
def test_guard_transform_gdal_TypeError(path_rgb_byte_tif):
"""As part of the 1.0 migration, guard_transform() should raise a TypeError
if a GDAL geotransform is encountered"""
with rasterio.open(path_rgb_byte_tif) as src:
aff = src.transform
with pytest.raises(TypeError):
transform.guard_transform(aff.to_gdal())
示例3: window
def window(self, left, bottom, right, top, boundless=False):
"""Get the window corresponding to the bounding coordinates.
Parameters
----------
left : float
Left (west) bounding coordinate
bottom : float
Bottom (south) bounding coordinate
right : float
Right (east) bounding coordinate
top : float
Top (north) bounding coordinate
boundless: boolean, optional
If boundless is False, window is limited
to extent of this dataset.
Returns
-------
window: tuple
((row_start, row_stop), (col_start, col_stop))
corresponding to the bounding coordinates
"""
transform = guard_transform(self.transform)
return windows.from_bounds(
left, bottom, right, top, transform=transform,
height=self.height, width=self.width, boundless=boundless)
示例4: pad
def pad(array, transform, pad_width, mode=None, **kwargs):
"""pad array and adjust affine transform matrix.
Parameters
----------
array: ndarray
Numpy ndarray, for best results a 2D array
transform: Affine transform
transform object mapping pixel space to coordinates
pad_width: int
number of pixels to pad array on all four
mode: str or function
define the method for determining padded values
Returns
-------
(array, transform): tuple
Tuple of new array and affine transform
Notes
-----
See numpy docs for details on mode and other kwargs:
http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.pad.html
"""
import numpy as np
transform = guard_transform(transform)
padded_array = np.pad(array, pad_width, mode, **kwargs)
padded_trans = list(transform)
padded_trans[2] -= pad_width * padded_trans[0]
padded_trans[5] -= pad_width * padded_trans[4]
return padded_array, Affine(*padded_trans[:6])
示例5: shapes
def shapes(image, mask=None, connectivity=4, transform=IDENTITY):
"""Yields a (shape, image_value) pair for each feature in the image.
The shapes are GeoJSON-like dicts and the image values are ints or floats
depending on the data type of the image.
Features are found using a connected-component labeling algorithm.
The image must be one of int16, int32, uint8, uint16, float32 data types.
Note: due to floating point precision issues, the floating point values
returned from a floating point image may not exactly match the original
values.
If a mask is provided, pixels for which the mask is `False` will be
excluded from feature generation.
"""
valid_dtypes = ('int16', 'int32', 'uint8', 'uint16', 'float32')
if np.dtype(image.dtype).name not in valid_dtypes:
raise ValueError('image dtype must be one of: %s'
% (', '.join(valid_dtypes)))
if mask is not None and np.dtype(mask.dtype) != np.dtype(rasterio.bool_):
raise ValueError("Mask must be dtype rasterio.bool_")
if connectivity not in (4, 8):
raise ValueError("Connectivity Option must be 4 or 8")
transform = guard_transform(transform)
with rasterio.drivers():
for s, v in _shapes(image, mask, connectivity, transform.to_gdal()):
yield s, v
示例6: window
def window(self, left, bottom, right, top, precision=None):
"""Get the window corresponding to the bounding coordinates.
The resulting window is not cropped to the row and column
limits of the dataset.
Parameters
----------
left: float
Left (west) bounding coordinate
bottom: float
Bottom (south) bounding coordinate
right: float
Right (east) bounding coordinate
top: float
Top (north) bounding coordinate
precision: int, optional
Number of decimal points of precision when computing inverse
transform.
Returns
-------
window: Window
"""
transform = guard_transform(self.transform)
return from_bounds(
left, bottom, right, top, transform=transform,
height=self.height, width=self.width, precision=precision)
示例7: shapes
def shapes(image, mask=None, connectivity=4, transform=IDENTITY):
"""Yields a (shape, image_value) pair for each feature in the image.
The shapes are GeoJSON-like dicts and the image values are ints.
Features are found using a connected-component labeling algorithm.
The image must be of unsigned 8-bit integer (rasterio.byte or
numpy.uint8) data type. If a mask is provided, pixels for which the
mask is `False` will be excluded from feature generation.
"""
if np.dtype(image.dtype) != np.dtype(rasterio.ubyte):
raise ValueError("Image must be dtype uint8/ubyte")
if mask is not None and np.dtype(mask.dtype) != np.dtype(rasterio.bool_):
raise ValueError("Mask must be dtype rasterio.bool_")
if connectivity not in (4, 8):
raise ValueError("Connectivity Option must be 4 or 8")
transform = guard_transform(transform)
with rasterio.drivers():
for s, v in _shapes(image, mask, connectivity, transform.to_gdal()):
yield s, v
示例8: run
def run(self, processes=4):
"""TODO"""
if processes == 1:
self.pool = MockTub(init_worker, (self.inpaths, self.global_args))
else:
self.pool = Pool(processes, init_worker, (self.inpaths, self.global_args))
self.options["transform"] = guard_transform(self.options["transform"])
if self.mode == "manual_read":
reader_worker = manual_reader(self.run_function)
elif self.mode == "array_read":
reader_worker = array_reader(self.run_function)
else:
reader_worker = simple_reader(self.run_function)
if isinstance(self.outpath_or_dataset, rasterio.io.DatasetWriter):
destination = self.outpath_or_dataset
else:
destination = rasterio.open(self.outpath_or_dataset, "w", **self.options)
# Open an output file, work through the function in parallel,
# and write out the data.
with destination as dst:
for data, window in self.pool.imap_unordered(reader_worker, self.windows):
dst.write(data, window=window)
self.pool.close()
self.pool.join()
示例9: plotting_extent
def plotting_extent(source, transform=None):
"""Returns an extent in the format needed
for matplotlib's imshow (left, right, bottom, top)
instead of rasterio's bounds (left, bottom, top, right)
Parameters
----------
source : array or dataset object opened in 'r' mode
input data
transform: Affine, required if source is array
Defines the affine transform if source is an array
Returns
-------
tuple of float
left, right, bottom, top
"""
if hasattr(source, 'bounds'):
extent = (source.bounds.left, source.bounds.right,
source.bounds.bottom, source.bounds.top)
elif not transform:
raise ValueError(
"transform is required if source is an array")
else:
transform = guard_transform(transform)
rows, cols = source.shape[0:2]
left, top = transform * (0, 0)
right, bottom = transform * (cols, rows)
extent = (left, right, bottom, top)
return extent
示例10: shapes
def shapes(image, mask=None, connectivity=4, transform=IDENTITY):
"""
Return a generator of (polygon, value) for each each set of adjacent pixels
of the same value.
Parameters
----------
image : numpy ndarray or rasterio Band object
(RasterReader, bidx namedtuple).
Data type must be one of rasterio.int16, rasterio.int32,
rasterio.uint8, rasterio.uint16, or rasterio.float32.
mask : numpy ndarray or rasterio Band object, optional
Values of False or 0 will be excluded from feature generation
Must evaluate to bool (rasterio.bool_ or rasterio.uint8)
connectivity : int, optional
Use 4 or 8 pixel connectivity for grouping pixels into features
transform : Affine transformation, optional
If not provided, feature coordinates will be generated based on pixel
coordinates
Returns
-------
Generator of (polygon, value)
Yields a pair of (polygon, value) for each feature found in the image.
Polygons are GeoJSON-like dicts and the values are the associated value
from the image, in the data type of the image.
Note: due to floating point precision issues, values returned from a
floating point image may not exactly match the original values.
Notes
-----
The amount of memory used by this algorithm is proportional to the number
and complexity of polygons produced. This algorithm is most appropriate
for simple thematic data. Data with high pixel-to-pixel variability, such
as imagery, may produce one polygon per pixel and consume large amounts of
memory.
"""
valid_dtypes = ('int16', 'int32', 'uint8', 'uint16', 'float32')
if np.dtype(image.dtype).name not in valid_dtypes:
raise ValueError('image dtype must be one of: %s'
% (', '.join(valid_dtypes)))
if mask is not None and np.dtype(mask.dtype).name not in ('bool', 'uint8'):
raise ValueError("Mask must be dtype rasterio.bool_ or rasterio.uint8")
if connectivity not in (4, 8):
raise ValueError("Connectivity Option must be 4 or 8")
transform = guard_transform(transform)
with rasterio.drivers():
for s, v in _shapes(image, mask, connectivity, transform.to_gdal()):
yield s, v
示例11: pad
def pad(array, transform, pad_width, mode=None, **kwargs):
"""Returns a padded array and shifted affine transform matrix.
Array is padded using `numpy.pad()`."""
transform = guard_transform(transform)
padded_array = numpy.pad(array, pad_width, mode, **kwargs)
padded_trans = list(transform)
padded_trans[2] -= pad_width*padded_trans[0]
padded_trans[5] -= pad_width*padded_trans[4]
return padded_array, Affine(*padded_trans[:6])
示例12: transform_handler
def transform_handler(ctx, param, value):
"""Get transform value from a template file or command line."""
retval = options.from_like_context(ctx, param, value)
if retval is None and value:
try:
value = json.loads(value)
except ValueError:
pass
try:
retval = guard_transform(value)
except:
raise click.BadParameter(
"'%s' is not recognized as an Affine array." % value,
param=param, param_hint='transform')
return retval
示例13: window_transform
def window_transform(self, window):
"""Get the affine transform for a dataset window.
Parameters
----------
window: rasterio.windows.Window
Dataset window
Returns
-------
transform: Affine
The affine transform matrix for the given window
"""
gtransform = guard_transform(self.transform)
return transform(window, gtransform)
示例14: write_cloud_mask
def write_cloud_mask(arr, profile, cloudmask, threshold=2):
"""
writes the cloud+alpha mask as single-band uint8 tiff
suitable for stacking as an alpha band
threshold defaults to 2; only 2 and above are considered clouds
"""
func = qa_vars['clouds']
data = func(arr)
profile.update(dtype='uint8')
profile.update(transform=guard_transform(profile['transform']))
with rasterio.open(cloudmask, 'w', **profile) as dest:
clouds = (data >= threshold)
nodata = (data == 0)
yesdata = ((clouds + nodata) == 0)
data = (yesdata * 255).astype('uint8')
dest.write(data, 1)
示例15: window_bounds
def window_bounds(self, window):
"""Get the bounds of a window
Parameters
----------
window: rasterio.windows.Window
Dataset window
Returns
-------
bounds : tuple
x_min, y_min, x_max, y_max for the given window
"""
transform = guard_transform(self.transform)
return bounds(window, transform)