[GIS] Cloud mask using pixel_qa

cloud covergoogle earthgoogle-earth-enginemaskingpixel

I need to create a cloud mask using the pixel_qa band, this is the code that I have so far:

var city = ee.Geometry.Point(9.15, 45.18);
var landsat8 = ee.ImageCollection('LANDSAT/LC08/C01/T1_SR')

// Fmask classification values 

var mosaic = landsat8 
    .filterBounds(city) 
    .filterDate('2017-08-01', '2017-09-01') 
    .mosaic();

var getQABits = function(image, start, end, newName) {
    // Compute the bits we need to extract.
    var pattern = 0;
    for (var i = start; i <= end; i++) {
        pattern += Math.pow(2, i);
    }
// Return a single band image of the extracted QA bits, giving the band a new name.
return image.select([0], [newName])
              .bitwiseAnd(pattern)
              .rightShift(start);
};

// A function to mask out cloudy pixels.
var cloud_shadows = function(image) {
    // Select the QA band.
    var QA = image.select(['pixel_qa']);
    // Get the internal_cloud_algorithm_flag bit.
    return getQABits(QA, 3,3, 'Cloud_shadows').eq(0);
    // Return an image masking out cloudy areas.
};

// A function to mask out cloudy pixels.
var clouds = function(image) {
    // Select the QA band.
    var QA = image.select(['pixel_qa']);
    // Get the internal_cloud_algorithm_flag bit.
    return getQABits(QA, 5,5, 'Cloud').eq(0);
    // Return an image masking out cloudy areas.
};

I tried to create a mask using the Map.addLayer but the result is only a white mask.
What I need is to create a mask in which clouds are displayed with a certain color (ex. white) and all the other pixel type with another color (ex. black).

Best Answer

For your desired output, use addBands instead of updateMask:

var city = ee.Geometry.Point(9.15, 45.18);
var landsat8 = ee.ImageCollection('LANDSAT/LC08/C01/T1_SR');


var getQABits = function(image, start, end, newName) {
    var pattern = 0;
    for (var i = start; i <= end; i++) {
       pattern += Math.pow(2, i);
    }
    return image.select([0], [newName])
                  .bitwiseAnd(pattern)
                  .rightShift(start);
};

var cloud_shadows = function(image) {
    var QA = image.select(['pixel_qa']);
    var ly = getQABits(QA, 3,3, 'Cloud_shadows').eq(0);
    return image.addBands(ly);
};


var clouds = function(image) {
    var QA = image.select(['pixel_qa']);
    var ly = getQABits(QA, 5,5, 'Cloud').eq(0);
    return image.addBands(ly);
};

var mosaic = landsat8 
    .filterBounds(city) 
    .filterDate('2017-08-01', '2017-09-01') 
    .map(cloud_shadows).map(clouds)
    .mosaic();

Map.addLayer(mosaic,{bands:['Cloud']}, 'Cloud');
Map.addLayer(mosaic,{bands:['Cloud_shadows']}, 'Cloud shadows');