scikit-image

Форк
0
/
_slice_along_axes.py 
86 строк · 2.5 Кб
1
__all__ = ['slice_along_axes']
2

3

4
def slice_along_axes(image, slices, axes=None, copy=False):
5
    """Slice an image along given axes.
6

7
    Parameters
8
    ----------
9
    image : ndarray
10
        Input image.
11
    slices : list of 2-tuple (a, b) where a < b.
12
        For each axis in `axes`, a corresponding 2-tuple
13
        ``(min_val, max_val)`` to slice with (as with Python slices,
14
        ``max_val`` is non-inclusive).
15
    axes : int or tuple, optional
16
        Axes corresponding to the limits given in `slices`. If None,
17
        axes are in ascending order, up to the length of `slices`.
18
    copy : bool, optional
19
        If True, ensure that the output is not a view of `image`.
20

21
    Returns
22
    -------
23
    out : ndarray
24
        The region of `image` corresponding to the given slices and axes.
25

26
    Examples
27
    --------
28
    >>> from skimage import data
29
    >>> img = data.camera()
30
    >>> img.shape
31
    (512, 512)
32
    >>> cropped_img = slice_along_axes(img, [(0, 100)])
33
    >>> cropped_img.shape
34
    (100, 512)
35
    >>> cropped_img = slice_along_axes(img, [(0, 100), (0, 100)])
36
    >>> cropped_img.shape
37
    (100, 100)
38
    >>> cropped_img = slice_along_axes(img, [(0, 100), (0, 75)], axes=[1, 0])
39
    >>> cropped_img.shape
40
    (75, 100)
41
    """
42

43
    # empty length of bounding box detected on None
44
    if not slices:
45
        return image
46

47
    if axes is None:
48
        axes = list(range(image.ndim))
49
        if len(axes) < len(slices):
50
            raise ValueError("More `slices` than available axes")
51

52
    elif len(axes) != len(slices):
53
        raise ValueError("`axes` and `slices` must have equal length")
54

55
    if len(axes) != len(set(axes)):
56
        raise ValueError("`axes` must be unique")
57

58
    if not all(a >= 0 and a < image.ndim for a in axes):
59
        raise ValueError(
60
            f"axes {axes} out of range; image has only " f"{image.ndim} dimensions"
61
        )
62

63
    _slices = [
64
        slice(None),
65
    ] * image.ndim
66
    for (a, b), ax in zip(slices, axes):
67
        if a < 0:
68
            a %= image.shape[ax]
69
        if b < 0:
70
            b %= image.shape[ax]
71
        if a > b:
72
            raise ValueError(
73
                f"Invalid slice ({a}, {b}): must be ordered `(min_val, max_val)`"
74
            )
75
        if a < 0 or b > image.shape[ax]:
76
            raise ValueError(
77
                f"Invalid slice ({a}, {b}) for image with dimensions {image.shape}"
78
            )
79
        _slices[ax] = slice(a, b)
80

81
    image_slice = image[tuple(_slices)]
82

83
    if copy and image_slice.base is not None:
84
        image_slice = image_slice.copy()
85

86
    return image_slice
87

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

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

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

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