Skip to content

Commit

Permalink
feat: convert image to grayscale (#366)
Browse files Browse the repository at this point in the history
Closes #287

### Summary of Changes

* feat: Added method that returns converted grayscale image but leaves
the original unchanged.

---------

Co-authored-by: megalinter-bot <129584137+megalinter-bot@users.noreply.github.com>
  • Loading branch information
jxnior01 and megalinter-bot committed Jun 16, 2023
1 parent c642176 commit 1312fe7
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
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 @@ -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.
Expand Down
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

0 comments on commit 1312fe7

Please sign in to comment.