diff --git a/src/safeds/data/image/containers/_image.py b/src/safeds/data/image/containers/_image.py index 3e0269c76..41309159e 100644 --- a/src/safeds/data/image/containers/_image.py +++ b/src/safeds/data/image/containers/_image.py @@ -222,6 +222,20 @@ def resize(self, new_width: int, new_height: int) -> Image: new_image._image = new_image._image.resize((new_width, new_height)) return new_image + def convert_to_grayscale(self) -> Image: + """ + Convert the image to grayscale. + + Returns + ------- + grayscale_image : Image + The grayscale image. + """ + data = io.BytesIO() + grayscale_image = self._image.convert("L") + grayscale_image.save(data, format=self._format.value) + return Image(data, self._format) + def crop(self, x: int, y: int, width: int, height: int) -> Image: """ Return an image that has been cropped to a given bounding rectangle. diff --git a/tests/resources/image/snapshot_heatmap_grayscale.png b/tests/resources/image/snapshot_heatmap_grayscale.png new file mode 100644 index 000000000..ca7f451c0 Binary files /dev/null and b/tests/resources/image/snapshot_heatmap_grayscale.png differ diff --git a/tests/safeds/data/image/containers/test_image.py b/tests/safeds/data/image/containers/test_image.py index f74603fe2..199892fc7 100644 --- a/tests/safeds/data/image/containers/test_image.py +++ b/tests/safeds/data/image/containers/test_image.py @@ -206,6 +206,22 @@ def test_should_return_resized_image( assert image.resize(new_width, new_height)._image.size == new_size +class TestConvertToGrayscale: + @pytest.mark.parametrize( + ("image", "expected"), + [ + ( + Image.from_png_file(resolve_resource_path("image/snapshot_heatmap.png")), + Image.from_png_file(resolve_resource_path("image/snapshot_heatmap_grayscale.png")), + ), + ], + ids=["grayscale"], + ) + def test_convert_to_grayscale(self, image: Image, expected: Image) -> None: + grayscale_image = image.convert_to_grayscale() + assert grayscale_image._image.tobytes() == expected._image.tobytes() + + class TestEQ: def test_should_be_equal(self) -> None: image = Image.from_png_file(resolve_resource_path("image/original.png"))