scikit-image

Форк
0
132 строки · 4.4 Кб
1
import functools
2
import warnings
3
from itertools import product
4

5
import numpy as np
6

7
from .dtype import img_as_float
8

9

10
def _rename_image_params(func):
11
    wm_images = (
12
        "Since version 0.24, the two input images are named `image0` and "
13
        "`image1` (instead of `image1` and `image2`, respectively). Please use "
14
        "`image0, image1` to avoid this warning for now, and avoid an error "
15
        "from version 0.26 onwards."
16
    )
17

18
    wm_method = (
19
        "Starting in version 0.24, all arguments following `image0, image1` "
20
        "(including `method`) will be keyword-only. Please pass `method=` "
21
        "in the function call to avoid this warning for now, and avoid an error "
22
        "from version 0.26 onwards."
23
    )
24

25
    @functools.wraps(func)
26
    def wrapper(*args, **kwargs):
27
        # Turn all args into kwargs
28
        for i, (value, param) in enumerate(
29
            zip(args, ["image0", "image1", "method", "n_tiles"])
30
        ):
31
            if i >= 2:
32
                warnings.warn(wm_method, category=FutureWarning, stacklevel=2)
33
            if param in kwargs:
34
                raise ValueError(
35
                    f"{param} passed both as positional and keyword argument."
36
                )
37
            else:
38
                kwargs[param] = value
39
        args = tuple()
40

41
        # Account for `image2` if given
42
        if "image2" in kwargs.keys():
43
            warnings.warn(wm_images, category=FutureWarning, stacklevel=2)
44

45
            # Safely move `image2` to `image1` if that's empty
46
            if "image1" in kwargs.keys():
47
                # Safely move `image1` to `image0`
48
                if "image0" in kwargs.keys():
49
                    raise ValueError(
50
                        "Three input images given; please use only `image0` "
51
                        "and `image1`."
52
                    )
53
                kwargs["image0"] = kwargs.pop("image1")
54
            kwargs["image1"] = kwargs.pop("image2")
55

56
        return func(*args, **kwargs)
57

58
    return wrapper
59

60

61
@_rename_image_params
62
def compare_images(image0, image1, *, method='diff', n_tiles=(8, 8)):
63
    """
64
    Return an image showing the differences between two images.
65

66
    .. versionadded:: 0.16
67

68
    Parameters
69
    ----------
70
    image0, image1 : ndarray, shape (M, N)
71
        Images to process, must be of the same shape.
72

73
        .. versionchanged:: 0.24
74
            `image1` and `image2` were renamed into `image0` and `image1`
75
            respectively.
76
    method : string, optional
77
        Method used for the comparison.
78
        Valid values are {'diff', 'blend', 'checkerboard'}.
79
        Details are provided in the note section.
80

81
        .. versionchanged:: 0.24
82
            This parameter and following ones are keyword-only.
83
    n_tiles : tuple, optional
84
        Used only for the `checkerboard` method. Specifies the number
85
        of tiles (row, column) to divide the image.
86

87
    Returns
88
    -------
89
    comparison : ndarray, shape (M, N)
90
        Image showing the differences.
91

92
    Notes
93
    -----
94
    ``'diff'`` computes the absolute difference between the two images.
95
    ``'blend'`` computes the mean value.
96
    ``'checkerboard'`` makes tiles of dimension `n_tiles` that display
97
    alternatively the first and the second image. Note that images must be
98
    2-dimensional to be compared with the checkerboard method.
99
    """
100

101
    if image1.shape != image0.shape:
102
        raise ValueError('Images must have the same shape.')
103

104
    img1 = img_as_float(image0)
105
    img2 = img_as_float(image1)
106

107
    if method == 'diff':
108
        comparison = np.abs(img2 - img1)
109
    elif method == 'blend':
110
        comparison = 0.5 * (img2 + img1)
111
    elif method == 'checkerboard':
112
        if img1.ndim != 2:
113
            raise ValueError(
114
                'Images must be 2-dimensional to be compared with the '
115
                'checkerboard method.'
116
            )
117
        shapex, shapey = img1.shape
118
        mask = np.full((shapex, shapey), False)
119
        stepx = int(shapex / n_tiles[0])
120
        stepy = int(shapey / n_tiles[1])
121
        for i, j in product(range(n_tiles[0]), range(n_tiles[1])):
122
            if (i + j) % 2 == 0:
123
                mask[i * stepx : (i + 1) * stepx, j * stepy : (j + 1) * stepy] = True
124
        comparison = np.zeros_like(img1)
125
        comparison[mask] = img1[mask]
126
        comparison[~mask] = img2[~mask]
127
    else:
128
        raise ValueError(
129
            'Wrong value for `method`. '
130
            'Must be either "diff", "blend" or "checkerboard".'
131
        )
132
    return comparison
133

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.