Search code examples
javascriptclassificationgoogle-earthgoogle-earth-engine

How to count sum of pixels in each class in a classified image (Landsat) in Google Earth Engine?


I'm making a dissertation about glacier changes. I did a supervised classification on a Landsat 8 image, and I would like to count how many pixels are there in each classes. I want to make a chart by the way.

But I stucked, my code runs into error. I tried to use ui.Chart.image.byClass() method with the specified parameters, but is does not works.

My code:

var img = ee.Image('LANDSAT/LC8_L1T_TOA/LC81940282016238LGN00') ; 

// Add pseudocolor image
Map.addLayer(img, {bands: ['B6', 'B5', 'B4'] }, 'Pseudocolor image' ) ; 

// Training points for classification - Point geometries
var points = [class1,class2,class3, class4, class5] ; 
var trainingPoints = ee.FeatureCollection(points) ; 

var training = img.sampleRegions(trainingPoints, ['class'] ,30) ; 

var trained = ee.Classifier.minimumDistance().train(training, 'class' ) ; 
var classified = img.classify(trained) ; 

var palette = ['red','red', '#696969' , '#90EE90' , '#008000' ]  ;

Map.addLayer(classified, {min: 0 , max : 5 , palette : palette }, 'L8 
classified' ) ; 

print(classified); 

var options = {
lineWidth: 1,
pointSize: 2,
hAxis: {title: 'Classes'},
vAxis: {title: 'Num of pixels'},
title: 'Number of pixels in each class.'
}; 

var chart = ui.Chart.image.byClass({

image : classified ,
classBand : 'classification', 
region : aletsch           //<-- A previousy defined line type geometry
}).setOptions(options) ; 

And the error what it throws:

Dictionary.get: Dictionary does not contain key: groups.

Is there any other tools to count the number of pixels in each classes?


Solution

  • What you're missing is a band to aggregate. Earth Engine knows you want to use 'classification' to group the results, but then can't find any other band to count (or sum or reduce in some way). Here's one option:

    var pixelChart = ui.Chart.image.byClass({
      image: ee.Image(1).addBands(classified),
      classBand: 'classification', 
      region: region,
      scale: 30,
      reducer: ee.Reducer.count()
    }).setOptions(options);
    

    That counts the number of pixels in a constant image of 1's. Perhaps a better option is to sum area (in square meters):

    var areaChart = ui.Chart.image.byClass({
      image: ee.Image.pixelArea().addBands(classified),
      classBand: 'classification', 
      region: region,
      scale: 30,
      reducer: ee.Reducer.sum()
    });
    

    See also this tutorial. By the way, always specify scale.