I have been trying to generate a GEE script to generate two raster bands from a Sentinel-2 Surface Reflection collection.
The first band should have the maximum NDVI value per pixel for a whole year. So this raster would have pixels from different dates, each pixel being the maximum NDVI value for a whole year.
The second raster band should register the acquisition date of each pixel as an integer of a date format "YYYYMMdd".
I've tried many things but I can't manage to generate the second raster right.
This is the code I'm working on now:
// Define ROI
var asset_polygon = ee.FeatureCollection('projects/ee-user/assets/mask');
// Define the year of interest
var year = 2022;
// Load & filter Sentinel-2 data
var sentinel2 = ee.ImageCollection('COPERNICUS/S2_SR')
.filterBounds(asset_polygon)
.filterDate(year + '-01-01', year + '-12-31')
.select(['B8', 'B4'])
.map(function(image) {
// Compute NDVI for each image
var ndvi = image.normalizedDifference(['B8', 'B4']).rename('ndvi');
// Add acquisition date as a band to the image
var date = ee.Date(image.get('system:time_start')).format('YYYYMMdd');
var dateBand = ee.Image(ee.Number.parse(date)).toInt().rename('date');
return image.addBands(ndvi).addBands(dateBand);
});
// Compute the maximum NDVI and acquisition date for each pixel
var maxNdvi = sentinel2.qualityMosaic('ndvi').select('ndvi');
var acquisitionDate = sentinel2.qualityMosaic('date').select('date');
// Export the rasters as single band images to Google Drive
Export.image.toDrive({
image: maxNdvi,
description: 'S2_max_ndvi_' + year,
folder: 'gee',
scale: 10,
region: asset_polygon.geometry()
});
Export.image.toDrive({
image: acquisitionDate,
description: 'S2_acq_date_' + year,
folder: 'gee',
scale: 10,
region: asset_polygon.geometry()
});
It seems when trying to generate the acquisition date raster, it is generating the maximum date of the integer "YYYYMMdd" instead of the date associated with the maximum value of NDVI.
How can I get the associated date for each pixel?
Best Answer
You were almost there. Instead of regenerating a
qualityMosaic
for thedate
band which you are currently doing inacquisitionDate
you need to keep thequalityMosaic
generated forndvi
and then select thedate
band, i.e.: