Google Earth Engine – Resolving Issues with the updateMask Function in JavaScript

google-earth-enginejavascriptmasking

I'm trying to use the updateMask function in GEE but I'm not quite sure how to use it in this occasion. So i did a trend analysis with formaTrend() to analyze the loss of forest cover in an area:

  var aoi = ee.Geometry.MultiPolygon([
  [6.753654920661802,49.98597828191218],
  [6.7461018200758645,49.902020897367365],
  [6.941795789802427,49.897598033936816],
  [6.945915662849302,49.99083449205881],
  [6.753654920661802,49.994807390209445],
  [6.753654920661802,49.98597828191218]]);


var addVI = function(image) {
  image = image.addBands(image.normalizedDifference(['B4', 'B3']).rename('NDVI'));
  return image;
}

var coll = ee.ImageCollection('LANDSAT/LT05/C01/T1_TOA')
  .filterDate('1995-01-01', '1995-12-30') // Zeitraum vor den Sturmereignissen
  .filterBounds(aoi)
  .filter(ee.Filter.lte('CLOUD_COVER', 4))
  .sort('DATE_ACQUIRED')// Collection sortiert nach Cloudcover


var coll2 = ee.ImageCollection('LANDSAT/LT05/C01/T1_TOA')
  .filterDate('1996-01-01', '1996-12-30') // Zeitraum vor den Sturmereignissen
  .filterBounds(aoi)
  .filter(ee.Filter.lte('CLOUD_COVER', 8))
  .sort('DATE_ACQUIRED')

print(coll, coll2);

var collection = coll.merge(coll2);
collection = collection.map(addVI);

// Forma Trend
var ndvistack = collection.select('NDVI');

var trend = ndvistack.formaTrend();
var ltTrend = trend.select(['long-trend']).clip(aoi);

var loss = ltTrend.mask(ltTrend.lt(0));

Map.addLayer(loss, {color: 'red'}, 'Loss');

var img = collection.median();

// img = img.updateMask(loss); doesnt work ):

After I figured out the areas which are affected by loss (stored in there variable "loss"). Now i want to calculate another vegeatation index exclusively on the areas where the algorithm detected a loss.

I tried using the updateMask() function like this:

img = img.updateMask(loss);

but i think i'm missing something, which i can't find out.
Is there a way to use the loss variable as a mask for other images?

Best Answer

Masking should be done on images with zeros and ones. You just have to update the mask as you did previously when obtaining the loss image. A less than or greater than expression are generally used for the input of updateMask.

var masked = img.updateMask(ltTrend.lt(0)); 

Here is how I adapted your code and added the masked and unmasked median composites to the map.

Related Question