2

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

2 Answers 2

3

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

1
  • 1
    Thanks! That did the trick! (And great catch, 34 is what I meant) Dec 12, 2021 at 1:46
3

You can simply or together the mask values you want.

var mask = crop2019.eq(20).or(crop2019.eq(34))

Which can also be easily represented in an expression:

var mask = crop2019.expression("b('landcover') == 20 || b('landcover') == 34")
1
  • Great answer too! Thanks Noel! Dec 13, 2021 at 14:42

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.