diff --git a/skimage/util/__init__.py b/skimage/util/__init__.py index 2500469b..5aee7337 100644 --- a/skimage/util/__init__.py +++ b/skimage/util/__init__.py @@ -7,6 +7,7 @@ from .apply_parallel import apply_parallel from .arraypad import pad, crop from ._regular_grid import regular_grid from .unique import unique_rows +from .invert import invert __all__ = ['img_as_float', @@ -22,4 +23,5 @@ __all__ = ['img_as_float', 'random_noise', 'regular_grid', 'apply_parallel', + 'invert', 'unique_rows'] diff --git a/skimage/util/invert.py b/skimage/util/invert.py new file mode 100644 index 00000000..be0ddef2 --- /dev/null +++ b/skimage/util/invert.py @@ -0,0 +1,33 @@ +import numpy as np +from .dtype import dtype_limits + + +def invert(image): + """Invert an image. + + Substract the image to the maximum value allowed by the dtype maximum. + + Parameters + ---------- + image : ndarray + The input image. + + Returns + ------- + invert : ndarray + Inverted image. + + Examples + -------- + >>> img = np.array([[100, 0, 200], + ... [0, 50, 0], + ... [30, 0, 255]], np.uint8) + >>> invert(img) + array([[155, 255, 55], + [255, 205, 255], + [225, 255, 0]], dtype=uint8) + """ + if image.dtype == 'bool': + return ~image + else: + return dtype_limits(image)[1] - image diff --git a/skimage/util/tests/test_invert.py b/skimage/util/tests/test_invert.py new file mode 100644 index 00000000..ea8c7ab9 --- /dev/null +++ b/skimage/util/tests/test_invert.py @@ -0,0 +1,45 @@ +import numpy as np +from numpy.testing import assert_array_equal +from skimage import dtype_limits +from skimage.util import invert + + +def test_invert_bool(): + dtype = 'bool' + image = np.zeros((3, 3), dtype=dtype) + image[1, :] = dtype_limits(image)[1] + expected = np.zeros((3, 3), dtype=dtype) + dtype_limits(image)[1] + expected[1, :] = 0 + result = invert(image) + assert_array_equal(expected, result) + +def test_invert_uint8(): + dtype = 'uint8' + image = np.zeros((3, 3), dtype=dtype) + image[1, :] = dtype_limits(image)[1] + expected = np.zeros((3, 3), dtype=dtype) + dtype_limits(image)[1] + expected[1, :] = 0 + result = invert(image) + assert_array_equal(expected, result) + +def test_invert_bool(): + dtype = 'int8' + image = np.zeros((3, 3), dtype=dtype) + image[1, :] = dtype_limits(image)[1] + expected = np.zeros((3, 3), dtype=dtype) + dtype_limits(image)[1] + expected[1, :] = 0 + result = invert(image) + assert_array_equal(expected, result) + +def test_invert_bool(): + dtype = 'float64' + image = np.zeros((3, 3), dtype=dtype) + image[1, :] = dtype_limits(image)[1] + expected = np.zeros((3, 3), dtype=dtype) + dtype_limits(image)[1] + expected[1, :] = 0 + result = invert(image) + assert_array_equal(expected, result) + + +if __name__ == '__main__': + np.testing.run_module_suite()