Google Earth Engine NDVI – Filtering Specific Range of Values

filtergoogle-earth-enginendvi

I have this script that creates a composite image From Sentinel-2 in GEE and filters it for date and ROI:

/* Import Sentinel-2 imagery and mask clouds using the Sentinel-2 QA band */
function maskS2clouds(COPERNICUS/S2_SR) {
  var qa = S2L2A.select('QA60');

  var cloudBitMask = 1 << 10;
  var cirrusBitMask = 1 << 11;

  var mask = qa.bitwiseAnd(cloudBitMask).eq(0)
      .and(qa.bitwiseAnd(cirrusBitMask).eq(0));

  return S2L2A.updateMask(mask).divide(10000);
}        
 
var S2_Spring= ee.ImageCollection(COPERNICUS/S2_SR)
                  .filterDate('2022-05-01', '2022-08-31')
                  // Pre-filter to get less cloudy granules.
                  .filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE',5))
                  .map(maskS2clouds)
                  .filterBounds(Region_Border)
                  .map(function(image){return image.clip(Region_Border)});
                  
var visualization = {
 min: 0.0,
 max: 0.3,
 bands: ['B4', 'B3', 'B2'],
};

After, I calculate NDVI and add it to the collection as a band:

var addNDVI = function(COPERNICUS/S2_SR) {
  var ndvi = S2L2A.normalizedDifference(['B8', 'B4']).rename('NDVI');
  return S2L2A.addBands(ndvi);
};

var S2_Spring = S2_Spring.map(addNDVI);

Finaly, I select the desired bands and create a composite:

var S2_Spring = ee.ImageCollection(S2_Spring.select(["B2", "B3", "B4","B8","NDVI", "NDWI","B5", "B6", "B7","B8A","B11", "B12"] ,["Sp_B2", "Sp_B3", "Sp_B4","Sp_B8","Sp_NDVI", "Sp_NDWI","Sp_B5", "Sp_B6", "Sp_B7","Sp_B8A","Sp_B11","Sp_B12"]));

var S2_Spring_Composite = S2_Spring.mosaic();

Then, I use it for supervised classification in GEE. I need to minimize my error in classification, so I decided to use a filter to mask out areas that are not useful for classification.
Is it possible to calculate NDVI over the final composite image 'S2_Spring_Composite' and filter it for a specific range? For example, find and deleted NDVI values less than 0 and more than 0.2?

Best Answer

You can use updateMask to mask the values you indicate. You just need to define a mask of the NDVI values you wish to retain in the image and apply it to your image.

// Create a mask with the values you wish to retain
var maskIm = S2_Spring_Composite.select('Sp_NDVI').gte(0)
                                .and(S2_Spring_Composite.select('Sp_NDVI').lte(0.2));

// Masked image
var maskedIm = S2_Spring_Composite.updateMask(maskIm);
Related Question