I'm pretty new at GEE.

I want to mask only the water areas for my study area. I want non-water areas to retain their pixel values. For this I detected and masked water areas with NDWI. However, after masking, I cannot show non water pixels and masked pixels (water) in the same image. I see black image for areas without water

I converted my image to 8 bit because it calculates the NDWI index more accurately.

This is my code : https://code.earthengine.google.com/85e1ed5971f860ef8f75ac46342f9f5f

var geometry = 
    /* color: #98ff00 */
    /* shown: false */
    /* displayProperties: [
        "type": "rectangle"
    ] */
        [[[28.115704913382, 36.89857549006249],
          [28.115704913382, 36.681919654361074],
          [28.33371486211247, 36.681919654361074],
          [28.33371486211247, 36.89857549006249]]], null, false);

var s2 = ee.ImageCollection('COPERNICUS/S2_SR');

var rgbVis = {
  min: 0.0,
  max: 3000,
  bands: ['B4', 'B3', 'B2'],
var filtered = s2
  .filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 30))
  .filter(ee.Filter.date('2021-08-25', '2021-08-29'))

var composite = filtered.median().clip(geometry) ;
// Display the input composite.
Map.addLayer(composite, rgbVis, 'image');

///Rescale to 8 bits

var composite = composite.unitScale(0, 65535).multiply(255).toByte();


var ndwi =
    composite.normalizedDifference(['B3', 'B8']).rename('NDWI');
    {palette: ['red', 'yellow', 'green', 'cyan', 'blue']},

// Create NDWI mask
var ndwiThreshold = ndwi.gte(0.0);
var ndwiMask = ndwiThreshold.updateMask(ndwiThreshold);
    {palette:['black', 'white']},
    'NDWI Binary Mask');
Map.addLayer(ndwiMask, {palette:['blue']}, 'NDWI Mask');

var mask = ndwiThreshold.eq(0); 
var S2_2 = composite.updateMask(mask); 
Map.addLayer(S2_2, rgbVis, 'image2');

1 Answer 1


One quick option: the 8 bits image used for NDWI must be different to image that you want to mask, so:

//Keep 8 bits for NDWI

///Rescale to 8 bits as new var (e.g. composite2)

var composite2 = composite.unitScale(0, 65535).multiply(255).toByte();


var ndwi =
    composite2.normalizedDifference(['B3', 'B8']).rename('NDWI');
    {palette: ['red', 'yellow', 'green', 'cyan', 'blue']},

enter image description here

code example here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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