3

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.

6

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.