Skip to content

Commit

Permalink
docs: Updated image_processing.ipynb Tutorial
Browse files Browse the repository at this point in the history
refactor: Removed IllegalFormatError; Image._repr_jpeg now returns None if image has alpha channel
  • Loading branch information
Marsmaennchen221 committed Dec 8, 2023
1 parent dad2d2c commit 4c6bcc1
Show file tree
Hide file tree
Showing 5 changed files with 13 additions and 31 deletions.
10 changes: 5 additions & 5 deletions docs/tutorials/image_processing.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
"source": [
"from safeds.data.image.containers import Image\n",
"\n",
"plane = Image.from_png_file(\"data/plane.png\")\n",
"plane = Image.from_file(\"data/plane.png\")\n",
"plane"
]
},
Expand Down Expand Up @@ -175,7 +175,7 @@
"execution_count": null,
"outputs": [],
"source": [
"plane.adjust_color_balance(0.5)"
"# plane.adjust_color_balance(0.5)"
],
"metadata": {
"collapsed": false
Expand Down Expand Up @@ -280,7 +280,7 @@
"execution_count": null,
"outputs": [],
"source": [
"plane.find_edges()\n"
"# plane.find_edges()\n"
],
"metadata": {
"collapsed": false
Expand All @@ -289,7 +289,7 @@
{
"cell_type": "markdown",
"source": [
"13. Add gaussian noise to the `Image`. A higher `standard_deviation` will result in a noisier `Image`:\n"
"13. Add noise to the `Image`. A higher `standard_deviation` will result in a noisier `Image`:\n"
],
"metadata": {
"collapsed": false
Expand All @@ -300,7 +300,7 @@
"execution_count": null,
"outputs": [],
"source": [
"plane.add_gaussian_noise(standard_deviation=0.1)\n"
"plane.add_noise(standard_deviation=0.1)\n"
],
"metadata": {
"collapsed": false
Expand Down
13 changes: 5 additions & 8 deletions src/safeds/data/image/containers/_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
from torchvision.transforms.v2 import functional as func2
from torchvision.utils import save_image

from safeds.exceptions import ClosedBound, IllegalFormatError, OutOfBoundsError
from safeds.exceptions import ClosedBound, OutOfBoundsError


class Image:
Expand Down Expand Up @@ -84,22 +84,19 @@ def from_bytes(data: bytes, device: Device = _default_device) -> Image:
def __init__(self, image_tensor: Tensor, device: Device = _default_device) -> None:
self._image_tensor: Tensor = image_tensor.to(device)

def _repr_jpeg_(self) -> bytes:
def _repr_jpeg_(self) -> bytes | None:
"""
Return a JPEG image as bytes.
If the image has an alpha channel return None.
Returns
-------
jpeg : bytes
The image as JPEG.
Raises
------
IllegalFormatError
If the image has an alpha channel
"""
if self.channel == 4:
raise IllegalFormatError("png", "The image has an alpha channel which cannot be displayed in jpeg format. ")
return None
buffer = io.BytesIO()
save_image(self._image_tensor.to(torch.float32) / 255, buffer, format="jpeg")
buffer.seek(0)
Expand Down
2 changes: 0 additions & 2 deletions src/safeds/exceptions/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
ColumnLengthMismatchError,
ColumnSizeError,
DuplicateColumnNameError,
IllegalFormatError,
IllegalSchemaModificationError,
IndexOutOfBoundsError,
MissingValuesColumnError,
Expand Down Expand Up @@ -47,7 +46,6 @@
"UnknownColumnNameError",
"ValueNotPresentWhenFittedError",
"WrongFileExtensionError",
"IllegalFormatError",
# ML exceptions
"DatasetContainsTargetError",
"DatasetMissesDataError",
Expand Down
7 changes: 0 additions & 7 deletions src/safeds/exceptions/_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,10 +148,3 @@ class ColumnIsTargetError(IllegalSchemaModificationError):

def __init__(self, column_name: str) -> None:
super().__init__(f'Column "{column_name}" is the target column and cannot be removed.')


class IllegalFormatError(Exception):
"""Exception raised when a format is not legal."""

def __init__(self, formats: list[str] | str, reason: str = "") -> None:
super().__init__(f"This format is illegal. {reason}Use one of the following formats: {formats}")
12 changes: 3 additions & 9 deletions tests/safeds/data/image/containers/test_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import torch
from safeds.data.image.containers import Image
from safeds.data.tabular.containers import Table
from safeds.exceptions import IllegalFormatError, OutOfBoundsError
from safeds.exceptions import OutOfBoundsError
from syrupy import SnapshotAssertion
from torch.types import Device

Expand Down Expand Up @@ -104,16 +104,10 @@ def test_should_return_bytes(self, resource_path: str | Path, device: Device) ->
],
ids=["plane-png", "rgba-png"],
)
def test_should_raise_if_image_has_alpha_channel(self, resource_path: str | Path, device: Device) -> None:
def test_should_return_none_if_image_has_alpha_channel(self, resource_path: str | Path, device: Device) -> None:
_skip_if_device_not_available(device)
image = Image.from_file(resolve_resource_path(resource_path), device)
with pytest.raises(
IllegalFormatError,
match=r"This format is illegal. The image has an alpha channel which "
r"cannot be displayed in jpeg format. Use one of the following "
r"formats: png",
):
image._repr_jpeg_()
assert image._repr_jpeg_() is None


@pytest.mark.parametrize("device", _test_devices(), ids=_test_devices_ids())
Expand Down

0 comments on commit 4c6bcc1

Please sign in to comment.