diff --git a/src/machinevisiontoolbox/base/types.py b/src/machinevisiontoolbox/base/types.py index df931c33..8cb1fc82 100644 --- a/src/machinevisiontoolbox/base/types.py +++ b/src/machinevisiontoolbox/base/types.py @@ -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``. @@ -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 @@ -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): diff --git a/tests/test_int_image_clip.py b/tests/test_int_image_clip.py new file mode 100644 index 00000000..7b04227d --- /dev/null +++ b/tests/test_int_image_clip.py @@ -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]