xrspatial.zonal.trim

xrspatial.zonal.trim(raster: xarray.core.dataarray.DataArray, values: Union[list, tuple] = (nan,), name: str = 'trim') xarray.core.dataarray.DataArray[source]

Trim scans from the edges and eliminates rows / cols which only contain the values supplied.

Parameters
  • raster (xr.DataArray) –

  • values (list or tuple, default=(np.nan)) – List of zone ids to trim from raster edge.

  • name (str, default='trim') – Output xr.DataArray.name property.

Returns

trim_agg

Return type

xarray.DataArray

Notes

  • This operation will change the output size of the raster.

Examples

import matplotlib.pyplot as plt
import numpy as np
import xarray as xr

from xrspatial import generate_terrain
from xrspatial.zonal import trim

# Generate Example Terrain
W = 500
H = 300

template_terrain = xr.DataArray(np.zeros((H, W)))
x_range=(-20e6, 20e6)
y_range=(-20e6, 20e6)

terrain_agg = generate_terrain(
    template_terrain, x_range=x_range, y_range=y_range
)

# Edit Attributes
terrain_agg = terrain_agg.assign_attrs(
    {
        'Description': 'Example Terrain',
        'units': 'km',
        'Max Elevation': '4000',
    }
)

terrain_agg = terrain_agg.rename({'x': 'lon', 'y': 'lat'})
terrain_agg = terrain_agg.rename('Elevation')
terrain_agg = terrain_agg.astype('int')

# Trim Image
trimmed_agg = trim(raster = terrain_agg, values = [0])

# Edit Attributes
trimmed_agg = trimmed_agg.assign_attrs({'Description': 'Example Trim'})

# Plot Terrain
terrain_agg.plot(cmap = 'terrain', aspect = 2, size = 4)
plt.title("Terrain")
plt.ylabel("latitude")
plt.xlabel("longitude")

# Plot Trimmed Terrain
trimmed_agg.plot(cmap = 'terrain', aspect = 2, size = 4)
plt.title("Trim")
plt.ylabel("latitude")
plt.xlabel("longitude")
../../_images/xrspatial-zonal-trim-1_00.png

(png, hires.png, pdf)

../../_images/xrspatial-zonal-trim-1_01.png

(png, hires.png, pdf)

>>> print(terrain_agg.shape)
(300, 500)

>>> print(terrain_agg.attrs)
{
    'res': (80000.0, 133333.3333333333),
    'Description': 'Example Terrain',
    'units': 'km',
    'Max Elevation': '4000',
}

>>> print(trimmed_agg.shape)
(268, 500)

>>> print(trimmed_agg.attrs)
{
    'res': (80000.0, 133333.3333333333),
    'Description': 'Example Trim',
    'units': 'km',
    'Max Elevation': '4000',
}