Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions src/machinevisiontoolbox/base/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,9 @@ class supported by NumPy, defaults to ``'uint8'``

* a floating point class, the pixel values are scaled from an input range of
[0.0, 1.0] to a range spanning zero to the maximum positive value of
``intclass``.
``intclass``. Values outside [0.0, 1.0] are clipped first, so 1.2 gives the
maximum value and -0.5 gives zero. Without this, they would wrap around to
an unrelated value.
* an integer class, the pixels are scaled and cast to ``intclass``. The
scale factor is the ratio of ``maxintval`` to the maximum positive value
of ``inclass``.
Expand All @@ -62,6 +64,8 @@ class supported by NumPy, defaults to ``'uint8'``
>>> int_image(im, 'int16')
>>> im = np.array([[False, True],[True, False]])
>>> int_image(im)
>>> im = np.array([-0.5, 0.5, 1.2])
>>> int_image(im) # values outside 0 to 1 are clipped

.. note:: Works for greyscale or color (arbitrary number of planes) image

Expand All @@ -79,7 +83,7 @@ class supported by NumPy, defaults to ``'uint8'``

elif np.issubdtype(image.dtype, np.floating):
# rescale to integer
scaled = image * np.float64(np.iinfo(intclass).max)
scaled = np.clip(image, 0.0, 1.0) * np.float64(np.iinfo(intclass).max)
return np.rint(scaled).astype(intclass)

elif np.issubdtype(image.dtype, np.integer):
Expand Down
26 changes: 26 additions & 0 deletions tests/test_int_image_clip.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
#!/usr/bin/env python
"""int_image() on floating point data outside the range 0 to 1."""

import numpy as np
import pytest

from machinevisiontoolbox.base.types import int_image


@pytest.mark.parametrize("dtype", [np.float32, np.float64])
def test_out_of_range_floats_are_clipped(dtype):
x = np.array([-0.5, 0.0, 0.5, 1.0, 1.2], dtype=dtype)
out = int_image(x, "uint8")
assert out.dtype == np.uint8
assert list(out) == [0, 0, 128, 255, 255]


def test_clipping_applies_to_uint16_and_to_color_arrays():
x = np.full((2, 2, 3), 2.0)
assert (int_image(x, "uint16") == 65535).all()
assert (int_image(-x, "uint16") == 0).all()


def test_values_in_range_are_unchanged():
x = np.linspace(0, 1, 11)
assert list(int_image(x, "uint8")) == [round(v * 255) for v in x]
Loading