本文整理匯總了Python中rasterio.windows.Window類的典型用法代碼示例。如果您正苦於以下問題:Python Window類的具體用法?Python Window怎麽用?Python Window使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了Window類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_window_fromslices
def test_window_fromslices(col_off, row_off, col_stop, row_stop):
"""Empty and non-empty absolute windows from slices, tuples, or lists
are valid"""
# Constrain windows to >= 0 in each dimension
assume(col_stop >= col_off)
assume(row_stop >= row_off)
rows = (row_off, row_stop)
cols = (col_off, col_stop)
expected = (col_off, row_off, col_stop - col_off, row_stop - row_off)
assert np.allclose(
Window.from_slices(rows=slice(*rows), cols=slice(*cols)).flatten(),
expected
)
assert np.allclose(
Window.from_slices(rows=rows, cols=cols).flatten(),
expected
)
assert np.allclose(
Window.from_slices(rows=list(rows), cols=list(cols)).flatten(),
expected
)
示例2: test_window_fromslices_negative_start_missing_dim_err
def test_window_fromslices_negative_start_missing_dim_err():
"""Should raise error if width or height are not provided"""
with pytest.raises(WindowError):
Window.from_slices(rows=(-10, 4), cols=(0, 4))
with pytest.raises(WindowError):
Window.from_slices(rows=(0, 4), cols=(-10, 4))
示例3: test_window_class_toslices
def test_window_class_toslices():
"""Test Window.toslices"""
window = Window(row_off=0, col_off=1, num_rows=100, num_cols=200)
yslice, xslice = window.toslices()
assert yslice.start == 0
assert yslice.stop == 100
assert xslice.start == 1
assert xslice.stop == 201
示例4: test_window_fromslices_implicit_err
def test_window_fromslices_implicit_err():
""" height and width are required if stop index is None; failing to
provide them will result in error"""
with pytest.raises(WindowError):
Window.from_slices(rows=(1, None), cols=(1, 4))
with pytest.raises(WindowError):
Window.from_slices(rows=(1, 4), cols=(1, None))
示例5: test_window_fromslices_negative_stop
def test_window_fromslices_negative_stop():
# TODO: Should negative stops even allowed?? Limited to boundless case?
assert np.allclose(
Window.from_slices(rows=(-4, -1), cols=(0, 4), height=10).flatten(),
(0, 6, 4, 3)
)
assert np.allclose(
Window.from_slices(rows=(0, 4), cols=(-4, -1), width=10).flatten(),
(6, 0, 3, 4)
)
示例6: test_window_fromslices_stops_lt_starts
def test_window_fromslices_stops_lt_starts():
"""Should produce empty windows if stop indexes are less than start
indexes"""
assert np.allclose(
Window.from_slices(rows=(4, 2), cols=(0, 4)).flatten(),
(0, 4, 4, 0)
)
assert np.allclose(
Window.from_slices(rows=(0, 4), cols=(4, 2)).flatten(),
(4, 0, 0, 4)
)
示例7: test_window_fromslices_invalid_rows_cols
def test_window_fromslices_invalid_rows_cols():
"""Should raise error if rows or cols are not slices, lists, or tuples
of length 2"""
invalids = (
np.array([0, 4]), # wrong type, but close
'04', # clearly the wrong type but right length
(1, 2, 3) # wrong length
)
for invalid in invalids:
with pytest.raises(WindowError):
Window.from_slices(rows=invalid, cols=(0, 4))
with pytest.raises(WindowError):
Window.from_slices(rows=(0, 4), cols=invalid)
示例8: test_data_window_maskedarray
def test_data_window_maskedarray():
"""Get window of masked arr."""
arr = np.ones((3, 3))
arr[0, :] = 0
arr = np.ma.masked_array(arr, arr == 0)
window = get_data_window(arr)
assert window == Window.from_slices((1, 3), (0, 3))
示例9: test_window_fromslices_negative_start
def test_window_fromslices_negative_start():
# TODO: if passing negative start, what are valid values for stop?
assert np.allclose(
Window.from_slices(rows=(-4, None), cols=(0, 4), height=10).flatten(),
(0, 6, 4, 4)
)
assert np.allclose(
Window.from_slices(rows=(0, 4), cols=(-4, None), width=10).flatten(),
(6, 0, 4, 4)
)
assert np.allclose(
Window.from_slices(rows=(-6, None), cols=(-4, None),
height=8, width=10).flatten(),
(6, 2, 4, 6)
)
示例10: test_window_fromslices_implicit
def test_window_fromslices_implicit(abs_off, imp_off, stop, dim):
""" providing None for start index will default to 0
and providing None for stop index will default to width or height """
assume(stop >= abs_off)
assume(dim >= imp_off)
absolute = (abs_off, stop)
implicit_start = (None, stop) # => (0, stop)
implicit_stop = (imp_off, None) # => (implicit_offset, dim)
implicit_both = (None, None) # => (implicit_offset, dim)
# Implicit start indexes resolve to 0
assert np.allclose(
Window.from_slices(rows=implicit_start, cols=absolute).flatten(),
(abs_off, 0, stop - abs_off, stop)
)
assert np.allclose(
Window.from_slices(rows=absolute, cols=implicit_start).flatten(),
(0, abs_off, stop, stop - abs_off)
)
# Implicit stop indexes resolve to dim (height or width)
assert np.allclose(
Window.from_slices(
rows=implicit_stop, cols=absolute, height=dim).flatten(),
(abs_off, imp_off, stop - abs_off, dim - imp_off)
)
assert np.allclose(
Window.from_slices(
rows=absolute, cols=implicit_stop, width=dim).flatten(),
(imp_off, abs_off, dim - imp_off, stop - abs_off)
)
# Both can be implicit
assert np.allclose(
Window.from_slices(
rows=implicit_both, cols=implicit_both,
width=dim, height=dim).flatten(),
(0, 0, dim, dim)
)
示例11: test_window_float
def test_window_float(path_rgb_byte_tif):
"""Test window float values"""
with rasterio.open(path_rgb_byte_tif) as src:
left, bottom, right, top = src.bounds
dx, dy = src.res
height = src.height
width = src.width
assert_window_almost_equals(from_bounds(
left, top - 400, left + 400, top, src.transform,
height, width), Window.from_slices((0, 400 / src.res[1]), (0, 400 / src.res[0])))
示例12: test_window_fromslices_boundless
def test_window_fromslices_boundless(col_off, row_off, col_stop, row_stop):
# Constrain windows to >= 0 in each dimension
assume(col_stop >= col_off)
assume(row_stop >= row_off)
assert np.allclose(
Window.from_slices(
rows=(-row_off, row_stop), cols=(col_off, col_stop),
boundless=True).flatten(),
(col_off, -row_off, col_stop - col_off, row_stop + row_off)
)
示例13: clip
def clip(indir, chip_csv, outdir,
image_pattern, chip_pattern, shape, driver):
""" Output image chips listed in a CSV file
\b
CSV file expects the following columns:
* idx (int): index of the chip
* name (str): name of chip land cover
* x (float): upper left X coordinate of chip
* y (float): upper left Y coordinate of chip
"""
# Handle 1 or 2 inputs
if not len(shape):
shape = None
else:
shape = (shape[0], shape[0]) if len(shape) == 1 else shape
indir, chip_csv, outdir = Path(indir), Path(chip_csv), Path(outdir)
outdir.mkdir(parents=True, exist_ok=True)
# Chip info
chips = pd.read_csv(chip_csv)
# Input images
images = list(indir.glob(image_pattern))
for chip in chips.itertuples():
_chip = dict(zip(chip._fields, chip))
_chip['Index'] += 1 # index on 1
for image in images:
# Format output filename
_chip['input'] = image.name
out_image = outdir.joinpath(chip_pattern.format(**_chip))
# Make sure output directory exists
out_image.parent.mkdir(parents=True, exist_ok=True)
with rasterio.open(str(image)) as src:
# Formulate chip bounds
col, row = map(int, ~src.transform * (chip.x, chip.y))
window = Window.from_offlen(col, row, shape[0], shape[1])
# Form output kwargs
out_kwargs = src.meta.copy()
out_kwargs['driver'] = driver
out_kwargs['width'] = shape[0]
out_kwargs['height'] = shape[1]
out_kwargs['transform'] = src.window_transform(window)
click.echo('Writing output for image: {}'
.format(out_image.name))
with rasterio.open(str(out_image), 'w', **out_kwargs) as dst:
dst.write(src.read(window=window))
示例14: test_window_from_bounds
def test_window_from_bounds(path_rgb_byte_tif):
# TODO: break this test up.
with rasterio.open(path_rgb_byte_tif) as src:
left, bottom, right, top = src.bounds
dx, dy = src.res
height = src.height
width = src.width
assert_window_almost_equals(from_bounds(
left + EPS, bottom + EPS, right - EPS, top - EPS, src.transform,
height, width), Window.from_slices((0, height), (0, width)))
assert_window_almost_equals(from_bounds(
left, top - 2 * dy - EPS, left + 2 * dx - EPS, top, src.transform,
height, width), Window.from_slices((0, 2), (0, 2)))
# boundless
assert_window_almost_equals(
from_bounds(left - 2 * dx, top - 2 * dy, left + 2 * dx,
top + 2 * dy, src.transform, height=height,
width=width),
Window.from_slices((-2, 2), (-2, 2), boundless=True, height=height,
width=width))
示例15: process_tile
def process_tile(tile):
"""Process a single MBTiles tile
Parameters
----------
tile : mercantile.Tile
Returns
-------
tile : mercantile.Tile
The input tile.
bytes : bytearray
Image bytes corresponding to the tile.
"""
global base_kwds, resampling, src
# Get the bounds of the tile.
ulx, uly = mercantile.xy(
*mercantile.ul(tile.x, tile.y, tile.z))
lrx, lry = mercantile.xy(
*mercantile.ul(tile.x + 1, tile.y + 1, tile.z))
kwds = base_kwds.copy()
kwds['transform'] = transform_from_bounds(ulx, lry, lrx, uly,
kwds['width'], kwds['height'])
src_nodata = kwds.pop('src_nodata', None)
dst_nodata = kwds.pop('dst_nodata', None)
warnings.simplefilter('ignore')
with MemoryFile() as memfile:
with memfile.open(**kwds) as tmp:
# determine window of source raster corresponding to the tile
# image, with small buffer at edges
try:
west, south, east, north = transform_bounds(TILES_CRS, src.crs, ulx, lry, lrx, uly)
tile_window = window_from_bounds(west, south, east, north, transform=src.transform)
adjusted_tile_window = Window(
tile_window.col_off - 1, tile_window.row_off - 1,
tile_window.width + 2, tile_window.height + 2)
tile_window = adjusted_tile_window.round_offsets().round_shape()
# if no data in window, skip processing the tile
if not src.read_masks(1, window=tile_window).any():
return tile, None
except ValueError:
log.info("Tile %r will not be skipped, even if empty. This is harmless.", tile)
reproject(rasterio.band(src, tmp.indexes),
rasterio.band(tmp, tmp.indexes),
src_nodata=src_nodata,
dst_nodata=dst_nodata,
num_threads=1,
resampling=resampling)
return tile, memfile.read()