π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(core)!: convert ImageModule inputs and outputs by dtype, channel count and range (#5239)
Dmytro Mishkincf2cdb7f7a88
diff --git a/changelog.d/5239.breaking.md b/changelog.d/5239.breaking.mdnew file mode 100644index 000000000..8f1523641--- /dev/null+++ b/changelog.d/5239.breaking.md@@ -0,0 +1,16 @@+`ImageModule`, `ImageSequential` and the augmentation containers now convert NumPy, PIL and+image-path inputs by their dtype, and return channels-last arrays for `output_type="numpy"`.+`to_tensor` used to divide every input by 255 whatever its dtype: a float image already in `[0, 1]`+shrank 255 times (0.5 became 0.00196), a `uint16` image or 16-bit PNG reached 257, and a `bool` mask+became 1/255. Now an integer input is divided by the maximum of its dtype (`uint8` by 255 as before,+`uint16` by 65535, `int16` by 32767), a `bool` array becomes 0 and 1, and a floating array keeps its+values; `uint8` inputs convert to the same values as before, and a PIL input now takes the default+dtype, as a NumPy input already did (it was always `float32`). A signed integer image maps to+`[iinfo.min / iinfo.max, 1]`, so its negative values stay negative (`int8` -128 gives -128 / 127).+`output_type="numpy"` (and `to_numpy`) used to return the `(C, H, W)` / `(B, C, H, W)` layout of the+output tensor, which `to_tensor` read back as channels-last and transposed; it now returns `(H, W,+C)` / `(B, H, W, C)`, the layout NumPy inputs use, with the tensor's values, so a float output fed+back in converts to the same tensor. Every 3-D or 4-D output is treated as an image, so a non-image+element of a tuple output (such as a `(B, N, 4)` box tensor) moves its axis too; modules with+several outputs are #5210. Code that expected the old layout moves the channel axis with+`np.moveaxis(out, -1, -3)`.diff --git a/changelog.d/5239.fixed.md b/changelog.d/5239.fixed.mdnew file mode 100644index 000000000..ba77b72e1--- /dev/null+++ b/changelog.d/5239.fixed.md@@ -0,0 +1,15 @@+`ImageModule`, `ImageSequential` and the augmentation containers accept grayscale and other+non-RGB PIL images (modes `L`, `I;16`, `I;16B`, `I`, `F`, `1`), which used to crash `to_tensor`+with a `permute` or byte-order error, and convert them to one-channel tensors like a grayscale NumPy+array; palette images (`P`, `PA`) are converted to RGB, or RGBA with transparency, instead of+yielding their palette indices. `output_type="pil"` / `to_pil` turn a one-channel tensor into a+mode `"L"` image instead of raising `TypeError: Cannot handle this data type`, and reject+multi-channel integer tensors PIL cannot store with a message naming the dtype. `to_pil`, `show()`+and `save()` clamp a float image to `[0, 1]` and round it to 8 bits on the CPU, the conversion the+`kornia.models` `save` methods already used: a value above 1 used to wrap modulo 256 (1.1 became+24), a negative value gave 0 or 231 depending on the method and the torch version, and a `uint8`+image was multiplied by 255 (200 became 56). A negative value now gives 0 on every torch version and+a `uint8` image keeps its values. In-range float pixels change by at most one step, from truncation+to rounding (0.999 now gives 255 instead of 254). `show()` renders bfloat16 outputs, which used to+raise `TypeError: Got unsupported ScalarType BFloat16`. Non-image NumPy arguments of+`AugmentationSequential` (masks, boxes) are still converted with the image rule: #5236.diff --git a/kornia/core/mixin/image_module.py b/kornia/core/mixin/image_module.pyindex 12665df69..918b80ad2 100644--- a/kornia/core/mixin/image_module.py+++ b/kornia/core/mixin/image_module.py@@ -29,11 +29,66 @@ from kornia.core.external import numpy as npfrom kornia.core.utils import is_exporting+def _image_to_float(image: torch.Tensor) -> torch.Tensor:+ """Convert an image tensor to floating point, scaling an integer image by the maximum of its dtype.++ A ``uint8`` image is divided by 255, a ``uint16`` one by 65535, and so on; a ``bool`` image becomes 0 and 1; a+ floating image is returned unchanged, since it is taken to be in ``[0, 1]`` already. Integer and ``bool`` images+ become the default floating dtype. A signed integer image maps to ``[iinfo.min / iinfo.max, 1]``: negative values+ stay negative, and the minimum lands just below -1 (``int8`` -128 gives -128 / 127). The division runs in float32+ when the default dtype is narrower, so a ``float16`` default still maps the ``uint16`` maximum 65535, which is+ above the largest finite ``float16`` (65504), to 1 rather than ``inf``.+ """+ if image.is_floating_point():+ return image+ default_dtype = torch.get_default_dtype()+ if image.dtype == torch.bool:+ return image.to(default_dtype)+ working_dtype = torch.promote_types(default_dtype, torch.float32)+ return (image.to(working_dtype) / float(torch.iinfo(image.dtype).max)).to(default_dtype)+++def _array_to_float_image(array: Any) -> torch.Tensor:+ """Convert a channels-last NumPy image to a channels-first tensor scaled by :func:`_image_to_float`."""+ from kornia.image.utils import image_to_tensor # pylint: disable=C0415++ if not array.dtype.isnative: # torch.from_numpy rejects big-endian data, such as PIL's "I;16B" mode+ array = array.astype(array.dtype.newbyteorder("="))+ return _image_to_float(image_to_tensor(array))+++# Non-``uint8`` dtypes PIL stores as a one-channel image (modes "1", "I;16" and "I"); ``uint8`` takes 1 to 4 channels.+_PIL_ONE_CHANNEL_DTYPES = (torch.bool, torch.int8, torch.int16, torch.uint16, torch.int32, torch.uint32)+++def _to_uint8_image(image: torch.Tensor) -> torch.Tensor:+ """Convert a floating image in ``[0, 1]`` to ``uint8`` for display or an 8-bit file.++ Values are clamped to ``[0, 1]``, scaled by 255 and rounded, so an image that overshoots the range saturates+ instead of wrapping modulo 256 (1.1 would otherwise become 24, black where it should be white), and a negative+ value becomes 0 on every torch version. A half-precision image is scaled in float32, so the product is not rounded+ to the half dtype before ``round`` (``float16`` 0.0058823 is 1.49998 / 255 and gives 1, not 2). Non-floating+ images pass through untouched, so a ``uint8`` or ``uint16`` image keeps its values.+ """+ if not image.is_floating_point():+ return image+ working_dtype = torch.promote_types(image.dtype, torch.float32)+ return (image.detach().to(working_dtype).clamp(0.0, 1.0) * 255).round().to(torch.uint8)++class ImageModuleMixIn:"""A MixIn that handles image-based operations.This modules accepts multiple input and output data types, provides end-to-end visualization, file saving features.Note that this MixIn fits the classes that return one image tensor only.++ Non-tensor inputs are converted by :meth:`to_tensor`: a NumPy array of shape :math:`(H, W)`, :math:`(H, W, C)`+ or :math:`(B, H, W, C)`, a PIL image or an image path becomes a :math:`(C, H, W)` or :math:`(B, C, H, W)` tensor.+ An integer image is scaled by the maximum of its dtype (``uint8`` by 255, ``uint16`` by 65535; a signed image keeps+ its negative values), a ``bool`` image becomes 0 and 1, and a floating image keeps its values. Tensors pass through+ unchanged. ``output_type="numpy"`` returns channels-last arrays with the values of the output tensor, so a floating+ output fed back in converts to the same tensor. ``output_type="pil"``, :meth:`show` and :meth:`save` clamp a+ floating image to ``[0, 1]`` and round it to 8 bits on the CPU, and pass a ``uint8`` image through with its values."""_output_image: Any@@ -141,7 +196,14 @@ class ImageModuleMixIn:def to_tensor(self, x: Any) -> torch.Tensor:"""Convert input to tensor.- Supports image path, numpy array, PIL image, and raw tensor.+ Supports image path, numpy array, PIL image, and raw tensor. A NumPy array of shape :math:`(H, W)`,+ :math:`(H, W, C)` or :math:`(B, H, W, C)` becomes :math:`(C, H, W)` or :math:`(B, C, H, W)`, with one channel+ for :math:`(H, W)`; a PIL image converts like its NumPy array, except that a palette image (mode ``P`` or+ ``PA``) is converted to RGB, or RGBA when it has transparency, first. An integer image is divided by the maximum+ of its dtype (``uint8`` by 255, ``uint16`` by 65535, a PIL mode ``I`` image by the ``int32`` maximum); a signed+ image maps to ``[iinfo.min / iinfo.max, 1]``, so its negative values stay negative. A ``bool`` image becomes 0+ and 1, and a floating image keeps its values; integer and ``bool`` images become the default floating dtype. A+ tensor is returned unchanged.Args:x: The input to convert.@@ -153,20 +215,27 @@ class ImageModuleMixIn:if isinstance(x, str):from kornia.io import ImageLoadType, load_image # pylint: disable=C0415- return load_image(x, ImageLoadType.UNCHANGED) / 255+ return _image_to_float(load_image(x, ImageLoadType.UNCHANGED))if isinstance(x, torch.Tensor):return xif isinstance(x, np.ndarray): # type: ignore- from kornia.image.utils import image_to_tensor # pylint: disable=C0415-- return image_to_tensor(x) / 255+ return _array_to_float_image(x)if isinstance(x, Image.Image): # type: ignore- return torch.from_numpy(np.array(x)).permute(2, 0, 1).float() / 255 # type: ignore+ if x.mode in ("P", "PA"): # palette indices are not intensities+ x = x.convert("RGBA" if x.mode == "PA" or "transparency" in x.info else "RGB")+ return _array_to_float_image(np.array(x)) # type: ignoreraise TypeError("Input type not supported")def to_numpy(self, x: Any) -> "np.array": # type: ignore"""Convert input to numpy array.+ A :math:`(C, H, W)` or :math:`(B, C, H, W)` tensor becomes a channels-last :math:`(H, W, C)` or+ :math:`(B, H, W, C)` array with the same values, the layout :meth:`to_tensor` accepts, so a floating array+ converts back to the same tensor. A tensor of any other rank keeps its shape. Every 3-D or 4-D tensor is taken+ to be an image, so a non-image element of a tuple output, such as a :math:`(B, N, 4)` box tensor, is moved to+ channels-last too; modules with several outputs are tracked in+ `#5210 <https://github.com/kornia/kornia/issues/5210>`_.+Args:x: The input to convert.@@ -175,7 +244,12 @@ class ImageModuleMixIn:"""if isinstance(x, torch.Tensor):- return x.cpu().detach().numpy()+ x = x.detach().cpu()+ if x.dim() == 3:+ x = x.permute(1, 2, 0)+ elif x.dim() == 4:+ x = x.permute(0, 2, 3, 1)+ return x.contiguous().numpy()if isinstance(x, np.ndarray): # type: ignorereturn xif isinstance(x, Image.Image): # type: ignore@@ -185,6 +259,10 @@ class ImageModuleMixIn:def to_pil(self, x: Any) -> "Image.Image": # type: ignore"""Convert input to PIL image.+ A floating image is clamped to ``[0, 1]`` and rounded to 8 bits on the CPU; a ``uint8`` image keeps its+ values. A one-channel image becomes a mode ``"L"`` image, and a :math:`(B, C, H, W)` batch a list of images.+ Other integer and ``bool`` images convert only with one channel (PIL modes ``"I"``, ``"I;16"`` and ``"1"``).+Args:x: The input to convert.@@ -193,20 +271,31 @@ class ImageModuleMixIn:"""if isinstance(x, torch.Tensor):- x = x.cpu().detach() * 255if x.dim() == 3:- x = x.permute(1, 2, 0)- return Image.fromarray(x.byte().numpy()) # type: ignore+ return self._chw_to_pil(x)if x.dim() == 4:- x = x.permute(0, 2, 3, 1)- return [Image.fromarray(_x.byte().numpy()) for _x in x] # type: ignore- raise NotImplementedError+ return [self._chw_to_pil(_x) for _x in x] # type: ignore+ raise NotImplementedError(+ f"to_pil converts a (C, H, W) or (B, C, H, W) tensor, got a tensor of shape {tuple(x.shape)}."+ )if isinstance(x, np.ndarray): # type: ignore- raise NotImplementedError+ raise NotImplementedError("to_pil does not convert NumPy arrays; convert them with to_tensor first.")if isinstance(x, Image.Image): # type: ignorereturn xraise TypeError("Input type not supported")+ @staticmethod+ def _chw_to_pil(image: torch.Tensor) -> "Image.Image": # type: ignore+ image = _to_uint8_image(image.detach().cpu())+ if image.dtype != torch.uint8 and (image.shape[0] != 1 or image.dtype not in _PIL_ONE_CHANNEL_DTYPES):+ raise NotImplementedError(+ "to_pil converts a float or uint8 image, or a one-channel bool, int8, int16, int32, uint16 or uint32 "+ f"image; got a {image.shape[0]}-channel {image.dtype} tensor."+ )+ if image.shape[0] == 1:+ return Image.fromarray(image[0].numpy()) # type: ignore+ return Image.fromarray(image.permute(1, 2, 0).numpy()) # type: ignore+def _detach_tensor(self, output_image: Union[torch.Tensor, List[torch.Tensor], Tuple[torch.Tensor]]) -> Union[torch.Tensor, List[torch.Tensor], Tuple[torch.Tensor]]:@@ -253,10 +342,10 @@ class ImageModuleMixIn:raise ValueErrorif backend == "pil" and display:- Image.fromarray((out_image.permute(1, 2, 0).squeeze().numpy() * 255).astype(np.uint8)).show() # type: ignore+ Image.fromarray(_to_uint8_image(out_image).permute(1, 2, 0).squeeze().numpy()).show() # type: ignorereturn Noneif backend == "pil":- return Image.fromarray((out_image.permute(1, 2, 0).squeeze().numpy() * 255).astype(np.uint8)) # type: ignore+ return Image.fromarray(_to_uint8_image(out_image).permute(1, 2, 0).squeeze().numpy()) # type: ignoreraise ValueError(f"Unsupported backend `{backend}`.")def save(self, name: Optional[str] = None, n_row: Optional[int] = None) -> None:@@ -284,4 +373,4 @@ class ImageModuleMixIn:if n_row is None:n_row = math.ceil(output_image.shape[0] ** 0.5)out_image = make_grid(output_image, n_row, padding=2)- write_image(name, out_image.mul(255.0).byte())+ write_image(name, _to_uint8_image(out_image))diff --git a/kornia/models/base.py b/kornia/models/base.pyindex 9f7a01248..04919fb79 100644--- a/kornia/models/base.py+++ b/kornia/models/base.py@@ -28,6 +28,7 @@ from torch import nnfrom kornia.core.download import load_state_dict_from_urlfrom kornia.core.external import PILImage as Image+from kornia.core.mixin.image_module import _to_uint8_imagefrom kornia.image.utils import tensor_to_imagefrom kornia.io import write_image@@ -36,27 +37,15 @@ logger = logging.getLogger(__name__)ModelConfig = TypeVar("ModelConfig")-def _to_writable_png(image: torch.Tensor) -> torch.Tensor:- """Convert a visualization tensor to the dtype ``write_image`` accepts for PNG.+def _write_png_batch(path_stem: str, image: torch.Tensor) -> None:+ """Write one image, or one file per item of a batch.``visualize`` returns float images in ``[0, 1]``, but ``write_image`` writesPNG only for ``uint8``/``uint16``; float32 is TIFF-only and every other- float dtype is rejected outright.-- These are pictures for a human to look at, not data to round-trip, so the- conversion is to ``uint8`` -- the same thing ``ImageModule`` already does- before handing a tensor to PIL. Values are clamped first: a visualization- that overshoots ``[0, 1]`` would otherwise wrap and put black where it- should be white. Non-float images pass through untouched, so a ``uint8``- or ``uint16`` visualization is written as-is.- """- if not image.is_floating_point():- return image- return (image.detach().clamp(0.0, 1.0) * 255).round().to(torch.uint8)---def _write_png_batch(path_stem: str, image: torch.Tensor) -> None:- """Write one image, or one file per item of a batch.+ float dtype is rejected outright. These are pictures for a human to look at,+ not data to round-trip, so a float image is converted to ``uint8`` the way+ ``ImageModule`` hands a tensor to PIL: clamped, scaled and rounded. A+ ``uint8`` or ``uint16`` visualization is written as-is.``write_image`` takes ``(3, H, W)``, ``(1, H, W)`` or ``(H, W)``, but thecontainers document their inputs as ``(B, 3, H, W)`` and passed the batch@@ -67,7 +56,7 @@ def _write_png_batch(path_stem: str, image: torch.Tensor) -> None:A batch of one still gets an index suffix, so a caller does not have toguess whether a file will be ``name.png`` or ``name_0.png``."""- image = _to_writable_png(image)+ image = _to_uint8_image(image)if image.dim() == 4:for i, item in enumerate(image):write_image(f"{path_stem}_{i}.png", item)diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.pyindex b872d86c7..c4426b587 100644--- a/tests/augmentation/container/test_augmentation_sequential.py+++ b/tests/augmentation/container/test_augmentation_sequential.py@@ -1490,8 +1490,7 @@ class TestConventionAugmentationSequential(BaseTester):assert cached.device == out_image.device # no device-to-host copy in the forward passself.assert_close(cached, out_image.detach())- if dtype != torch.bfloat16: # `.show()` renders through `Tensor.numpy()`, which has no bfloat16 support- assert isinstance(aug.show(display=False), PILImage.Image)+ assert isinstance(aug.show(display=False), PILImage.Image)path = tmp_path / "augmented.jpg"aug.save(name=str(path))assert path.is_file()diff --git a/tests/augmentation/container/test_sequential_aug.py b/tests/augmentation/container/test_sequential_aug.pyindex c71fae330..a20d4672b 100644--- a/tests/augmentation/container/test_sequential_aug.py+++ b/tests/augmentation/container/test_sequential_aug.py@@ -115,7 +115,7 @@ class TestConventionImageSequential(BaseTester):output = aug(image, output_type=output_type)if output_type == "numpy":- assert output.shape == (2, 3, 6, 8) and not isinstance(output, torch.Tensor)+ assert output.shape == (2, 6, 8, 3) and not isinstance(output, torch.Tensor) # channels-last (#5207)else:assert len(output) == 2 and all(isinstance(out, PILImage.Image) for out in output)cached = aug._output_image@@ -125,8 +125,7 @@ class TestConventionImageSequential(BaseTester):if container == "AugmentationSequential":assert cached.device == image.device # no device-to-host copy in the forward pass (#4918)- if dtype != torch.bfloat16: # `.show()` renders through `Tensor.numpy()`, which has no bfloat16 support- assert isinstance(aug.show(display=False), PILImage.Image)+ assert isinstance(aug.show(display=False), PILImage.Image)output_path = tmp_path / "output.png"aug.save(name=str(output_path))assert output_path.is_file()diff --git a/tests/core/test_module.py b/tests/core/test_module.pyindex 279f147aa..a275e9a6d 100644--- a/tests/core/test_module.py+++ b/tests/core/test_module.py@@ -26,6 +26,7 @@ from PIL import Image as PILImagefrom kornia.augmentation import ImageSequential as AugmentationImageSequentialfrom kornia.core.module import ImageModule, ImageModuleMixIn, ImageSequential+from kornia.io import write_imagefrom testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_available@@ -62,6 +63,8 @@ class TestImageModuleMixIn:tensor = img_module.to_tensor(sample_numpy)assert isinstance(tensor, (torch.Tensor,))assert tensor.shape == (3, 100, 100)+ # A floating array is already in [0, 1]: it is transposed, not rescaled (#5207).+ torch.testing.assert_close(tensor, torch.from_numpy(sample_numpy).permute(2, 0, 1), rtol=0.0, atol=0.0)def test_to_tensor_tensor(self, img_module, sample_tensor):tensor = img_module.to_tensor(sample_tensor)@@ -70,7 +73,8 @@ class TestImageModuleMixIn:def test_to_numpy_tensor(self, img_module, sample_tensor):array = img_module.to_numpy(sample_tensor)assert isinstance(array, (np.ndarray,))- assert array.shape == (3, 100, 100)+ # Channels-last, the layout `to_tensor` accepts (#5207).+ assert array.shape == (100, 100, 3)def test_to_numpy_numpy(self, img_module, sample_numpy):array = img_module.to_numpy(sample_numpy)@@ -274,11 +278,11 @@ class TestLazyOutputCache(BaseTester):image = torch.rand(1, 3, 6, 8, device=device, dtype=dtype, requires_grad=True)output = module(image)cached = module._output_image- expected = (output[0].detach().cpu().permute(1, 2, 0) * 255).byte().numpy()- if dtype != torch.bfloat16: # NumPy does not support bfloat16.- rendered = module.show(display=False)- assert isinstance(rendered, PILImage.Image)- np.testing.assert_array_equal(np.asarray(rendered), expected)+ working = output[0].detach().to(torch.promote_types(dtype, torch.float32))+ expected = (working.clamp(0.0, 1.0) * 255).round().to(torch.uint8).cpu().permute(1, 2, 0).numpy()+ rendered = module.show(display=False)+ assert isinstance(rendered, PILImage.Image)+ np.testing.assert_array_equal(np.asarray(rendered), expected)path = tmp_path / "cached.png"module.save(name=str(path))with PILImage.open(path) as saved:@@ -295,12 +299,14 @@ class TestLazyOutputCache(BaseTester):expected = image.sigmoid().detach().cpu()if output_type == "numpy":assert isinstance(output, np.ndarray)- np.testing.assert_array_equal(output, expected.numpy())+ np.testing.assert_array_equal(output, expected.permute(0, 2, 3, 1).numpy())else:assert isinstance(output, list)assert len(output) == 1assert isinstance(output[0], PILImage.Image)- np.testing.assert_array_equal(np.asarray(output[0]), (expected[0].permute(1, 2, 0) * 255).byte().numpy())+ working = expected[0].to(torch.promote_types(dtype, torch.float32))+ rendered = (working.clamp(0.0, 1.0) * 255).round().to(torch.uint8).permute(1, 2, 0).numpy()+ np.testing.assert_array_equal(np.asarray(output[0]), rendered)@pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)def test_export_preserves_cache_4957(self, device, dtype):@@ -317,3 +323,228 @@ class TestLazyOutputCache(BaseTester):exported = torch.export.export(module, (image,), strict=True)self.assert_close(exported.module()(image), expected)assert module._output_image is cached+++class _Identity(ImageModule):+ def forward(self, x):+ return x+++# The #5209 repro row: truncated (0.999), a half step (0.5), above the range (1.1), below it (-0.1), and the ends.+_ROW = [0.999, 0.5, 1.1, -0.1, 0.0, 1.0]+_ROW_UINT8 = [255, 128, 255, 0, 0, 255]+++class TestImageModuleConversions(BaseTester):+ """Value and layout contract of the ``ImageModule`` input and output conversions."""++ @pytest.mark.parametrize("half", [torch.float16, torch.bfloat16])+ def test_half_images_round_like_their_exact_value_5209(self, half):+ # Every half value in [0, 1]: the 8-bit pixel is round(v * 255) of the exact value, so the product must not be+ # rounded to the half dtype first (float16 0.0058823 * 255 is 1.49998, which float16 rounds up to 1.5).+ from kornia.core.mixin.image_module import _to_uint8_image++ bits = torch.arange(-(2**15), 2**15, dtype=torch.int32).to(torch.int16)+ values = bits.view(half)+ values = values[values.isfinite() & (values >= 0) & (values <= 1)]+ expected = (values.double() * 255).round().to(torch.uint8)+ assert torch.equal(_to_uint8_image(values), expected)++ @pytest.mark.parametrize("np_dtype", [np.uint8, np.uint16, np.int8, np.int16, np.int32])+ def test_to_tensor_scales_integer_numpy_by_dtype_max_5207(self, np_dtype):+ info = np.iinfo(np_dtype)+ values = [0, info.max // 2, info.max] if info.min == 0 else [info.min, -1, 0, info.max // 2, info.max]+ pixel = np.array(values, dtype=np_dtype)+ image = np.broadcast_to(pixel, (2, 4, len(values))).copy() # (H, W, C), every pixel is `pixel`+ out = _Identity().to_tensor(image)+ expected = torch.tensor(pixel.astype(np.float64) / info.max, dtype=torch.float32).view(-1, 1, 1)+ self.assert_close(out, expected.expand(len(values), 2, 4))+ if info.min < 0: # a signed minimum lands just below -1: int8 -128 -> -128 / 127+ assert out[0, 0, 0].item() == pytest.approx(info.min / info.max)++ @pytest.mark.parametrize("default_dtype", [torch.float16, torch.bfloat16])+ @pytest.mark.parametrize("np_dtype", [np.uint16, np.int32])+ def test_to_tensor_scales_in_float32_under_a_half_default_dtype_5207(self, np_dtype, default_dtype):+ # 65535 and 2**31 - 1 overflow float16 (largest finite 65504): converting before dividing gave inf.+ info = np.iinfo(np_dtype)+ pixel = np.array([0, 1, 65504, 65535, info.max], dtype=np_dtype)+ image = np.broadcast_to(pixel, (2, 4, len(pixel))).copy() # (H, W, C), every pixel is `pixel`+ previous = torch.get_default_dtype()+ torch.set_default_dtype(default_dtype)+ try:+ out = _Identity().to_tensor(image)+ finally:+ torch.set_default_dtype(previous)+ assert out.dtype == default_dtype+ assert torch.isfinite(out).all()+ expected = torch.tensor(pixel.astype(np.float64) / info.max).to(default_dtype).view(-1, 1, 1)+ self.assert_close(out, expected.expand(len(pixel), 2, 4), rtol=0.0, atol=0.0)++ @pytest.mark.parametrize("np_dtype", [np.float16, np.float32, np.float64])+ def test_to_tensor_passes_floating_numpy_through_5207(self, np_dtype):+ image = np.random.default_rng(0).random((2, 4, 3)).astype(np_dtype)+ out = _Identity().to_tensor(image)+ self.assert_close(out, torch.from_numpy(image).permute(2, 0, 1), rtol=0.0, atol=0.0)++ def test_to_tensor_maps_bool_numpy_to_zero_one_5207(self):+ mask = np.array([[True, False, True], [False, True, False]])+ out = _Identity().to_tensor(mask)+ self.assert_close(out, torch.tensor([[[1.0, 0.0, 1.0], [0.0, 1.0, 0.0]]]), rtol=0.0, atol=0.0)++ @pytest.mark.parametrize(+ "shape, expected_shape",+ [((4, 6), (1, 4, 6)), ((4, 6, 1), (1, 4, 6)), ((4, 6, 3), (3, 4, 6)), ((2, 4, 6, 3), (2, 3, 4, 6))],+ )+ def test_to_tensor_numpy_layouts_5207(self, shape, expected_shape):+ image = np.arange(np.prod(shape), dtype=np.uint8).reshape(shape)+ channels_first = image[None] if image.ndim == 2 else np.moveaxis(image, -1, -3)+ out = _Identity().to_tensor(image)+ assert out.shape == expected_shape+ self.assert_close(out, torch.from_numpy(channels_first.astype(np.float32) / 255))++ def test_to_tensor_path_5207(self, tmp_path):+ path = tmp_path / "rgb.png"+ PILImage.new("RGB", (6, 4), (255, 51, 0)).save(path)+ out = _Identity().to_tensor(str(path))+ self.assert_close(out, torch.tensor([1.0, 0.2, 0.0]).view(3, 1, 1).expand(3, 4, 6))++ def test_to_tensor_16_bit_path_5207(self, tmp_path):+ path = tmp_path / "rgb16.png"+ write_image(str(path), torch.tensor([65535, 13107, 0], dtype=torch.uint16).view(3, 1, 1).expand(3, 4, 6))+ out = _Identity().to_tensor(str(path))+ self.assert_close(out, torch.tensor([1.0, 0.2, 0.0]).view(3, 1, 1).expand(3, 4, 6))++ def test_numpy_output_round_trips_through_numpy_input_5207(self):+ module = _Identity()+ image = np.random.default_rng(0).integers(0, 256, (4, 6, 3), dtype=np.uint8)+ first = module(image, output_type="numpy")+ # The numpy output is channels-last like the numpy input, in the [0, 1] range of the converted tensor.+ assert first.shape == image.shape+ np.testing.assert_array_equal(first, (image / 255).astype(np.float32))+ second = module(first, output_type="numpy")+ np.testing.assert_array_equal(second, first)++ @pytest.mark.parametrize("shape", [(3, 4, 6), (1, 4, 6), (2, 3, 4, 6), (2, 1, 4, 6)])+ def test_to_numpy_is_the_inverse_of_to_tensor_5207(self, shape, device, dtype):+ if dtype == torch.bfloat16:+ pytest.skip("NumPy has no bfloat16")+ module = _Identity()+ image = torch.rand(shape, device=device, dtype=dtype)+ array = module.to_numpy(image)+ assert array.shape == (*shape[:-3], *shape[-2:], shape[-3])+ self.assert_close(module.to_tensor(array), image.cpu(), rtol=0.0, atol=0.0)++ @pytest.mark.parametrize(+ "mode, fill, expected",+ [+ ("L", 51, [0.2]),+ ("I;16", 65535, [1.0]),+ ("I;16B", 65535, [1.0]),+ ("I", 2**31 - 1, [1.0]),+ ("F", 0.25, [0.25]),+ ("1", 1, [1.0]),+ ("LA", (51, 255), [0.2, 1.0]),+ ("RGB", (255, 51, 0), [1.0, 0.2, 0.0]),+ ("RGBA", (255, 51, 0, 255), [1.0, 0.2, 0.0, 1.0]),+ ],+ )+ def test_to_tensor_pil_modes_5208(self, mode, fill, expected):+ out = _Identity().to_tensor(PILImage.new(mode, (6, 4), fill))+ expected = torch.tensor(expected).view(-1, 1, 1).expand(len(expected), 4, 6)+ self.assert_close(out, expected)++ @pytest.mark.parametrize(+ "mode, fill, transparency, expected",+ [+ ("P", 1, None, [1.0, 0.0, 0.0]),+ ("P", 1, 0, [1.0, 0.0, 0.0, 1.0]),+ ("PA", (1, 51), None, [1.0, 0.0, 0.0, 0.2]),+ ],+ )+ def test_to_tensor_pil_palette_converts_to_colors_5208(self, mode, fill, transparency, expected):+ image = PILImage.new(mode, (6, 4), fill)+ image.putpalette([0, 0, 0, 255, 0, 0] + [0] * (256 * 3 - 6)) # index 1 is red+ if transparency is not None:+ image.info["transparency"] = transparency+ out = _Identity().to_tensor(image)+ self.assert_close(out, torch.tensor(expected).view(-1, 1, 1).expand(len(expected), 4, 6))++ def test_to_pil_one_channel_is_mode_l_5208(self, device, dtype):+ module = _Identity()+ image = torch.tensor([0.0, 0.2, 1.0], device=device, dtype=dtype).view(1, 1, 3).expand(1, 2, 3)+ pil = module.to_pil(image)+ assert pil.mode == "L"+ np.testing.assert_array_equal(np.asarray(pil), [[0, 51, 255], [0, 51, 255]])+ batch = module.to_pil(image[None].expand(2, 1, 2, 3))+ assert [im.mode for im in batch] == ["L", "L"]+ (converted,) = module(image[None], output_type="pil")+ assert converted.mode == "L"+ np.testing.assert_array_equal(np.asarray(converted), [[0, 51, 255], [0, 51, 255]])++ def test_to_pil_rejects_other_inputs_with_a_message_5208(self):+ module = _Identity()+ with pytest.raises(NotImplementedError, match=r"\(C, H, W\)"):+ module.to_pil(torch.rand(4, 6))+ with pytest.raises(NotImplementedError, match="NumPy"):+ module.to_pil(np.zeros((4, 6, 3), np.uint8))++ def _row_image(self, device, dtype):+ return torch.tensor(_ROW, device=device, dtype=dtype).view(1, 1, 6).expand(3, 2, 6).contiguous()++ def test_to_pil_clamps_and_rounds_5209(self, device, dtype):+ pil = _Identity().to_pil(self._row_image(device, dtype))+ assert pil.mode == "RGB"+ pixels = np.asarray(pil)+ for channel in range(3):+ np.testing.assert_array_equal(pixels[:, :, channel], [_ROW_UINT8, _ROW_UINT8])++ def test_show_clamps_and_rounds_5209(self, device, dtype):+ module = _Identity()+ module(self._row_image(device, dtype))+ shown = module.show(display=False)+ np.testing.assert_array_equal(np.asarray(shown)[:, :, 0], [_ROW_UINT8, _ROW_UINT8])++ def test_save_clamps_and_rounds_5209(self, device, dtype, tmp_path):+ module = _Identity()+ module(self._row_image(device, dtype))+ path = tmp_path / "row.png"+ module.save(name=str(path))+ with PILImage.open(path) as saved:+ np.testing.assert_array_equal(np.asarray(saved)[:, :, 0], [_ROW_UINT8, _ROW_UINT8])++ def test_integer_image_is_not_rescaled_5209(self, device, tmp_path):+ module = _Identity()+ image = torch.full((3, 2, 2), 200, dtype=torch.uint8, device=device)+ assert np.asarray(module.to_pil(image)).tolist() == [[[200] * 3] * 2] * 2+ (converted,) = module(image[None], output_type="pil")+ assert np.asarray(converted).tolist() == [[[200] * 3] * 2] * 2+ module(image)+ assert np.asarray(module.show(display=False)).tolist() == [[[200] * 3] * 2] * 2+ path = tmp_path / "u8.png"+ module.save(name=str(path))+ with PILImage.open(path) as saved:+ assert np.asarray(saved).tolist() == [[[200] * 3] * 2] * 2++ @pytest.mark.parametrize(+ "torch_dtype, channels", [(torch.uint16, 3), (torch.int32, 3), (torch.int64, 3), (torch.int64, 1)]+ )+ def test_to_pil_rejects_integer_images_pil_cannot_store_5209(self, torch_dtype, channels):+ image = torch.zeros(channels, 2, 2, dtype=torch_dtype)+ with pytest.raises(NotImplementedError, match=f"{channels}-channel {torch_dtype}"):+ _Identity().to_pil(image)++ def test_to_pil_show_save_agree_on_float16_ties_5209(self, device, tmp_path):+ # x * 255 lands on exact .5 ties in float16 (0.00196 -> 0.5). All three methods round on the CPU, half to even:+ # MPS on torch 2.5.1 rounds ties away from zero, so rounding on the device made `to_pil` differ from the others.+ generator = torch.Generator().manual_seed(0)+ image = torch.rand(3, 32, 32, generator=generator).to(device=device, dtype=torch.float16)+ image[:, 0, 0] = 0.00196+ module = _Identity()+ module(image)+ pil = np.asarray(module.to_pil(image))+ assert pil[0, 0].tolist() == [0, 0, 0]+ np.testing.assert_array_equal(pil, np.asarray(module.show(display=False)))+ path = tmp_path / "ties.png"+ module.save(name=str(path))+ with PILImage.open(path) as saved:+ np.testing.assert_array_equal(pil, np.asarray(saved))