⚠️ Our 0.1 release refactored several early-development functions for long-term stability, to update your code see here. ⚠️
Future changes will come with deprecation warnings! 🙂

Polygonize a raster

Polygonize a raster#

This example demonstrates the polygonizing of a raster using geoutils.Raster.polygonize() and geoutils.Mask.polygonize().

We open a raster.

import geoutils as gu

filename_rast = gu.examples.get_path("exploradores_aster_dem")
rast = gu.Raster(filename_rast)
rast.crop([rast.bounds.left, rast.bounds.bottom, rast.bounds.left + 5000, rast.bounds.bottom + 5000])
Raster(
  data=[[3889.968994140625 3886.230712890625 3877.96533203125 ...
         1853.031005859375 1852.1669921875 1852.843017578125]
        [3899.0419921875 3895.246337890625 3886.021240234375 ...
         1858.28369140625 1854.7979736328125 1856.1204833984375]
        [3904.080322265625 3901.120361328125 3893.490478515625 ...
         1867.3121337890625 1860.0323486328125 1863.2193603515625]
        ...
        [2690.725830078125 2695.724609375 2700.945556640625 ... 1925.1962890625
         1907.0738525390625 1897.7000732421875]
        [2688.682373046875 2693.766845703125 2697.1826171875 ...
         1900.9295654296875 1884.9849853515625 1875.97314453125]
        [2686.294677734375 2692.3466796875 2694.712890625 ... 1883.2508544921875
         1868.762451171875 1859.6497802734375]]
  transform=| 30.00, 0.00, 627175.00|
            | 0.00,-30.00, 4838555.00|
            | 0.00, 0.00, 1.00|
  crs=EPSG:32718
  nodata=-9999.0)


Let’s plot the raster.

rast.plot(cmap="terrain")
polygonize

We polygonize the raster.

polygonize

By default, polygonize() will try to polygonize target all valid values. Instead, one can specify discrete values to target by passing a number or list, or a range of values by passing a tuple.

# A range of values to polygonize
rast_polygonized = rast.polygonize((2500, 3000))
rast_polygonized.plot(ax="new")
polygonize

An even simpler way to do this is to compute a Mask() to polygonize using logical comparisons on the Raster().

rast_polygonized = ((2500 < rast) & (rast < 3000)).polygonize()
rast_polygonized.plot(ax="new")
polygonize

Note

See Support of pythonic operators for more details on casting to Mask().

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

Gallery generated by Sphinx-Gallery