# number of pixels inside a polygon in Google Earth Engine

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:

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?

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');

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.

• Can you explain the effects of scale? If I have a native resolution of 30x30 meters, what is the proper scale to use if I want to know the number of pixels inside the polygon? Sep 28, 2017 at 16:30
• Number of what sized pixels? If you want to know how many 30 meter pixels there are, use `scale: 30`. Sep 29, 2017 at 16:19
• OK, I think you answered the question, but in general I want to know the number of pixels at native resolution. Is there a general way to retrieve the native resolution in the scale specification part of sumDictionarypolygon above? Sep 30, 2017 at 17:15
• To discover native resolution of a band, you can use: `image.select(0).projection().nominalScale()` Oct 2, 2017 at 16:43