Coverage for .tox/py39/lib/python3.9/site-packages/cows/arraycrop.py: 89.19%
Shortcuts on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1'''
2Contains code from scikit-image v0.18.3
3'''
5import numpy as np
8def crop(ar, crop_width, copy=False, order='K'):
9 """Crop array `ar` by `crop_width` along each dimension.
10 Parameters
11 ----------
12 ar : array-like of rank N
13 Input array.
14 crop_width : {sequence, int}
15 Number of values to remove from the edges of each axis.
16 ``((before_1, after_1),`` ... ``(before_N, after_N))`` specifies
17 unique crop widths at the start and end of each axis.
18 ``((before, after),) or (before, after)`` specifies
19 a fixed start and end crop for every axis.
20 ``(n,)`` or ``n`` for integer ``n`` is a shortcut for
21 before = after = ``n`` for all axes.
22 copy : bool, optional
23 If `True`, ensure the returned array is a contiguous copy. Normally,
24 a crop operation will return a discontiguous view of the underlying
25 input array.
26 order : {'C', 'F', 'A', 'K'}, optional
27 If ``copy==True``, control the memory layout of the copy. See
28 ``np.copy``.
29 Returns
30 -------
31 cropped : array
32 The cropped array. If ``copy=False`` (default), this is a sliced
33 view of the input array.
34 """
35 ar = np.array(ar, copy=False)
37 if isinstance(crop_width, int):
38 crops = [[crop_width, crop_width]] * ar.ndim
39 elif isinstance(crop_width[0], int):
40 if len(crop_width) == 1:
41 crops = [[crop_width[0], crop_width[0]]] * ar.ndim
42 elif len(crop_width) == 2: 42 ↛ 45line 42 didn't jump to line 45, because the condition on line 42 was never false
43 crops = [crop_width] * ar.ndim
44 else:
45 raise ValueError(
46 f"crop_width has an invalid length: {len(crop_width)}\n"
47 "crop_width should be a sequence of N pairs, "
48 "a single pair, or a single integer"
49 )
50 elif len(crop_width) == 1:
51 crops = [crop_width[0]] * ar.ndim
52 elif len(crop_width) == ar.ndim: 52 ↛ 55line 52 didn't jump to line 55, because the condition on line 52 was never false
53 crops = crop_width
54 else:
55 raise ValueError(
56 f"crop_width has an invalid length: {len(crop_width)}\n"
57 "crop_width should be a sequence of N pairs, "
58 "a single pair, or a single integer"
59 )
61 slices = tuple(slice(a, ar.shape[i] - b)
62 for i, (a, b) in enumerate(crops))
63 if copy:
64 cropped = np.array(ar[slices], order=order, copy=True)
65 else:
66 cropped = ar[slices]
67 return cropped