I am new here so please forgive any mistakes in this post: I have a simple script to classify cultivated area vs none cultivated areas using Sentinel-2 in GEE. I want to mask out all objects that are less than 1 ha in size. Below is the script I have put together, but the problem I have is that the .connectedComponents and .connectedPixelCount have a maxSize of 255, which drops very large chunks of the cultivated area's when I finally apply the mask in the end. Can anyone help me tidy this up?

//Add Sentinel imagery from Dry Season 2019, layer stack, composite and clip
var Sentinel2 = ee.ImageCollection('COPERNICUS/S2_SR')
                  .filterDate('2019-03-20', '2019-08-31')
                  .filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 10))
                  .select(['B2', 'B3','B4','B8','B11','B12'])
//Create an NDVI band and add it to the Sentinel stack
var ndvi = Sentinel2.normalizedDifference(["B8","B4"]);
var with_ndvi = Sentinel2.addBands(ndvi);

// Merge the training points to a single FeatureCollection.
var trainingPoints = Cult.merge(NoCult);

//Obtain signatures for each class from the image
var training = with_ndvi.sampleRegions({collection: trainingPoints, properties: ['Class'],  scale: 10});

//Train the classifier
var classifier = ee.Classifier.cart().train(training, 'Class');

//Run the classification
var classified = with_ndvi.classify(classifier);

//Extract out just the agriculture
var agric = classified.updateMask(classified.eq(1));

// Uniquely label the agric areas.
var objectId = agric.connectedComponents({
  connectedness: ee.Kernel.plus(1),
  maxSize: 255

// Compute the number of pixels in each object defined by the "labels" band.
var objectSize = objectId.select('labels')
    maxSize: 255, eightConnected: false

// Get a pixel area image.
var pixelArea = ee.Image.pixelArea();

// Multiply pixel area by the number of pixels in an object to calculate the object area. 
var objectArea = objectSize.multiply(pixelArea);

// Mask out objects below 1 hectare
var areaMask = objectArea.gte(10000);

//Create final cultivated area layer with mask applied
var agricFin = agric.updateMask(areaMask);


Link to the script is here: https://code.earthengine.google.com/1172c13936c011b39f2c62abf56fecb3

1 Answer 1


You could maybe do like this:

// Pick large enough maxSize to fit your minArea at the scale you
// want to export in. As you zoom in, you will require more and more
// pixels to get your minArea. At some point it will be larger than
// maxSize, and everything get masked out.
var minArea = 10000
var maxSize = 200
var pixelCount = agric.connectedPixelCount(maxSize)
var minPixelCount = ee.Image(minArea).divide(ee.Image.pixelArea())
var agricFin = agric.updateMask(pixelCount.gte(minPixelCount))


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.