Search code examples
google-earth-engine

Reclassify all pixel values in all of the images in an image collection - GEE


I am new to GEE so the answer to this question may be simple to most of you. I am looking for a way to reclassify pixel values in all of the images in an image collection. I'm working with the Monthly History data from the Global Surface Water dataset and targeting the months March-May. As it currently is, water pixels have a value of 2, non-water pixels are 1, and non-sampled pixels (no data) are 0. I would like to reclassify such that water = 1, not water = 0, and everything else is masked. My code is below:

var dataset = ee.ImageCollection('JRC/GSW1_2/MonthlyHistory')
.filterBounds(roi)
.map(function(image){return image.clip(roi)})
.filter(ee.Filter.calendarRange(3, 5, 'month'));
print(dataset);

This is the part that doesn't work...

var reclassified = function(img) {
  return img.remap(([2, 1], [1, 0]), 'water');
};
var new_ds = dataset.map(reclassified)
print(new_ds);

Solution

  • You have an extra set of parentheses here:

      return img.remap(([2, 1], [1, 0]), 'water');
                       ^              ^
    

    The effect of this mistake is to proceed as if you had written img.remap([1, 0], 'water'), which fails because 'water' can't be turned into a list.

    There is another problem: when you're not using the named parameters form, you have to write all the arguments up to the last optional one you want to specify. The parameter list is remap(from, to, defaultValue, bandName), so you need to write a defaultValue even though you don't need it. In Earth Engine API calls, you can use null for any optional parameter you don't want to specify:

      return img.remap([2, 1], [1, 0], null, 'water');
    

    Or, you can use named arguments for the same result:

      return img.remap({
        from: [2, 1],
        to: [1, 0],
        bandName: 'water'
      });
    

    Or, since in this particular case your image contains only one band, you can leave out the bandName entirely:

      return img.remap([2, 1], [1, 0]);