pythonfor-loopgoogle-earth-enginegeemap

Loop over image collection ee.ImageCollection to plot in geemap.Map


I am accessing the GEE data catalog through earthengine-api in Colab. Then I would like to explore all the images from my filtered image collection before downloading.

# import libraries
import ee,datetime
import geemap
ee.Authenticate()
ee.Initialize()
Map = geemap.Map()

Filter a collection

roi = ee.Geometry.Polygon([['insert your coordinates']])

start = ee.Date('2023-01-01')
end = ee.Date('2023-02-01')

collection = ee.ImageCollection('COPERNICUS/S2_SR_HARMONIZED') \
               .filterBounds(roi) \
               .filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 10)) \
               .filterDate(start, end)

Visualize it

# Visualization
visualization = {'min': 0.0,
                 'max': 0.3,
                 'bands': ['B4', 'B3', 'B2']}

listOfImages = collection.toList(collection.size())
for i in range(collection.size().getInfo()):
  img = listOfImages.get(i)
  Image = img.multiply(0.0001)
  Map.addLayer(Image, visualization, 'RGB'+str(i))
Map

I was expecting a map where I could interact and explore the data. But I am getting the following error message.

AttributeError:

Cannot add an object of type ComputedObject to the map.


Solution

  • Because multiply is a function for ee.Images (https://developers.google.com/earth-engine/apidocs/ee-image-multiply) not ee.ImageCollections (https://developers.google.com/earth-engine/apidocs/ee-imagecollection).

    So make img an ee.Image in your for loop when multiplying:

    for i in range(collection.size().getInfo()):
        img = listOfImages.get(i)
        Image = ee.Image(img).multiply(0.0001)
        Map.addLayer(Image, visualization, 'RGB' + str(i))