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
40 changes: 40 additions & 0 deletions geetools/Image.py
Original file line number Diff line number Diff line change
Expand Up @@ -1420,6 +1420,46 @@ def plot(
gdf = gdf.set_crs("EPSG:4326").to_crs(crs)
gdf.boundary.plot(ax=ax, color=color)

@classmethod
def fromList(cls, images: ee.List | list):
"""Create a single image by passing a list of images.

Warning: The bands cannot have repeated names, if so, it will throw an error (see examples).

Parameters:
images: a list of ee.Image

Returns:
A single ee.Image with one band per image in the passed list

Examples:
.. code-block:: python

import ee, geetools

ee.Initialize()

sequence = ee.List([1, 2, 3])
images = sequence.map(lambda i: ee.Image(ee.Number(i)).rename(ee.Number(i).int().format()))
image = ee.Image.geetools.fromList(images)
print(image.bandNames().getInfo())

.. code-block:: python

import ee, geetools

ee.Initialize()

sequence = ee.List([1, 2, 2, 3])
images = sequence.map(lambda i: ee.Image(ee.Number(i)).rename(ee.Number(i).int().format()))
image = ee.Image.geetools.fromList(images)
print(image.bandNames().getInfo())
> ee.ee_exception.EEException: Image.rename: Can't add a band named '2' to image because a band with this name already exists. Existing bands: [1, 2].
"""
bandNames = images.map(lambda i: ee.Image(i).bandNames()).flatten()
ic = ee.ImageCollection.fromImages(images)
return ic.toBands().rename(bandNames)

def byBands(
self,
regions: ee.featurecollection,
Expand Down
22 changes: 22 additions & 0 deletions tests/test_Image.py
Original file line number Diff line number Diff line change
Expand Up @@ -644,6 +644,28 @@ def test_plot_with_crs(self, s2_sr_vatican_2020, vatican, image_regression):
image_regression.check(image_byte.getvalue())


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

def test_from_list_unique(self):
"""Test using a list of unique band names."""
sequence = ee.List([1, 2, 3])
images = sequence.map(lambda i: ee.Image(ee.Number(i)).rename(ee.Number(i).int().format()))
image = ee.Image.geetools.fromList(images)
assert image.bandNames().getInfo() == ["1", "2", "3"]

def test_from_list_multiband(self):
"""Test using a list of multiband images."""
images = ee.List(
[
ee.Image([1, 2, 3]).rename(["1", "2", "3"]),
ee.Image([4, 5]).rename(["4", "5"]),
]
)
image = ee.Image.geetools.fromList(images)
assert image.bandNames().getInfo() == ["1", "2", "3", "4", "5"]


class TestPlotByRegions:
"""Test the ``plot_by_regions`` method."""

Expand Down
Loading