colab Open in SageMaker Studio Lab Open in Planetary Computer

Container Emulation Methods for ee.Image and ee.ImageCollection

Tutorial created by **David Montero Loaiza**: GitHub | Twitter

Let’s start!

If required, please uncomment:

[1]:
#!pip install eemont
#!pip install geemap

Import the required packages.

[2]:
import ee, eemont, geemap
import geemap.colormaps as cm

Authenticate and Initialize Earth Engine and geemap.

[3]:
Map = geemap.Map()

Let’s define a point of interest:

[4]:
poi = ee.Geometry.PointFromQuery("Oporto, Portugal",user_agent = "eemont-tutorial-024")

Let’s work with Sentinel-2 SR:

[5]:
S2 = (ee.ImageCollection("COPERNICUS/S2_SR")
      .filterBounds(poi)
      .filterDate("2020-01-01","2020-07-01")
      .preprocess()
      .spectralIndices())

Container Emulation Methods

ee.ImageCollection

If you want to know how many images has the image collection, you can use len():

[6]:
len(S2)
[6]:
72

If you want to select specific bands from the collection, you can use collection[band] or collection[[band1,band2,...,bandn]]:

[7]:
RGB = S2[["B2","B3","B4"]]

You can also do this by using band indices:

[8]:
RGB = S2[[1,2,3]]

Or regex:

[9]:
RGB = S2["B[2-4]"]

Or even better: slices!

[10]:
RGB = S2[1:4]

Create a composite by using container emulation methods!

[11]:
Map = geemap.Map()
Map.addLayer(S2[[3,2,1]].median(),{"min":0,"max":0.3},"RGB")
Map.centerObject(poi)
Map

If you want to select images from a collection, convert the collection to a list and use container emulation methods!

We are going to select the first, the third, and the fifth images from the collection.

First, let’s convert the collection to a list:

[12]:
S2list = S2.toList(S2.size())

Then, we can select the images!

[13]:
S2selected = S2list[[0,2,4]]

Now we have three images in the S2selected list:

[14]:
len(S2selected)
[14]:
3

Now, let’s select all images from the 21st until the end.

Psst! We can use slices!

[15]:
S2selected = S2list[20:]

Let’s see how many images do we have!

[16]:
len(S2selected)
[16]:
52

If we don’t want the last images to be selected, we can use negative indices! Here an example:

[17]:
S2selected = S2list[20:-5]

Now, let’s see how many images do we have in the list now!

[18]:
len(S2selected)
[18]:
47

But they’re ee.Image objects inside an ee.List object. We can leave it that way, or we can convert them into an ee.ImageCollection object!

[19]:
S2selected = ee.ImageCollection(S2selected)

ee.Image

We can also select bands for an ee.Image object!

[20]:
S2img = S2.first()

Let’s select the NDVI:

[21]:
NDVI = S2img['NDVI']

Or let’s select the RGB bands using slices!

[22]:
RGBimg = S2img[1:4]

The same rules for ee.ImageCollection apply for the ee.Image object class!

Let’s visualize the NDVI for Oporto!

[23]:
Map = geemap.Map()
Map.addLayer(S2img["NDVI"],{"min":0,"max":1,"palette":cm.palettes.ndvi},"NDVI")
Map.centerObject(poi)
Map