scikit-image
86 строк · 2.5 Кб
1__all__ = ['slice_along_axes']
2
3
4def slice_along_axes(image, slices, axes=None, copy=False):
5"""Slice an image along given axes.
6
7Parameters
8----------
9image : ndarray
10Input image.
11slices : list of 2-tuple (a, b) where a < b.
12For 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).
15axes : int or tuple, optional
16Axes corresponding to the limits given in `slices`. If None,
17axes are in ascending order, up to the length of `slices`.
18copy : bool, optional
19If True, ensure that the output is not a view of `image`.
20
21Returns
22-------
23out : ndarray
24The region of `image` corresponding to the given slices and axes.
25
26Examples
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
44if not slices:
45return image
46
47if axes is None:
48axes = list(range(image.ndim))
49if len(axes) < len(slices):
50raise ValueError("More `slices` than available axes")
51
52elif len(axes) != len(slices):
53raise ValueError("`axes` and `slices` must have equal length")
54
55if len(axes) != len(set(axes)):
56raise ValueError("`axes` must be unique")
57
58if not all(a >= 0 and a < image.ndim for a in axes):
59raise ValueError(
60f"axes {axes} out of range; image has only " f"{image.ndim} dimensions"
61)
62
63_slices = [
64slice(None),
65] * image.ndim
66for (a, b), ax in zip(slices, axes):
67if a < 0:
68a %= image.shape[ax]
69if b < 0:
70b %= image.shape[ax]
71if a > b:
72raise ValueError(
73f"Invalid slice ({a}, {b}): must be ordered `(min_val, max_val)`"
74)
75if a < 0 or b > image.shape[ax]:
76raise ValueError(
77f"Invalid slice ({a}, {b}) for image with dimensions {image.shape}"
78)
79_slices[ax] = slice(a, b)
80
81image_slice = image[tuple(_slices)]
82
83if copy and image_slice.base is not None:
84image_slice = image_slice.copy()
85
86return image_slice
87