• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python windows.Window类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中rasterio.windows.Window的典型用法代码示例。如果您正苦于以下问题:Python Window类的具体用法?Python Window怎么用?Python Window使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Window类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
    )
开发者ID:mwtoews,项目名称:rasterio,代码行数:26,代码来源:test_windows.py


示例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))
开发者ID:mwtoews,项目名称:rasterio,代码行数:8,代码来源:test_windows.py


示例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
开发者ID:ceholden,项目名称:rasterio,代码行数:8,代码来源:test_windows.py


示例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))
开发者ID:mwtoews,项目名称:rasterio,代码行数:9,代码来源:test_windows.py


示例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)
    )
开发者ID:mwtoews,项目名称:rasterio,代码行数:11,代码来源:test_windows.py


示例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)
    )
开发者ID:mwtoews,项目名称:rasterio,代码行数:13,代码来源:test_windows.py


示例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)
开发者ID:mwtoews,项目名称:rasterio,代码行数:16,代码来源:test_windows.py


示例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))
开发者ID:mwtoews,项目名称:rasterio,代码行数:7,代码来源:test_windows.py


示例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)
    )
开发者ID:mwtoews,项目名称:rasterio,代码行数:17,代码来源:test_windows.py


示例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)
    )
开发者ID:mwtoews,项目名称:rasterio,代码行数:43,代码来源:test_windows.py


示例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])))
开发者ID:mwtoews,项目名称:rasterio,代码行数:11,代码来源:test_windows.py


示例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)
    )
开发者ID:mwtoews,项目名称:rasterio,代码行数:12,代码来源:test_windows.py


示例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))
开发者ID:ceholden,项目名称:misc,代码行数:53,代码来源:extract_chips.py


示例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))
开发者ID:mwtoews,项目名称:rasterio,代码行数:23,代码来源:test_windows.py


示例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()
开发者ID:mapbox,项目名称:rio-mbtiles,代码行数:61,代码来源:__init__.py


示例16: geometry_window

def geometry_window(dataset, shapes, pad_x=0, pad_y=0, north_up=True,
                    rotated=False, pixel_precision=3):
    """Calculate the window within the raster that fits the bounds of the
    geometry plus optional padding.  The window is the outermost pixel indices
    that contain the geometry (floor of offsets, ceiling of width and height).

    If shapes do not overlap raster, a WindowError is raised.

    Parameters
    ----------
    dataset: dataset object opened in 'r' mode
        Raster for which the mask will be created.
    shapes: iterable over geometries.
        A geometry is a GeoJSON-like object or implements the geo interface.
        Must be in same coordinate system as dataset.
    pad_x: float
        Amount of padding (as fraction of raster's x pixel size) to add to left
        and right side of bounds.
    pad_y: float
        Amount of padding (as fraction of raster's y pixel size) to add to top
        and bottom of bounds.
    north_up: bool
        If True (default), the origin point of the raster's transform is the
        northernmost point and y pixel values are negative.
    rotated: bool
        If true, some rotation terms exist in the dataset transform (this
        requires special attention.)
    pixel_precision: int
        Number of places of rounding precision for evaluating bounds of shapes.

    Returns
    -------
    window: rasterio.windows.Window instance
    """

    if pad_x:
        pad_x = abs(pad_x * dataset.res[0])

    if pad_y:
        pad_y = abs(pad_y * dataset.res[1])

    if not rotated:
        all_bounds = [bounds(shape, north_up=north_up) for shape in shapes]
        lefts, bottoms, rights, tops = zip(*all_bounds)

        left = min(lefts) - pad_x
        right = max(rights) + pad_x

        if north_up:
            bottom = min(bottoms) - pad_y
            top = max(tops) + pad_y
        else:
            bottom = max(bottoms) + pad_y
            top = min(tops) - pad_y
    else:
        # get the bounds in the pixel domain by specifying a transform to the bounds function
        all_bounds_px = [bounds(shape, transform=~dataset.transform) for shape in shapes]
        # get left, right, top, and bottom as above
        lefts, bottoms, rights, tops = zip(*all_bounds_px)
        left = min(lefts) - pad_x
        right = max(rights) + pad_x
        top = min(tops) - pad_y
        bottom = max(bottoms) + pad_y
        # do some clamping if there are any values less than zero or greater than dataset shape
        left = max(0, left)
        top = max(0, top)
        right = min(dataset.shape[1], right)
        bottom = min(dataset.shape[0], bottom)
        # convert the bounds back to the CRS domain
        left, top = (left, top) * dataset.transform
        right, bottom = (right, bottom) * dataset.transform

    window = dataset.window(left, bottom, right, top)
    window_floored = window.round_offsets(op='floor', pixel_precision=pixel_precision)
    w = math.ceil(window.width + window.col_off - window_floored.col_off)
    h = math.ceil(window.height + window.row_off - window_floored.row_off)
    window = Window(window_floored.col_off, window_floored.row_off, w, h)

    # Make sure that window overlaps raster
    raster_window = Window(0, 0, dataset.width, dataset.height)

    # This will raise a WindowError if windows do not overlap
    window = window.intersection(raster_window)

    return window
开发者ID:DanLipsitt,项目名称:rasterio,代码行数:85,代码来源:features.py


示例17: test_round_window_already_at_edge

def test_round_window_already_at_edge(path_alpha_tif):
    with rasterio.open(path_alpha_tif) as src:
        block_shapes = src.block_shapes
        test_window = ((256, 512), (512, 768))
        rounded_window = round_window_to_full_blocks(test_window, block_shapes)
        assert rounded_window == Window.from_slices(*test_window)
开发者ID:mwtoews,项目名称:rasterio,代码行数:6,代码来源:test_windows.py


示例18: test_intersection

def test_intersection():
    """Window intersection works."""
    window = intersection(Window(0, 0, 10, 10), Window(8, 8, 12, 12))
    assert window == Window.from_slices((8, 10), (8, 10))
开发者ID:mwtoews,项目名称:rasterio,代码行数:4,代码来源:test_windows.py


示例19: test_window_union

def test_window_union():
    """Window union works."""
    window = union(Window(0, 0, 1, 1), Window(1, 1, 2, 2))
    assert window == Window.from_slices((0, 3), (0, 3))
开发者ID:mwtoews,项目名称:rasterio,代码行数:4,代码来源:test_windows.py


示例20: test_data_window_nodata_3d

def test_data_window_nodata_3d():
    """Get window of 3d arr with nodata."""
    arr = np.ones((3, 3, 3))
    arr[:, 0, :] = 0
    window = get_data_window(arr, nodata=0)
    assert window == Window.from_slices((1, 3), (0, 3))
开发者ID:mwtoews,项目名称:rasterio,代码行数:6,代码来源:test_windows.py



注:本文中的rasterio.windows.Window类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python rasterstats.raster_stats函数代码示例发布时间:2022-05-26
下一篇:
Python warp.transform_geom函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap