0

I'm using reduceRegion to sum the number of water pixels determined by an NDWI. I want to do this on a collection of images to see change in water area over a period time.

The values are returned from the reduceRegion in the console and appear to be integers, but I am unable to extract them as such. This seems to be a common problem, but the solution is typically using getInfo function to bring these values over to client side. Unfortunately getInfo returns a null in this case.

The code below is for a collection of images OR a single image. The single image(image1) returns an image with an extra property(waterArea), and the mapped algorithm blows up(because the function is returning nulls).

I've also tried using getInfo on waterAg to potentially bring that list over to client side, however that returns the same List of objects that I don't want.

var image1 = ee.Image(leastcloud.first()).select(['B11','B8','B3'])

var stackarea = function(image){

  var watermask = ee.Image(0)

  var MNDWI = image.normalizedDifference(['B3','B11'])
  watermask = watermask.where(MNDWI.gt(.31),1);


             //sum of water pixels in an area
  var sum = ee.Number(watermask.reduceRegion({
  reducer: ee.Reducer.sum(),
  geometry: geometry,
  scale: 20,
  maxPixels: 1e9
  }));

  var clientSide = sum.getInfo()
  var setArea = image.set('waterArea', clientSide)
  return setArea

};

var single = stackarea(image1)
print(single)

var watermapped = filterSpot.map(stackarea)
var waterAg = watermapped.aggregate_array('waterArea')
print(waterAg)

I'm really not sure how to extract these values as numbers...

I'm hoping to get a list of numbers so that I can concatenate that array to other arrays(date of image, cloud pixel %, etc.)

joel
  • 1
  • 1
  • 2

1 Answers1

0

reduceRegion returns a dictionary object, not a number-like object. Therefore, in your stackarea function, clientSide variable is a dictionary (i.e. an object), not a number.

The number that you're after is stored in the dictionary returned by the reduceRegion function. You can get your hand on that number by using a get function on this dictionary object:

  var sum = watermask.reduceRegion({
  reducer: ee.Reducer.sum(),
  geometry: geometry,
  scale: 20,
  maxPixels: 1e9
  }).get('nd');

In this way, sum will be a server-side number that store the value you're after (There's no need to use ee.Number here as it does not help much).

In case you wonder about why using get('nd') but not get('somethingelse'), well it's the name of the band in your watermask image, and this name is the default band name given to the result of the normalizedDifference function.

And in my opinion, you don't even need to use the getInfo function which takes much more time to execute. Just delete the line var clientSide = sum.getInfo() and modify the next line into var setArea = image.set('waterArea', sum).

Hope this help.

Kevin
  • 338
  • 1
  • 3
  • 9