Mapping over image collection
Mapping over an ImageCollection
Reference: https://developers.google.com/earth-engine/guides/ic_mapping
To apply a function to every Image
in an ImageCollection
use imageCollection.map()
. The only argument to map()
is a function which takes one parameter: an ee.Image
.
In [ ]:
import ee
import geemap
In [ ]:
Map = geemap.Map()
Define a function¶
In [ ]:
def minus1000(num):
result = ee.Number(num).subtract(1000)
return result
In [ ]:
result = minus1000(2000)
print(result.getInfo())
Apply the map function¶
In [ ]:
years = ee.List.sequence(2000, 2010)
print(years.getInfo())
In [ ]:
results = years.map(minus1000)
print(results.getInfo())
Use anonymous/lambda function¶
In [ ]:
years = ee.List.sequence(2000, 2010)
results = years.map(lambda x: ee.Number(x).subtract(1000))
print(results.getInfo())
Filter an ImageCollection¶
In [ ]:
roi = ee.Geometry.Point(-83.92, 35.96) # Knoxville, Tennessee
collection = ee.ImageCollection('LANDSAT/LC08/C01/T1_SR') \
.filterBounds(roi) \
.filterDate("2019-01-01", "2020-01-01") \
.sort("CLOUD_COVER")
print(collection.size().getInfo())
In [ ]:
image = collection.first()
In [ ]:
# image.getInfo()
In [ ]:
geemap.image_props(image).getInfo()
In [ ]:
collection.aggregate_array("CLOUD_COVER").getInfo()
In [ ]:
vis_params = {
'bands': ['B5', 'B4', 'B3'],
'min': 0,
'max': 3000,
'gamma': 1.0
}
Map.addLayer(image, vis_params, "First image")
Map.centerObject(image)
Map
Select the best image each year¶
In [ ]:
roi = ee.Geometry.Point(-83.92, 35.96) # Knoxville, Tennessee
def best_image(year):
start_date = ee.Date.fromYMD(year, 1, 1)
end_date = start_date.advance(1, 'year')
image = ee.ImageCollection('LANDSAT/LC08/C01/T1_SR') \
.filterBounds(roi) \
.filterDate(start_date, end_date) \
.sort("CLOUD_COVER") \
.first()
return image
In [ ]:
start_year = 2013
end_year = 2020
years = ee.List.sequence(start_year, end_year)
year_list = years.getInfo()
print(year_list)
In [ ]:
images = years.map(best_image)
In [ ]:
count = images.size().getInfo()
print(count)
In [ ]:
ee.ImageCollection(images).aggregate_array("CLOUD_COVER").getInfo()
In [ ]:
for index in range(0, count):
image = ee.Image(images.get(index))
layer_name = "Image " + str(year_list[index])
Map.addLayer(image, vis_params, layer_name, False)
In [ ]:
Map
Set image properties¶
In [ ]:
collection = ee.ImageCollection(images)
In [ ]:
collection.aggregate_array("system:time_start").getInfo()
In [ ]:
collection = collection.map(lambda img: img.set({"DATE": ee.Date(img.get("system:time_start")).format("YYYY-MM-dd")}))
In [ ]:
collection.aggregate_array("DATE").getInfo()
Last update: 2021-03-17