Google Earth Engine – How to Calculate Number of Pixels Inside a Polygon?

google-earth-enginepolygonspatial statistics

I'm trying to know how many pixels are inside my polygon when I calculate the mean (and other statistics) by using the "count" reducer. I guess many things go into this: what GEE does with pixels that are split, the right choice of scale, etc. I read somewhere that a pixel will be considered in a calculation when more than 50% of it is included in the polygon. I'm trying to understand what is going on with the following code:

https://code.earthengine.google.com/6144ac3715d195827378795c98994139

In have two polygons, polygon 1 and 2 that are inside the corresponding pixel. Polygon 1 has an area of 316 m2 and Polygon 2 an area of 360 m2, yet when I use the count reducer I get a value of 0 for the first one and a value of 1 for the second one. What is the rule here? Moreover, I still get a value for the mean even though the count is zero. What am I doing wrong?

I was trying to read the scale documentation about this, but I cannot understand what is going on.

Best Answer

The inputs to the count reducer are not weighted. A pixel is either in or out. If it's in, the centroid of the pixel must be in the region. It's out otherwise. The mean is weighted by area, so you get an answer based on the fraction of the pixel intersected by the region.

Edit:

As suggested by Noel, you can use the sum() reducer on the image mask to get both fractional pixels and area. Continuing the OP's example,

var mask = image.select(0).mask().rename('mask');
var area = ee.Image.pixelArea().multiply(mask).rename('area');

var sumDictionarypolygon1 = mask.addBands(area).reduceRegion({
  reducer: ee.Reducer.sum(),
  geometry: polygon1.geometry(),
  scale: 30,
  maxPixels: 1e9
});
print('sum for pol 1 mask, scale=30', sumDictionarypolygon1);

Note that you can get a more accurate area (that matches polygon1.area()) by increasing the scale.

Related Question