Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create a single band image from a list of images #347

Merged
merged 8 commits into from
Oct 24, 2024
15 changes: 15 additions & 0 deletions geetools/Image.py
Original file line number Diff line number Diff line change
Expand Up @@ -1427,3 +1427,18 @@ def plot(
gdf = gpd.GeoDataFrame.from_features(fc.getInfo()["features"])
gdf = gdf.set_crs("EPSG:4326").to_crs(crs)
gdf.boundary.plot(ax=ax, color=color)

@classmethod
def fromList(cls, image_list: ee_list):
fitoprincipe marked this conversation as resolved.
Show resolved Hide resolved
"""Create a single image by passing a list of images.

Parameters:
image_list: a list of ee.Image

Returns:
A single ee.Image with one band per image in the passed list
"""
ilist = ee.List(image_list)
i0 = ee.Image(ilist.get(0))
rest = ee.List(ilist.slice(1))
return i0.geetools.merge(rest)
fitoprincipe marked this conversation as resolved.
Show resolved Hide resolved
24 changes: 24 additions & 0 deletions tests/test_Image.py
Original file line number Diff line number Diff line change
Expand Up @@ -641,3 +641,27 @@ def test_plot_with_crs(self, s2_sr_vatican_2020, vatican, image_regression):
fig.savefig(image_byte, format="png")
image_byte.seek(0)
image_regression.check(image_byte.getvalue())


class TestFromList:
"""Test ``fromList`` method."""

def test_from_list(self):
"""This test is meant to fail."""
12rambau marked this conversation as resolved.
Show resolved Hide resolved
esa = ee.ImageCollection("ESA/WorldCover/v200")
esai = esa.first()
values = [10, 20, 30]
names = ["trees", "shrubs", "grass"]

def over_values_names(zipped):
z = ee.List(zipped)
value = ee.Number(z.get(0))
name = ee.String(z.get(1))
mask = esai.eq(value).rename(name)
return mask

combined = ee.List(values).zip(ee.List(names))
images = combined.map(over_values_names)
final = ee.Image.geetools.fromList(images)
bands = final.bandNames().getInfo()
assert bands == names