scikit-image

Форк
0
320 строк · 11.8 Кб
1
"""
2
Binary morphological operations
3
"""
4

5
import numpy as np
6
from scipy import ndimage as ndi
7

8
from .footprints import _footprint_is_sequence, pad_footprint
9
from .misc import default_footprint
10

11

12
def _iterate_binary_func(binary_func, image, footprint, out, border_value):
13
    """Helper to call `binary_func` for each footprint in a sequence.
14

15
    binary_func is a binary morphology function that accepts "structure",
16
    "output" and "iterations" keyword arguments
17
    (e.g. `scipy.ndimage.binary_erosion`).
18
    """
19
    fp, num_iter = footprint[0]
20
    binary_func(
21
        image, structure=fp, output=out, iterations=num_iter, border_value=border_value
22
    )
23
    for fp, num_iter in footprint[1:]:
24
        # Note: out.copy() because the computation cannot be in-place!
25
        #       SciPy <= 1.7 did not automatically make a copy if needed.
26
        binary_func(
27
            out.copy(),
28
            structure=fp,
29
            output=out,
30
            iterations=num_iter,
31
            border_value=border_value,
32
        )
33
    return out
34

35

36
# The default_footprint decorator provides a diamond footprint as
37
# default with the same dimension as the input image and size 3 along each
38
# axis.
39
@default_footprint
40
def binary_erosion(image, footprint=None, out=None, *, mode='ignore'):
41
    """Return fast binary morphological erosion of an image.
42

43
    This function returns the same result as grayscale erosion but performs
44
    faster for binary images.
45

46
    Morphological erosion sets a pixel at ``(i,j)`` to the minimum over all
47
    pixels in the neighborhood centered at ``(i,j)``. Erosion shrinks bright
48
    regions and enlarges dark regions.
49

50
    Parameters
51
    ----------
52
    image : ndarray
53
        Binary input image.
54
    footprint : ndarray or tuple, optional
55
        The neighborhood expressed as a 2-D array of 1's and 0's.
56
        If None, use a cross-shaped footprint (connectivity=1). The footprint
57
        can also be provided as a sequence of smaller footprints as described
58
        in the notes below.
59
    out : ndarray of bool, optional
60
        The array to store the result of the morphology. If None is
61
        passed, a new array will be allocated.
62
    mode : str, optional
63
        The `mode` parameter determines how the array borders are handled.
64
        Valid modes are: 'max', 'min', 'ignore'.
65
        If 'max' or 'ignore', pixels outside the image domain are assumed
66
        to be `True`, which causes them to not influence the result.
67
        Default is 'ignore'.
68

69
        .. versionadded:: 0.23
70
            `mode` was added in 0.23.
71

72
    Returns
73
    -------
74
    eroded : ndarray of bool or uint
75
        The result of the morphological erosion taking values in
76
        ``[False, True]``.
77

78
    Notes
79
    -----
80
    The footprint can also be a provided as a sequence of 2-tuples where the
81
    first element of each 2-tuple is a footprint ndarray and the second element
82
    is an integer describing the number of times it should be iterated. For
83
    example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]``
84
    would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net
85
    effect that is the same as ``footprint=np.ones((9, 9))``, but with lower
86
    computational cost. Most of the builtin footprints such as
87
    :func:`skimage.morphology.disk` provide an option to automatically generate a
88
    footprint sequence of this type.
89

90
    For even-sized footprints, :func:`skimage.morphology.erosion` and
91
    this function produce an output that differs: one is shifted by one pixel
92
    compared to the other.
93

94
    See also
95
    --------
96
    skimage.morphology.isotropic_erosion
97

98
    """
99
    if out is None:
100
        out = np.empty(image.shape, dtype=bool)
101

102
    if mode not in {"max", "min", "ignore"}:
103
        raise ValueError(f"unsupported mode, got {mode!r}")
104
    border_value = False if mode == 'min' else True
105

106
    footprint = pad_footprint(footprint, pad_end=True)
107
    if not _footprint_is_sequence(footprint):
108
        footprint = [(footprint, 1)]
109

110
    out = _iterate_binary_func(
111
        binary_func=ndi.binary_erosion,
112
        image=image,
113
        footprint=footprint,
114
        out=out,
115
        border_value=border_value,
116
    )
117
    return out
118

119

120
@default_footprint
121
def binary_dilation(image, footprint=None, out=None, *, mode='ignore'):
122
    """Return fast binary morphological dilation of an image.
123

124
    This function returns the same result as grayscale dilation but performs
125
    faster for binary images.
126

127
    Morphological dilation sets a pixel at ``(i,j)`` to the maximum over all
128
    pixels in the neighborhood centered at ``(i,j)``. Dilation enlarges bright
129
    regions and shrinks dark regions.
130

131
    Parameters
132
    ----------
133
    image : ndarray
134
        Binary input image.
135
    footprint : ndarray or tuple, optional
136
        The neighborhood expressed as a 2-D array of 1's and 0's.
137
        If None, use a cross-shaped footprint (connectivity=1). The footprint
138
        can also be provided as a sequence of smaller footprints as described
139
        in the notes below.
140
    out : ndarray of bool, optional
141
        The array to store the result of the morphology. If None is
142
        passed, a new array will be allocated.
143
    mode : str, optional
144
        The `mode` parameter determines how the array borders are handled.
145
        Valid modes are: 'max', 'min', 'ignore'.
146
        If 'min' or 'ignore', pixels outside the image domain are assumed
147
        to be `False`, which causes them to not influence the result.
148
        Default is 'ignore'.
149

150
        .. versionadded:: 0.23
151
            `mode` was added in 0.23.
152

153
    Returns
154
    -------
155
    dilated : ndarray of bool or uint
156
        The result of the morphological dilation with values in
157
        ``[False, True]``.
158

159
    Notes
160
    -----
161
    The footprint can also be a provided as a sequence of 2-tuples where the
162
    first element of each 2-tuple is a footprint ndarray and the second element
163
    is an integer describing the number of times it should be iterated. For
164
    example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]``
165
    would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net
166
    effect that is the same as ``footprint=np.ones((9, 9))``, but with lower
167
    computational cost. Most of the builtin footprints such as
168
    :func:`skimage.morphology.disk` provide an option to automatically generate a
169
    footprint sequence of this type.
170

171
    For non-symmetric footprints, :func:`skimage.morphology.binary_dilation`
172
    and :func:`skimage.morphology.dilation` produce an output that differs:
173
    `binary_dilation` mirrors the footprint, whereas `dilation` does not.
174

175
    See also
176
    --------
177
    skimage.morphology.isotropic_dilation
178

179
    """
180
    if out is None:
181
        out = np.empty(image.shape, dtype=bool)
182

183
    if mode not in {"max", "min", "ignore"}:
184
        raise ValueError(f"unsupported mode, got {mode!r}")
185
    border_value = True if mode == 'max' else False
186

187
    footprint = pad_footprint(footprint, pad_end=True)
188
    if not _footprint_is_sequence(footprint):
189
        footprint = [(footprint, 1)]
190

191
    out = _iterate_binary_func(
192
        binary_func=ndi.binary_dilation,
193
        image=image,
194
        footprint=footprint,
195
        out=out,
196
        border_value=border_value,
197
    )
198
    return out
199

200

201
@default_footprint
202
def binary_opening(image, footprint=None, out=None, *, mode='ignore'):
203
    """Return fast binary morphological opening of an image.
204

205
    This function returns the same result as grayscale opening but performs
206
    faster for binary images.
207

208
    The morphological opening on an image is defined as an erosion followed by
209
    a dilation. Opening can remove small bright spots (i.e. "salt") and connect
210
    small dark cracks. This tends to "open" up (dark) gaps between (bright)
211
    features.
212

213
    Parameters
214
    ----------
215
    image : ndarray
216
        Binary input image.
217
    footprint : ndarray or tuple, optional
218
        The neighborhood expressed as a 2-D array of 1's and 0's.
219
        If None, use a cross-shaped footprint (connectivity=1). The footprint
220
        can also be provided as a sequence of smaller footprints as described
221
        in the notes below.
222
    out : ndarray of bool, optional
223
        The array to store the result of the morphology. If None
224
        is passed, a new array will be allocated.
225
    mode : str, optional
226
        The `mode` parameter determines how the array borders are handled.
227
        Valid modes are: 'max', 'min', 'ignore'.
228
        If 'ignore', pixels outside the image domain are assumed to be `True`
229
        for the erosion and `False` for the dilation, which causes them to not
230
        influence the result. Default is 'ignore'.
231

232
        .. versionadded:: 0.23
233
            `mode` was added in 0.23.
234

235
    Returns
236
    -------
237
    opening : ndarray of bool
238
        The result of the morphological opening.
239

240
    Notes
241
    -----
242
    The footprint can also be a provided as a sequence of 2-tuples where the
243
    first element of each 2-tuple is a footprint ndarray and the second element
244
    is an integer describing the number of times it should be iterated. For
245
    example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]``
246
    would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net
247
    effect that is the same as ``footprint=np.ones((9, 9))``, but with lower
248
    computational cost. Most of the builtin footprints such as
249
    :func:`skimage.morphology.disk` provide an option to automatically generate a
250
    footprint sequence of this type.
251

252
    See also
253
    --------
254
    skimage.morphology.isotropic_opening
255

256
    """
257
    tmp = binary_erosion(image, footprint, mode=mode)
258
    out = binary_dilation(tmp, footprint, out=out, mode=mode)
259
    return out
260

261

262
@default_footprint
263
def binary_closing(image, footprint=None, out=None, *, mode='ignore'):
264
    """Return fast binary morphological closing of an image.
265

266
    This function returns the same result as grayscale closing but performs
267
    faster for binary images.
268

269
    The morphological closing on an image is defined as a dilation followed by
270
    an erosion. Closing can remove small dark spots (i.e. "pepper") and connect
271
    small bright cracks. This tends to "close" up (dark) gaps between (bright)
272
    features.
273

274
    Parameters
275
    ----------
276
    image : ndarray
277
        Binary input image.
278
    footprint : ndarray or tuple, optional
279
        The neighborhood expressed as a 2-D array of 1's and 0's.
280
        If None, use a cross-shaped footprint (connectivity=1). The footprint
281
        can also be provided as a sequence of smaller footprints as described
282
        in the notes below.
283
    out : ndarray of bool, optional
284
        The array to store the result of the morphology. If None,
285
        is passed, a new array will be allocated.
286
    mode : str, optional
287
        The `mode` parameter determines how the array borders are handled.
288
        Valid modes are: 'max', 'min', 'ignore'.
289
        If 'ignore', pixels outside the image domain are assumed to be `True`
290
        for the erosion and `False` for the dilation, which causes them to not
291
        influence the result. Default is 'ignore'.
292

293
        .. versionadded:: 0.23
294
            `mode` was added in 0.23.
295

296
    Returns
297
    -------
298
    closing : ndarray of bool
299
        The result of the morphological closing.
300

301
    Notes
302
    -----
303
    The footprint can also be a provided as a sequence of 2-tuples where the
304
    first element of each 2-tuple is a footprint ndarray and the second element
305
    is an integer describing the number of times it should be iterated. For
306
    example ``footprint=[(np.ones((9, 1)), 1), (np.ones((1, 9)), 1)]``
307
    would apply a 9x1 footprint followed by a 1x9 footprint resulting in a net
308
    effect that is the same as ``footprint=np.ones((9, 9))``, but with lower
309
    computational cost. Most of the builtin footprints such as
310
    :func:`skimage.morphology.disk` provide an option to automatically generate a
311
    footprint sequence of this type.
312

313
    See also
314
    --------
315
    skimage.morphology.isotropic_closing
316

317
    """
318
    tmp = binary_dilation(image, footprint, mode=mode)
319
    out = binary_erosion(tmp, footprint, out=out, mode=mode)
320
    return out
321

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

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

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

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