Understanding the Cloud Mask in Google Earth Engine

cloudmaskinggoogle-earth-enginejavascript

I would like to understand what the logic of this code is (I know that with this code it is possible to mask the pixels classified as cloud and cloud shadow of Landsat 8 images).

I'm still having some difficulties understanding bitwise operators.

function maskL8sr(image) {
  // Bits 3 and 5 are cloud shadow and cloud, respectively.
  var cloudShadowBitMask = 1 << 3;
  var cloudsBitMask = 1 << 5;

  // Get the pixel QA band.
  var qa = image.select('pixel_qa');

  // Both flags should be set to zero, indicating clear conditions.
  var mask = qa.bitwiseAnd(cloudShadowBitMask).eq(0)
      .and(qa.bitwiseAnd(cloudsBitMask).eq(0));

  // Return the masked image.
  return image.updateMask(mask);
}

Best Answer

Bitwise operations take quite a bit of mental gymnastics to get one's head around. I know it took me quite a while to grasp the concept enough to feel comfortable.

First part of the code creating the test variables.

var cloudShadowBitMask = 1 << 3; // pushes "1" 3 spaces to the left 001000
var cloudsBitMask = 1 << 5;  // pushes "1" 5 spaces to the left 0100000

The bitwiseAnd() function tests the validity of that bit against a byte to see if the "bit" is true in the full byte.

000000000000 // Image QA    Test against this

000000001000 // cloudShadowBitMask
000000000000 // result false.  No bit matches.  So no cloud Shadow

000000100000 // cloudsBitMask
000000000000 // result false.  No bit matches.  So no cloud

The great thing about this is that you can check individual bits, as is the case of your clouds. Here you are only checking for clouds. It could be that bit 9 is ice, so your Image QA looks like this.

001000000000 // Image QA. contains Ice/Snow.  Test against this

000000001000 // cloudShadowBitMask
000000000000 // result false.  No bit matches.  So no cloud Shadow

000000100000 // cloudsBitMask
000000000000 // result false.  No bit matches.  So no cloud

As you then supply this to your mask any pixel that doesn't equal 0 to both these tests, will be masked in your final image and not be used in any subsequent calculations.

Related Question