xrspatial.zonal.crop

xrspatial.zonal.crop(zones: xarray.core.dataarray.DataArray, values: xarray.core.dataarray.DataArray, zones_ids: Union[list, tuple], name: str = 'crop')[source]

Crop scans from edges and eliminates rows / cols until one of the input values is found.

Parameters
  • zones (xr.DataArray) – Input zone raster.

  • values (xr.DataArray) – Input values raster.

  • zones_ids (list or tuple) – List of zone ids to crop raster.

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

Returns

crop_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 crop

# 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')

# Crop Image
values_agg = terrain_agg[0:300, 0:250]
cropped_agg = crop(
    zones=terrain_agg,
    values=values_agg,
    zones_ids=[0],
)

# Edit Attributes
cropped_agg = cropped_agg.assign_attrs({'Description': 'Example Crop'})

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

# Plot Cropped Terrain
cropped_agg.plot(cmap = 'terrain', aspect = 2, size = 4)
plt.title("Crop")
plt.ylabel("latitude")
plt.xlabel("longitude")
../../_images/xrspatial-zonal-crop-1_00.png

(png, hires.png, pdf)

../../_images/xrspatial-zonal-crop-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(cropped_agg.shape)
(300, 250)

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