Google Earth Engine – Masking ee.Image() for Specific Values from a List: Step-by-Step Guide

google-earth-enginegoogle-earth-engine-javascript-api

In Google Earth Engine I'm having trouble masking for more than one value (non-contiguous). I was curious what I'm doing incorrectly?

The gist is that I'm pulling a raster that has landcover types for Canada, and I'd like to pull out only a couple of those. So far I'm only able to pull one value out.

This part, crop2019.eq(20) is the bit I'm having trouble with. I've tried crop2019.eq([20,35]) but this throws an error when I add it to the map.

Here's the code in entirety.

var roi = 
    ee.Geometry.Polygon(
        [[[-114.98227393568517, 51.566350380791135],
          [-114.98227393568517, 50.51293892977377],
          [-113.13107764662267, 50.51293892977377],
          [-113.13107764662267, 51.566350380791135]]], null, false),

  // Canada AAFC Annual Crop Inventory (Each pixel value represents different landcover)
  crop2019 = ee.ImageCollection('AAFC/ACI')
    .filter(ee.Filter.date('2019-01-01', '2020-01-01')) // last update was 2020
    .first()
    .select('landcover')
    .clip(roi),

  masked2019 = crop2019.updateMask(
    // ============================================================
    // QUESTION:  How can I specify more than one value in a Mask?
    //            I'd like to have 20 (Water), 35 (Urban).
    // ============================================================
    
    crop2019.eq(20)
  );

Map.addLayer(crop2019, null, "Classified Landcover", false); // turn classified map off 
Map.addLayer(masked2019, null, "Classified Landcover > Masked ");
Map.addLayer(roi, {color: 'FF0000'}, 'ROI polygon', false); // turn ROI polygon off

Map.centerObject(roi, 8);

I've tried the following solution but it just results in a black raster: How to mask pixels in image collection?

Additionally here's the code in GEE: https://code.earthengine.google.com/67048aa4c31d423f869781d576d9c234

Best Answer

First, I didn't find class 35. Is urban 34? For this case, you can use the classical if-else statement inside an expression function.

For classes 20 and 34:

masked2019 = crop2019.updateMask(
    crop2019.expression(
      "(b('landcover') == 20) ? 2" +
      ": (b('landcover') == 34) ? 1" +
      ":0"
      )
  );

Check expressions and conditional operators guides

Related Question