I have a feature collection that is used as input for a model. In order to validate the model, I would like to mask a random percentage of pixels from each image, i.e. splitting the feature collection into a training and validation collection.
I tried to solve this by adding a random band (ee.Image.random()) to each image and then creating a mask with the .gte() and .lt() routines. I intended to map that function over the collection later on. However, the random band has a different resolution and projection than the image.
I also tried to re-project the random image to the projection of the target image. That did not work either.
Is there any easy implementable solution to mask random pixels in Google Earth Engine?
This is an example of what I am trying to do. Only the last three blocks are relevant. The pictures illustrate the respective outputs.
[![// Function to cloud mask from the pixel_qa band of Landsat 8 SR data.
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, scaled to TOA reflectance, without the QA bands.
return image.updateMask(mask).divide(10000)
.select("B\[0-9\]*")
.copyProperties(image, \["system:time_start"\]);
}
// Map the function over one year of data.
var collection = ee.ImageCollection('LANDSAT/LC08/C01/T1_SR')
.filterDate('2016-01-01', '2016-12-31')
.map(maskL8sr);
var composite = collection.median();
// without reprojection
var sol1 = composite.addBands(ee.Image.random());
sol1 = sol1.updateMask(sol1.select('random').gt(0.2));
// with reprojection
var rand = ee.Image.random();
rand = rand.select('random').gt(0.2);
rand = rand.reproject({crs: composite.projection(), scale: 30});
var sol2 = composite.updateMask(rand);][1]][1]
// Display the results.
Map.addLayer(sol1, {bands: ['B4', 'B3', 'B2'], min: 0, max: 0.3});
Map.addLayer(sol2, {bands: ['B4', 'B3', 'B2'], min: 0, max: 0.3});