Friday 5 August 2016

Add a date (day of year) band to each image in a collection using Google Earth Engine


I would like to add a date (day of year)band to each image in a collection. This will be used as a variable in supervised classification of sentinel-2 imagery along with peak NDVI.



I built a function to add the date band that makes sense to me but doesn't work when I map it. The error reads "Image.constant: Invalid Image.constant type". I think my hang up is converting the date (string) to a number (e.g., '123' -> 123). Seems like it should be simple but I've been stuck for quite some time now.


GEE CODE HERE


I think the 'num' variable isn't actually a number even though I cast it as such...


//filter collection by range, day of year, and bounds
var collection = ee.ImageCollection('COPERNICUS/S2')
.filterDate('2015-05-01', '2017-05-31')
.filter(ee.Filter.dayOfYear(121, 151))
.filterBounds(GP);



//create date band (day of year) for each image in collection
var addDate = function(image){
var doy = ee.Date(image.get('system:time_start')).format('D');
var num = ee.Number(doy);
var banddate = image.select('B8').multiply(0).eq(0).multiply(num).rename('date');
return image.addBands(banddate);
};
//map it
var withDate = collection.map(addDate);
print(withDate);




I think I figured it out...I needed "ee.Number.parse(doy)" instead of "ee.Number(doy)". And I needed ".toUint16()" to cast banddate as an unsigned 16bit image.



Answer



A bit easier way to get DOY and turn it into a new band is:


var addDate = function(image){
var doy = image.date().getRelative('day', 'year');
var doyBand = ee.Image.constant(doy).uint16().rename('doy')
doyBand = doyBand.updateMask(image.select('B8').mask())


return image.addBands(doyBand);
};

You can also reuse mask from another band as well.


https://code.earthengine.google.com/0f1a4577a1a80be9b9feb629685585c8


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...