Python arithmetic

Python arithmetic#

This example demonstrates arithmetic operations using raster arithmetic on xarray.DataArray objects with the rst accessor. See Python operators for more details.

We open a raster

import geoutils as gu

filename_rast = gu.examples.get_path("everest_landsat_b4")
rast = gu.open_raster(filename_rast)
rast
<xarray.DataArray (y: 655, x: 800)> Size: 2MB
[524000 values with dtype=float32]
Coordinates:
  * y            (y) float64 5kB 3.108e+06 3.108e+06 ... 3.089e+06 3.089e+06
  * x            (x) float64 6kB 4.78e+05 4.78e+05 ... 5.02e+05 5.02e+05
    band         int64 8B 1
    spatial_ref  int64 8B 0
Attributes:
    AREA_OR_POINT:             Point
    scale_factor:              1.0
    add_offset:                0.0
    overview_factors:          []
    overview_selected_level:   -1
    overview_selected_factor:  1
    block_shape:               (10, 800)


rast.rst.plot(cmap="Greys_r")
python arithmetic

Performing arithmetic operations implicitly loads the data.

rast = (rast + 1.0) ** 0.5 / 5
rast.rst.plot(cmap="Greys_r")
python arithmetic

Important

Arithmetic operations cast to new dtypes automatically following Xarray and NumPy coercion rules.

Logical comparison operations will naturally return a boolean xarray.DataArray.

mask = rast == 200
mask
<xarray.DataArray (y: 655, x: 800)> Size: 524kB
array([[False, False, False, ..., False, False, False],
       [False, False, False, ..., False, False, False],
       [False, False, False, ..., False, False, False],
       ...,
       [False, False, False, ..., False, False, False],
       [False, False, False, ..., False, False, False],
       [False, False, False, ..., False, False, False]], shape=(655, 800))
Coordinates:
  * y            (y) float64 5kB 3.108e+06 3.108e+06 ... 3.089e+06 3.089e+06
  * x            (x) float64 6kB 4.78e+05 4.78e+05 ... 5.02e+05 5.02e+05
    band         int64 8B 1
    spatial_ref  int64 8B 0
Attributes:
    AREA_OR_POINT:             Point
    scale_factor:              1.0
    add_offset:                0.0
    overview_factors:          []
    overview_selected_level:   -1
    overview_selected_factor:  1
    block_shape:               (10, 800)


Boolean xarray.DataArray objects support Python logical operators to be combined together.

mask = (rast >= 3) | (rast % 2 == 0) & (rast != 80)
mask.rst.plot()
python arithmetic

Finally, boolean rasters can be used for selecting values from a raster.

Total running time of the script: (0 minutes 1.917 seconds)

Gallery generated by Sphinx-Gallery