Skip to content

Instantly share code, notes, and snippets.

@kvutien
Last active January 10, 2021 22:35
Show Gist options
  • Save kvutien/7712a3ef1fd1e2c3be449aabb7efdcce to your computer and use it in GitHub Desktop.
Save kvutien/7712a3ef1fd1e2c3be449aabb7efdcce to your computer and use it in GitHub Desktop.
Generate mosaic with the best NDVI of a month over a period of time
/*
* @notice GEE JavaScript for Code Editor
* @notice Generate a mosaic using pixels of the best NDVI of all images of a month
* @notice Do it over all same months of a period of time, for example March (or August, or December)
* @notice ... useful to remove clouds and calculate monthly NDVI stats over several years
* @author Vu Tien Khang, licence MIT, Jan 2021
*/
// make a list of years composing the history
var history = ee.List.sequence(2017, 2020);
// per year of history, calculate bestNDVI and add to bestNDVICollection
bestNDVICollection = history.map(makeBestCollection(studyMonth, refSetS2));
// do something with this collection...
//-------------------------
function makeBestCollection(studyMonth, refSetS2){
/*
* @notice Generate a mosaic using pixels of the best NDVI of all images of a month
* @param {integer in 1-12} studyMonth: month to generate ee.DateRange
* @param {imageCollection} refsetS2: full set of images, several years
* @dev {function} addNDVI: function to add NVI channel named 'NDVI' to an image
*/
return function(year){
// ask GEE to set start of range of dates
var mosaicStartDate = ee.Date.fromYMD(year, studyMonth, 1);
// ask GEE to set range of images to mosaic
var range2Mosaic = ee.DateRange(mosaicStartDate, mosaicStartDate.advance(1, 'month'));
// ask GEE to keep only images in this range to mosaic
var filtered = refSetS2.filterDate (range2Mosaic);
// ask GEE to add NDVI channel to all images of this filtered collection
var with_NDVI = filtered.map (addNDVI);
// ask GEE to make a mosaic from all the set with the best NDVI and return this image
return with_NDVI.qualityMosaic ('NDVI')
.set('system:time_start', with_NDVI.first().get('system:time_start'));
}
}
//---------------------------
function addNDVI(NIR, RED){
/*
* @notice Function used by map() to add to "image" the band NDVI (normalized difference NIR and Red)
* @param {ee.String} NIR: name of band NIR in image, depends on the satellite
* @param {ee.String} RED: name of band RED in image, depends on the satellite
* @author Vu Tien Khang, licence MIT, Jan 2021
*/
return function (image) {
var ndvi = image.normalizedDifference ([NIR, RED]).rename ('NDVI');
return image.addBands (ndvi);
}};
@kvutien
Copy link
Author

kvutien commented Jan 10, 2021

This snippet is a bit too "ninja" :-)
For beginners or students, I made also a complete ready-to-use GEE code: https://gist.github.com/kvutien/97be53cd7694d30ff06ddfaa742a399e

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment