Stack Different Bands from Separate Image Collections in GEE

geemapgoogle-earth-enginestack

I have two image collections.

The first collection has 3 images ,each one has 1 band, the blue band of sentinel 2.

The second collection has the same data as collection1, but the only difference is that instead of having the blue band, it has the green band.

I would like to create one imageCollection from the both collection that will have 3 images, each image will have 2 bands: the green and the red. (stacking the first imgae in col1 with first image in col2,etc. ).

I know how to stack images with addbands, for example:

stacked_img = img_red1.addBands(img_green1)

or how to create image collection from images:

ee.ImageCollection.fromImages([img_red1,img_green1])

But I'm not sure how to tackle it when I have two image collections when each one has more than 1 image and the order of the images has meaning.

My end goal: new image collection, with 3 images , each one has 2 bands: red and green (from col1 and col2)

Best Answer

Hopefully, the images you want to pair have some common property. Like system:time_start or similar. Otherwise, you have to rely on the order in the collection, turning them into lists and pairing them based on their list index. That's not efficient for larger collections, and you can run out of memory.

Assuming you have such an property, you could join the two collection together:

var redCollection = ee.ImageCollection([
  ee.Image(1).set('dateOfYear', 1).rename('red'),
  ee.Image(2).set('dateOfYear', 2).rename('red'),
  ee.Image(3).set('dateOfYear', 3).rename('red'),
])

var greenCollection = ee.ImageCollection([
  ee.Image(4).set('dateOfYear', 1).rename('green'),
  ee.Image(5).set('dateOfYear', 2).rename('green'),
  ee.Image(6).set('dateOfYear', 3).rename('green'),
])

var collection = ee.ImageCollection(
  ee.Join.saveFirst('greenImage')
    .apply({
      primary: redCollection, 
      secondary: greenCollection, 
      condition: ee.Filter.equals({leftField: 'dayOfYear', rightField: 'dayOfYear'})
    })
).map(function (redImage) {
  var greenImage = ee.Image(redImage.get('greenImage'))
  return redImage
    .addBands(greenImage)
    .int8()
})

https://code.earthengine.google.com/469979917ae8e12423fecbf6ca1dc43c

Related Question