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

feat: convert image to grayscale #366

Merged
merged 10 commits into from
Jun 16, 2023
14 changes: 14 additions & 0 deletions src/safeds/data/image/containers/_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,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)
alex-senger marked this conversation as resolved.
Show resolved Hide resolved
alex-senger marked this conversation as resolved.
Show resolved Hide resolved
return Image(data, self._format)

def flip_vertically(self) -> Image:
"""
Flip the image vertically (horizontal axis, flips up-down and vice versa).
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
16 changes: 16 additions & 0 deletions tests/safeds/data/image/containers/test_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"))
Expand Down