I have multiple aligned rasters, one for each crop type, where values range from 0 to 100 (%). I'm trying to produce a class raster, where each pixel is assigned to only one crop type. I want to assume that a pixel belongs to a crop type class when that particular crop presented the highest value (%) in its own raster.

I'm thinking I should put all images in a single ImageCollection and run a .max() method in order to get the maximum pixel value from any of the crop rasters. But how do I know from which particular image that pixel value came?

2 Answers 2


ee.Reducer.max takes a numInputs argument that can be used to copy additional values that correspond with the maximum of the first band. If you add a class band to each crop image, combine them into a collection, and use a max reducer with numInputs: 2, the output will be a single image with one band for the maximum probability of all crops and another band for the associated crop class.

Here's a quick demo with random dummy data:

// Create dummy crop probability images
var crop1 = ee.Image.random(1);
var crop2 = ee.Image.random(2);
var crop3 = ee.Image.random(3);

// Add a "class" band to each image
crop1 = crop1.addBands(ee.Image.constant(1).uint8());
crop2 = crop2.addBands(ee.Image.constant(2).uint8());
crop3 = crop3.addBands(ee.Image.constant(3).uint8());

// Collect all of the crop images into a single collection
var crop_probs = ee.ImageCollection([crop1, crop2, crop3]);

// Reduce the collection with `numImputs: 2` to include the crop class with the max probability
var crop_class = crop_probs.reduce(ee.Reducer.max({numInputs: 2})).rename(["prob", "class"]);
Map.addLayer(crop_class, {min: 1, max: 3, bands: ["class"]}, "Crop class")
  • 1
    great solution! I ended up doing something very similar, but using qualityMosaic instead of max, but I like your solution better :) Sep 13, 2023 at 13:05

For reference, this is what I ended up doing. I added the class code as a property to each raster file upon upload, so it could be fetched by a function that adds a band with that value as a constant. Then used qualityMosaic to use the probability band as a quality band.


var maize = ee.Image.random(1);
var soy = ee.Image.random(2);
var rice = ee.Image.random(3);
var geoglam = ee.ImageCollection.fromImages([maize, soy, rice]);

var addClass = function(img){
  var cropBand = ee.Image.constant(img.get('cropclass')).toLong().rename('cropclass');
  img = img.addBands(cropBand);
  return img;

// maping the whole collection using function
var with_class = geoglam.map(addClass);

//A quality mosaic will take the pixel with the highest value from the quality band (in this case the % coverage)
var geoglamcrop  = with_class.qualityMosaic('b1');

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.