GEE – Pixel-wise Max Class Count for ImageCollection

google-earth-enginegoogle-earth-engine-javascript-apiland-coverpython

I am working with Dynamic World dataset. The label band gives me the pixelwise landcover class values. For any specific year, ImageCollection.mode() gives me the pixelwise most occurring landcover class. I am also interested in calculating how many times that class actually occurred in each pixel. In short, value and count of that class.

bn = ee.Geometry.Rectangle([-91, 33, -90, 34])
startDate = '2020-06-01'
endDate = '2021-09-01'
dw = ee.ImageCollection('GOOGLE/DYNAMICWORLD/V1').filterDate(startDate, endDate).filterBounds(bn)
max_occurred_class_label = dw.select('label').mode()
max_occurred_class_count = anyFunction(dw.select('label'))

Any ideas, how to achieve this?

Best Answer

There's a couple of ways:

You can map over the collection testing if each pixel is equal to the mode you found, then sum that.

var count = dw.map(function(img) {
    return img.select('label').eq(max_occurred_class_label)
}).sum()

Or you can compute a histogram per pixel, sort it by count and then strip off the last row of the resulting array. This method is usually better if you're going to do anything involving more logic (like compare to 2nd most frequent or deal with ties):

var result = dw.select('label').reduce(ee.Reducer.autoHistogram(16).unweighted())
var values = result.arraySlice(1, 1, 2)
var sorted = result.arraySort(values)
var topLabel = sorted.arrayGet([-1,0])
var topCount = sorted.arrayGet([-1,1])

When doing stuff with arrays, it's easy to get confused on this like which axis is which, so it's usually easiest to look at the results on the map at every step:

https://code.earthengine.google.com/72a330a14f473257a817c238b5e64d15