3

How to calculate the number of pixels in a polygon, especially, when an image contains null-value pixels? I tried the function ee.Reducer.countEvery(), but it does not work.

var geometry = /* color: #d63000 */ee.Geometry.Polygon(
    [[[-122.420654296875, 37.96148894979038],
      [-122.530517578125, 37.735934739135104],
      [-122.244873046875, 37.82276800453933],
      [-121.904296875, 37.87481898883636]]]);

// Load a Landsat 8 image.
var image = ee.Image('LANDSAT/LC08/C01/T1/LC08_044034_20140318');


var c=image.reduceRegion({
  reducer: ee.Reducer.countEvery(),
  geometry: geometry
  });

print(c);
1
  • what in case if we need to count the pixels of three different categories in classified image? Like I followed the code above it worked and gave the total pixels in one count just. I want different categories pixels separately. Jun 17, 2022 at 13:03

1 Answer 1

10

You should use ee.Reducer.count() instead of ee.Reducer.countEvery().

var geometry = /* color: #d63000 */ee.Geometry.Polygon(
    [[[-122.420654296875, 37.96148894979038],
      [-122.530517578125, 37.735934739135104],
      [-122.244873046875, 37.82276800453933],
      [-121.904296875, 37.87481898883636]]]);

// Load a Landsat 8 image.
Map.centerObject(geometry);

var image = ee.Image('LANDSAT/LC08/C01/T1/LC08_044034_20140318');

var c = image.reduceRegion({
  reducer: ee.Reducer.count(),
  geometry: geometry
  });

print(c);

enter image description here

I tested the reducer in a raster with null values, and you get the count of pixels with non-null values only.

enter image description here

EDIT: If you need to count non-null and null pixels, you must unmask the image first (This command fills the null values in the image with zeros).

Map.centerObject(geometry);

var image = ee.Image('users/XXXX/cover2014');
image = image.unmask();

Map.addLayer(image, {});

var c = image.reduceRegion({
  reducer: ee.Reducer.count(),
  geometry: geometry
  });

print(c);

enter image description here

4
  • Thank you for your help. I tried ee.Reducer.count() but it only calculates non-null pixels. I want to calculate the number of all the pixels, both null and non-null pixels included. If you can help me with that it would be great.
    – Sky
    Feb 10, 2018 at 22:08
  • You can't count with the reducer pixels that do not exist. To perform the count on both, null and non-null pixels, you must use unmask() command first. See the edit in the answer.
    – gtapko
    Feb 10, 2018 at 23:44
  • I tried your answer. It is correct. Thank you very much.
    – Sky
    Feb 11, 2018 at 4:49
  • 1
    No worries, if it was useful you could accept the answer.
    – gtapko
    Feb 11, 2018 at 7:12

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.