0

I am struggling to create the code where if the previous classified image and the sequential classified image in the image collection are both urban for example, then make the current image class urban at that pixel as well.

What I have so far, but doesn't work:

var sortedCollection = classified2.sort('system:time_start', true);

var adjustImage = function(image) {
  var currentImage = image.get('system:time_start');
  var previousImage = ee.Image(sortedCollection.filter(ee.Filter.lt('system:time_start', currentImage)).first());
  var nextImage = ee.Image(sortedCollection.filter(ee.Filter.gt('system:time_start', currentImage)).first());

  if (previousImage !== null && nextImage !== null) {
    var imageFixed = currentImage.where(previousImage.eq(6), 6);
    return imageFixed;
} else {
  return currentImage;
}
};
var correctedCollection = sortedCollection.map(adjustImage);
Map.addLayer(correctedCollection, {}, 'FirstCorrectedImage');

1 Answers1

0

I'm not clear from your description exactly how you want your logic to work. I'm assuming that if the previous and next image in the collection have the same value, you want to use that value. Otherwise, you use the value of current image.

The main issue is the way you are dealing with null. You are using client-side operations on server-side objects. Read up on the distinction here.

It's often tricky to deal with null in EE. Often times, it's better to try to keep the data in lists or collections, to avoid null from showing up at all. You could filter the collection and limit the list, instead of using first(). That gives you two images collections, previous and next in the below script. They each have 0 or 1 images. Then you can merge these collections (adjacentImages). When you have a count of 2 but only have 1 distinct value, you have both a previous and next with the same value.

function adjustImage(image) {
  var timeStart = image.date().millis()
  var previous = sortedCollection
    .filter(ee.Filter.lt('system:time_start', timeStart))
    .sort('system:time_start', false)
    .limit(1)
  var next = sortedCollection.filter(ee.Filter.gt('system:time_start', timeStart))
    .limit(1)
  var adjacentImages = previous.merge(next)
  var reduced = adjacentImages
    .reduce(
      ee.Reducer.count()
        .combine(ee.Reducer.countDistinctNonNull().setOutputs(['distinct']), null, true)
    )
    .rename(['count', 'distinctCount'])
  var adjacentEqual = reduced.select('count').eq(2)
    .and(reduced.select('distinctCount').eq(1))
  return image
    .where(adjacentEqual, adjacentImages.first())  
}

https://code.earthengine.google.com/ac74aa966320c10375afa809bd76d7d9

Daniel Wiell
  • 253
  • 2
  • 5