1

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"
      }
    ] */
    ee.Geometry.Polygon(
        [[[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'))
  .filter(ee.Filter.bounds(geometry))
  .select('B.*');

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


///Rescale to 8 bits

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

///NDWI/////

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

// Create NDWI mask
var ndwiThreshold = ndwi.gte(0.0);
var ndwiMask = ndwiThreshold.updateMask(ndwiThreshold);
Map.addLayer(
    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); 
print(S2_2)
Map.addLayer(S2_2, rgbVis, 'image2');

1 Answer 1

0

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();

///NDWI/////

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


enter image description here

code example here

Your Answer

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

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