0

I'm trying to count the number of water pixels across a Landsat 5 image collection. I have a script which I believe is successful in identifying the water pixels in each image and spiting a chart with each pixel identified (see below). I'd like to sum the number of mndwi pixels in the collection, but every time I try different reducers it only gives me a band, when I'd like a value. What do I need to do?

Here is the relevant part of my script:

//modNDWI (modified Normalized Difference Water Index)
//MNDWI = (GREEN − SWIR)/(GREEN + SWIR)
var mndwi = function(image) {
  var fun_mndwi = ee.Image(0).expression(
    '((B2 - B5) / (B2 + B5))', {
      'B2': image.select('B2'),
      'B5': image.select('B5'),
    });
  return image.addBands(fun_mndwi.rename('mndwi'));
};

////////////////////////////////

// Add a Function which removes pixels
var h2opixel = function(image) {
var maskpixel = image.select('mndwi').gt(-0.1);
  return image.mask(maskpixel);
};

////Map function over image collection
var collection_mndwi = lsat5masked.map(mndwi)
  .select('mndwi');//now only 1 banded images
Map.addLayer(collection_mndwi, mndwiParams,'collection_mndwi');//applied index
var FinalDataset = collection_mndwi.map(h2opixel);//filtered by -0.1
Map.addLayer(FinalDataset,mndwiParams,'final datset');

print(FinalDataset);
///////////////////////

///This is what won't work they way I'd like:

//count total number of pixels 
var count3 = FinalDataset.reduce({
  reducer: ee.Reducer.count()
  });
print(count3);```

1 Answer 1

0

To get the sum of some pixels in a region of an image you need to use .reduceRegion(). See here for the documentation.

So in your case if you want to calculate the number of water pixels for each Image in the Collection you would map over the collection and apply .reduceRegion() to each image.

//count total number of pixels 
var water_sums = FinalDataset.map(function(image){
  var reduced = image.reduceRegion({
    reducer: ee.Reducer.sum(),
    geometry: geometry, // NEEDS TO BE CREATED
    scale: 30
  })
  return ee.Feature(null, reduced)
})

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.