Skip to content

Commit

Permalink
Create a single band image from a list of images (#347)
Browse files Browse the repository at this point in the history
  • Loading branch information
12rambau authored Oct 24, 2024
2 parents 40836aa + 1047d60 commit 65598b5
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
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 = ee.List(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

0 comments on commit 65598b5

Please sign in to comment.