diff --git a/geetools/Image.py b/geetools/Image.py index dd31ae72..8c0fab07 100644 --- a/geetools/Image.py +++ b/geetools/Image.py @@ -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, diff --git a/tests/test_Image.py b/tests/test_Image.py index 3beefc1d..a41010b8 100644 --- a/tests/test_Image.py +++ b/tests/test_Image.py @@ -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."""