I am working on Sentinel -2 image collection over my study region in Google Earth Engine. I can calculate Mean NDVI for an image using ee.Reducer.mean() and mask pixels using update mask .gt(mean value number). Now I want to do this to each image of the collection. Since mean NDVI value of each image will be different I am facing difficulty to use .map function.I attempted this but I think I have got it all wrong and now I am stuck. How can I iterate it to each image in image collection?
/////////////Sentinel-2 Burned Area Detection/////////////////////////////////////
////Get image collection with specified cloud percentage threshold.
var s2= ee.ImageCollection("COPERNICUS/S2_SR").filter(ee.Filter.lt("CLOUDY_PIXEL_PERCENTAGE", 10));
var admin2 = ee.FeatureCollection("FAO/GAUL_SIMPLIFIED_500m/2015/level2");
var Bhopal = admin2.filter(ee.Filter.eq('ADM2_NAME', 'Bhopal'))
var geometry = Bhopal.geometry()
////vis parameters.
var vis = {bands: ['B4', 'B3', 'B2'], max: 2000, gamma: 1.5};
////print fire occurance.
// print(ee.String('Fire incident occurred between ').cat(fire_start).cat(' and ').cat(fire_end));
////Define Study area
var area = ee.FeatureCollection(geometry);
var opacity = 0.5; // number [0-1]
Map.centerObject(area, 6.5);
////Filter Dates for rabi season
/////March
var fireImColA1 = ee.ImageCollection(s2.filterDate('2019-03-01', '2019-03-07') //// Filter by dates.
.filterBounds(area));
//// Creat a Cloud Mask.
function maskS2sr(image) {
var cloudBitMask = ee.Number(2).pow(10).int(); ////cloud band
var cirrusBitMask = ee.Number(2).pow(11).int();//// cirrus band
var qa = image.select('QA60'); //// Get the pixel QA band.
var mask = qa.bitwiseAnd(cloudBitMask).eq(0) //// Flags set to zero for clear conditions.
.and(qa.bitwiseAnd(cirrusBitMask).eq(0)); //// Flags set to zero for clear conditions.
return image.updateMask(mask) //// Return the masked image, scaled to TOA reflectance, without the QA bands.
.copyProperties(image, ["system:time_start"]);
}
//// Apply cloud mask to pre and post fire image collections
/////March
var fire_CM_ImColA1 = fireImColA1.map(maskS2sr);
///Function add NDVI band to image collection
var addNDVI = function(image) {
return image.addBands(image.normalizedDifference(['B8', 'B4']).rename('NDVI'));
};
/////Add bands//////
var fire_WM_ImColA1 = fire_CM_ImColA1.map(addNDVI);
////meanNDVI///
var mean_ndvi = function(image){
var ndvi = image.select(['NDVI']);
var ndvi_mean = ndvi.reduceRegion({
reducer: ee.Reducer.mean(),
geometry: geometry,
scale: 20,
maxPixels: 10e18,
});
return ndvi_mean;
};
var fire_ImColA1 = fire_WM_ImColA1.map(mean_ndvi);
var mean_mask = function(image){
var mask = image.select(['mean_ndvi']);
return image.addBands(ee.Image(1).updateMask(mean_mask.gt(mean_mask)).rename('mean_mask'));
};
print (fire_ImColA1);