1

I have a raster layer (based on Landsat (30x30m)) of newly emergent lakes after spring snowmelt and subsequent runoff. These are stored in a raster layer. When I look at it, there is a lot of noise (single pixels) everywhere. The raster specs are:

class       : SpatRaster 
dimensions  : 20191, 51818, 1  (nrow, ncol, nlyr)
resolution  : 0.0002694946, 0.0002694946  (x, y)
extent      : -122.5147, -108.55, 59.38906, 64.83043  (xmin, xmax, ymin, ymax)
coord. ref. : lon/lat WGS 84 (EPSG:4326) 
source      : dNBR14_02.tif 
name        : lakes 
min value   :   0
max value   :   2

I want to delete pixels based on their area and not the values! This means deleting all pixels that cover an area of fewer than two pixels.

image

I am using R.

library(terra)

lakes = rast('path/lakes.tif')
condition = extent < 2 pixels #How can I set an condition for my masking?
x = mask(lakes, condition, inverse = T)

2 Answers 2

5

Here is the recommendation on a sieve approach from terra's help. You can use the patches, zonal and ifel functions to remove pixels base on a criteria such as minimum size.

Read in some data and classify so there are some isolated patches.

library(terra)
r <- rast(system.file("ex/elev.tif", package="terra"))
  r <- classify(r, cbind(-Inf, 400, NA))

Remove patches smaller than 100 ha

y <- patches(r)
rz <- zonal(cellSize(y, unit="ha"), y, sum, as.raster=TRUE)
  s <- ifel(rz < 100, NA, y)
    plot(c(r,s))
0

This Python utility is made for that purpose https://gdal.org/programs/gdal_sieve.html

gdal_sieve.py script removes raster polygons smaller than a provided threshold size (in pixels) and replaces them with the pixel value of the largest neighbour polygon. The result can be written back to the existing raster band, or copied into a new file.

The Python source code is in GitHub https://github.com/OSGeo/gdal/blob/master/swig/python/gdal-utils/osgeo_utils/gdal_sieve.py. Perhaps you can adapt it for R.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.