scikit-image
74 строки · 2.5 Кб
1import numpy as np
2from .dtype import dtype_limits
3
4
5def invert(image, signed_float=False):
6"""Invert an image.
7
8Invert the intensity range of the input image, so that the dtype maximum
9is now the dtype minimum, and vice-versa. This operation is
10slightly different depending on the input dtype:
11
12- unsigned integers: subtract the image from the dtype maximum
13- signed integers: subtract the image from -1 (see Notes)
14- floats: subtract the image from 1 (if signed_float is False, so we
15assume the image is unsigned), or from 0 (if signed_float is True).
16
17See the examples for clarification.
18
19Parameters
20----------
21image : ndarray
22Input image.
23signed_float : bool, optional
24If True and the image is of type float, the range is assumed to
25be [-1, 1]. If False and the image is of type float, the range is
26assumed to be [0, 1].
27
28Returns
29-------
30inverted : ndarray
31Inverted image.
32
33Notes
34-----
35Ideally, for signed integers we would simply multiply by -1. However,
36signed integer ranges are asymmetric. For example, for np.int8, the range
37of possible values is [-128, 127], so that -128 * -1 equals -128! By
38subtracting from -1, we correctly map the maximum dtype value to the
39minimum.
40
41Examples
42--------
43>>> img = np.array([[100, 0, 200],
44... [ 0, 50, 0],
45... [ 30, 0, 255]], np.uint8)
46>>> invert(img)
47array([[155, 255, 55],
48[255, 205, 255],
49[225, 255, 0]], dtype=uint8)
50>>> img2 = np.array([[ -2, 0, -128],
51... [127, 0, 5]], np.int8)
52>>> invert(img2)
53array([[ 1, -1, 127],
54[-128, -1, -6]], dtype=int8)
55>>> img3 = np.array([[ 0., 1., 0.5, 0.75]])
56>>> invert(img3)
57array([[1. , 0. , 0.5 , 0.25]])
58>>> img4 = np.array([[ 0., 1., -1., -0.25]])
59>>> invert(img4, signed_float=True)
60array([[-0. , -1. , 1. , 0.25]])
61"""
62if image.dtype == 'bool':
63inverted = ~image
64elif np.issubdtype(image.dtype, np.unsignedinteger):
65max_val = dtype_limits(image, clip_negative=False)[1]
66inverted = np.subtract(max_val, image, dtype=image.dtype)
67elif np.issubdtype(image.dtype, np.signedinteger):
68inverted = np.subtract(-1, image, dtype=image.dtype)
69else: # float dtype
70if signed_float:
71inverted = -image
72else:
73inverted = np.subtract(1, image, dtype=image.dtype)
74return inverted
75