Skip to content

titan.rio_utils

Utility functions to make it easier to work with rasterio in python.

block_windows(width, height, blockxsize=BLOCKSIZE, blockysize=BLOCKSIZE)

Returns a tuple of iterables with custom window sizes for block-based read/write.

Designed to be used as a custom block size implementation of rasterio's src.block_windows().

Parameters:

Name Type Description Default
width int

the raster width (xsize) in pixels.

required
height int

the raster height (ysize) in pixels.

required
blockxsize int

the size of the x (column) dimension to read per block.

BLOCKSIZE
blockysize int

the size of the y (row) dimension to read per block.

BLOCKSIZE

Returns:

Name Type Description
iter idxs, windows

an iterable with a tuple of block indexes ((0, 0), (0, 1) ... ) and Windows (Window(col_off=0, row_off=0, width=blockxsize, height=blockysize), ... ).

Source code in titan/rio_utils.py
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
def block_windows(width: int, height: int, blockxsize: int = BLOCKSIZE, blockysize: int = BLOCKSIZE) -> iter:
    """Returns a tuple of iterables with custom window sizes for block-based read/write.

    Designed to be used as a custom block size implementation of rasterio's `src.block_windows()`.

    Args:
        width: the raster width (xsize) in pixels.
        height: the raster height (ysize) in pixels.
        blockxsize: the size of the x (column) dimension to read per block.
        blockysize: the size of the y (row) dimension to read per block.

    Returns:
        iter(idxs, windows): an iterable with a tuple of block indexes ((0, 0), (0, 1) ... )
            and Windows (Window(col_off=0, row_off=0, width=blockxsize, height=blockysize), ... ).
    """

    # check to see if the blocks are perfect fits for the extent. if not, use custom tile boundary blocks
    xmod = width % blockxsize
    ymod = height % blockysize
    perfectx = xmod == 0
    perfecty = ymod == 0

    # get the total number of blocks to set
    n_xblocks = int(np.ceil(width / blockxsize))
    n_yblocks = int(np.ceil(height / blockysize))
    xblocks = range(n_xblocks)
    yblocks = range(n_yblocks)

    # iterate over each row/col tile combination to create the output idx, window iterator
    windows = []
    for yblock in yblocks:
        for xblock in xblocks:
            idx = (yblock, xblock)
            xoff = blockxsize * xblock
            yoff = blockysize * yblock

            window_width = blockxsize if (xblock != xblocks[-1] or perfectx) else xmod
            window_height = blockysize if (yblock != yblocks[-1] or perfecty) else ymod

            window = rio.windows.Window(xoff, yoff, window_width, window_height)
            windows.append((idx, window))

    return iter(windows)