Debian Codegraph @

dask_image/ndinterp/_rotate.py

raw
1 # -*- coding: utf-8 -*-
2
3 import dask.array as da
4 import numpy as np
5 from scipy.special import sindg, cosdg
6
7 from ._affine_transform import affine_transform
8
9
10 def rotate(
11 input_arr,
12 angle,
13 axes=(1, 0),
14 reshape=True,
15 output_chunks=None,
16 **kwargs,
17 ):
18 """Rotate an array using Dask.
19
20 The array is rotated in the plane defined by the two axes given by the
21 `axes` parameter using spline interpolation of the requested order.
22
23 Chunkwise processing is performed using
24 `dask_image.ndinterp.affine_transform`, for which further parameters
25 supported by the ndimage functions can be passed as keyword arguments.
26
27 Notes
28 -----
29 Differences to `ndimage.rotate`:
30 - currently, prefiltering is not supported
31 (affecting the output in case of interpolation `order > 1`)
32 - default order is 1
33 - modes 'reflect', 'mirror' and 'wrap' are not supported
34
35 Arguments are equal to `ndimage.rotate` except for
36 - `output` (not present here)
37 - `output_chunks` (relevant in the dask array context)
38
39 Parameters
40 ----------
41 input_arr : array_like (Numpy Array, Cupy Array, Dask Array...)
42 The image array.
43 angle : float
44 The rotation angle in degrees.
45 axes : tuple of 2 ints, optional
46 The two axes that define the plane of rotation. Default is the first
47 two axes.
48 reshape : bool, optional
49 If `reshape` is true, the output shape is adapted so that the input
50 array is contained completely in the output. Default is True.
51 output_chunks : tuple of ints, optional
52 The shape of the chunks of the output Dask Array.
53 **kwargs : dict, optional
54 Additional keyword arguments are passed to
55 `dask_image.ndinterp.affine_transform`.
56
57 Returns
58 -------
59 rotate : Dask Array
60 A dask array representing the rotated input.
61
62 Examples
63 --------
64 >>> from scipy import ndimage, misc
65 >>> import matplotlib.pyplot as plt
66 >>> import dask.array as da
67 >>> fig = plt.figure(figsize=(10, 3))
68 >>> ax1, ax2, ax3 = fig.subplots(1, 3)
69 >>> img = da.from_array(misc.ascent(),chunks=(64,64))
70 >>> img_45 = dask_image.ndinterp.rotate(img, 45, reshape=False)
71 >>> full_img_45 = dask_image.ndinterp.rotate(img, 45, reshape=True)
72 >>> ax1.imshow(img, cmap='gray')
73 >>> ax1.set_axis_off()
74 >>> ax2.imshow(img_45, cmap='gray')
75 >>> ax2.set_axis_off()
76 >>> ax3.imshow(full_img_45, cmap='gray')
77 >>> ax3.set_axis_off()
78 >>> fig.set_tight_layout(True)
79 >>> plt.show()
80 >>> print(img.shape)
81 (512, 512)
82 >>> print(img_45.shape)
83 (512, 512)
84 >>> print(full_img_45.shape)
85 (724, 724)
86 """
87
88 if not isinstance(input_arr, da.core.Array):
89 input_arr = da.from_array(input_arr)
90
91 if output_chunks is None:
92 output_chunks = input_arr.chunksize
93
94 ndim = input_arr.ndim
95
96 if ndim < 2:
97 raise ValueError('input array should be at least 2D')
98
99 axes = list(axes)
100
101 if len(axes) != 2:
102 raise ValueError('axes should contain exactly two values')
103
104 if not all([float(ax).is_integer() for ax in axes]):
105 raise ValueError('axes should contain only integer values')
106
107 if axes[0] < 0:
108 axes[0] += ndim
109 if axes[1] < 0:
110 axes[1] += ndim
111 if axes[0] < 0 or axes[1] < 0 or axes[0] >= ndim or axes[1] >= ndim:
112 raise ValueError('invalid rotation plane specified')
113
114 axes.sort()
115
116 c, s = cosdg(angle), sindg(angle)
117
118 rot_matrix = np.array([[c, s],
119 [-s, c]])
120
121 img_shape = np.asarray(input_arr.shape)
122 in_plane_shape = img_shape[axes]
123
124 if reshape:
125 # Compute transformed input bounds
126 iy, ix = in_plane_shape
127 in_bounds = np.array([[0, 0, iy, iy],
128 [0, ix, 0, ix]])
129 out_bounds = rot_matrix @ in_bounds
130 # Compute the shape of the transformed input plane
131 out_plane_shape = (np.ptp(out_bounds, axis=1) + 0.5).astype(int)
132 else:
133 out_plane_shape = img_shape[axes]
134
135 output_shape = np.array(img_shape)
136 output_shape[axes] = out_plane_shape
137 output_shape = tuple(output_shape)
138
139 out_center = rot_matrix @ ((out_plane_shape - 1) / 2)
140 in_center = (in_plane_shape - 1) / 2
141 offset = in_center - out_center
142
143 matrix_nd = np.eye(ndim)
144 offset_nd = np.zeros(ndim)
145
146 for o_x, idx in enumerate(axes):
147
148 matrix_nd[idx, axes[0]] = rot_matrix[o_x, 0]
149 matrix_nd[idx, axes[1]] = rot_matrix[o_x, 1]
150
151 offset_nd[idx] = offset[o_x]
152
153 output = affine_transform(
154 input_arr,
155 matrix=matrix_nd,
156 offset=offset_nd,
157 output_shape=output_shape,
158 output_chunks=output_chunks,
159 **kwargs,
160 )
161
162 return output