pystackreg 0.2.8__cp313-cp313-macosx_11_0_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pystackreg/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ # -*- coding: utf-8 -*-
2
+ from .pystackreg import StackReg
3
+ from .version import __version__
pystackreg/conftest.py ADDED
@@ -0,0 +1,2 @@
1
+ # required for pytest to import the package from here
2
+ # instead of using an installed package
@@ -0,0 +1,480 @@
1
+ # -*- coding: utf-8 -*-
2
+ from . import turboreg # type: ignore
3
+ import numpy as np
4
+ from tqdm import tqdm
5
+ import warnings
6
+ from .util import simple_slice, running_mean
7
+
8
+
9
+ class StackReg:
10
+ """
11
+ Python implementation of the ImageJ/Fiji StackReg plugin
12
+ (http://bigwww.epfl.ch/thevenaz/stackreg/ )
13
+ """
14
+
15
+ TRANSLATION = 2
16
+ """
17
+ Translation
18
+ """
19
+
20
+ RIGID_BODY = 3
21
+ """
22
+ Rigid body (translation + rotation)
23
+ """
24
+
25
+ SCALED_ROTATION = 4
26
+ """
27
+ Scaled rotation (translation + rotation + scaling)
28
+ """
29
+
30
+ AFFINE = 6
31
+ """
32
+ Affine (translation + rotation + scaling + shearing)
33
+ """
34
+
35
+ BILINEAR = 8
36
+ """
37
+ Bilinear (non-linear transformation; does not preserve straight lines)
38
+ """
39
+
40
+ _valid_transformations = [
41
+ TRANSLATION,
42
+ RIGID_BODY,
43
+ SCALED_ROTATION,
44
+ AFFINE,
45
+ BILINEAR,
46
+ ]
47
+
48
+ _is_registered = False
49
+
50
+ def __init__(self, transformation):
51
+ """
52
+ Constructor
53
+ :param transformation: TRANSLATION, RIGID_BODY, SCALED_ROTATION, AFFINE,
54
+ BILINEAR
55
+ """
56
+ if transformation not in self._valid_transformations:
57
+ raise Exception("Invalid transformation")
58
+
59
+ self._transformation = transformation
60
+ self._m = None
61
+ self._tmats = None
62
+ self._refpts = None
63
+ self._movpts = None
64
+
65
+ def is_registered(self):
66
+ """
67
+ Indicates whether register() was already called and a transformation matrix
68
+ was calculated
69
+
70
+ :rtype: bool
71
+ :return: True if a transformation matrix was already calculated
72
+ """
73
+ return self._is_registered
74
+
75
+ def register(self, ref, mov):
76
+ """
77
+ Registers an image to a reference image: Only the transformation matrix
78
+ will be calculated, the image will not be transformed
79
+ (use transform() or register_transform() ).
80
+
81
+ :type ref: array_like (Ni..., Nj...)
82
+ :param ref: Reference image (static)
83
+
84
+ :type mov: array_like (Ni..., Nj...)
85
+ :param mov:
86
+ The image that should be aligned to the reference image
87
+
88
+ :rtype: ndarray(3,3)
89
+ :return: 2D transformation matrix
90
+ """
91
+ self._is_registered = True
92
+
93
+ self._m, self._refpts, self._movpts = turboreg._register(
94
+ ref[:-1, :-1], mov[:-1, :-1], self._transformation
95
+ )
96
+
97
+ return self.get_matrix()
98
+
99
+ def transform(self, mov, tmat=None):
100
+ """
101
+ Transform an image according to a previous registration.
102
+
103
+ Either a transformation matrix has to be explicitly supplied or
104
+ register() has to be called before calling transform().
105
+
106
+ :type mov: array_like (Ni..., Nj...)
107
+ :param mov: The image that will be transformed
108
+
109
+ :type tmat: ndarray(3,3), optional
110
+ :param tmat: The transformation matrix
111
+
112
+ :rtype: ndarray (Ni..., Nj...)
113
+ :return: Transformed image - will be of the same shape as the input image
114
+ (cropping may occur)
115
+ """
116
+ if tmat is None and not self.is_registered():
117
+ raise Exception("Register first")
118
+
119
+ if tmat is not None:
120
+ tmat = self._matrix_long_to_short(tmat)
121
+ else:
122
+ tmat = self._m
123
+
124
+ return turboreg._transform(mov, tmat)
125
+
126
+ def register_transform(self, ref, mov):
127
+ """
128
+ Register and transform an image to a reference image.
129
+
130
+ :type ref: ref: array_like (Ni..., Nj...)
131
+ :param ref: Reference image (static)
132
+
133
+ :type mov: array_like (Ni..., Nj...)
134
+ :param mov: The image that should be aligned to the reference image
135
+
136
+ :rtype: ndarray (Ni..., Nj...)
137
+ :return: Transformed image - will be of the same shape as the input image
138
+ (cropping may occur)
139
+ """
140
+ self.register(ref, mov)
141
+ return self.transform(mov)
142
+
143
+ def get_matrix(self):
144
+ """
145
+ Get the current transformation matrix
146
+
147
+ :rtype: ndarray(3,3) or ndarray(4,4) for bilinear transformation
148
+ :return: The transformation matrix
149
+ """
150
+ return self._matrix_short_to_long(self._m)
151
+
152
+ def set_matrix(self, mat):
153
+ """
154
+ Sets the current transformation matrix
155
+
156
+ :type mat: ndarray(3,3) or ndarray(4,4) for bilinear transformation
157
+ :param mat: The transformation matrix
158
+ """
159
+
160
+ exp_shape = (4, 4) if self._transformation == self.BILINEAR else (3, 3)
161
+
162
+ if not exp_shape == mat.shape:
163
+ raise Exception(
164
+ "Invalid shape of transformation matrix: Expected %s, got %s"
165
+ % (str(exp_shape), str(mat.shape))
166
+ )
167
+
168
+ self._m = self._matrix_long_to_short(mat)
169
+
170
+ self._is_registered = True
171
+
172
+ def _matrix_short_to_long(self, m):
173
+ """
174
+ Converts the transformation matrix from the short form used by TurboReg to
175
+ the canonical form from linear algebra.
176
+
177
+ :type m: array_like
178
+ :param m: TurboReg transformation matrix
179
+
180
+ :rtype: ndarray(3,3)
181
+ :return: Canonical transformation matrix
182
+ """
183
+
184
+ if self._transformation == self.TRANSLATION:
185
+ mat = np.identity(3).astype(np.double)
186
+ mat[0:2, 2] = m[:, 0]
187
+ elif self._transformation in [
188
+ self.RIGID_BODY,
189
+ self.SCALED_ROTATION,
190
+ self.AFFINE,
191
+ ]:
192
+ mat = np.identity(3).astype(np.double)
193
+ mat[0:2, :] = m[:, [1, 2, 0]]
194
+ elif self._transformation == self.BILINEAR:
195
+ mat = np.identity(4).astype(np.double)
196
+ mat[0:2, :] = m[:, [1, 2, 3, 0]]
197
+ else:
198
+ raise Exception("Unexpected transformation")
199
+
200
+ return mat
201
+
202
+ def _matrix_long_to_short(self, mat):
203
+ """
204
+ Converts the transformation matrix from the canonical form from linear algebra
205
+ to the short form used by TurboReg.
206
+
207
+ :type mat: ndarray(3,3)
208
+ :param mat: Canonical transformation matrix
209
+
210
+ :rtype: array_like
211
+ :return: TurboReg transformation matrix
212
+ """
213
+ if self._transformation == self.TRANSLATION:
214
+ m = mat[0:2, 2].reshape((2, 1))
215
+ elif self._transformation in [
216
+ self.RIGID_BODY,
217
+ self.SCALED_ROTATION,
218
+ self.AFFINE,
219
+ ]:
220
+ m = mat[0:2, [2, 0, 1]]
221
+ elif self._transformation == self.BILINEAR:
222
+ m = mat[0:2, [3, 0, 1, 2]]
223
+ else:
224
+ raise Exception("Unexpected transformation")
225
+
226
+ return m.astype(np.double)
227
+
228
+ @staticmethod
229
+ def _detect_time_axis(img):
230
+ """
231
+ Detects the time axis of a movie/stack by returning the dimension with the
232
+ lowest average variability
233
+
234
+ :param img:
235
+ :return:
236
+ """
237
+ var = np.array([np.var(img, axis=i).mean() for i in range(img.ndim)])
238
+ return np.argmin(var)
239
+
240
+ def get_points(self):
241
+ """
242
+ Returns the pairs of corresponding points from which the
243
+ transformation matrix can be calculated.
244
+
245
+ :rtype: (ndarray, ndarray)
246
+ :return: (Point coordinates of reference image, Point coordinates of image to
247
+ be aligned)
248
+ """
249
+ return self._refpts, self._movpts
250
+
251
+ def register_stack(
252
+ self,
253
+ img,
254
+ reference="previous",
255
+ n_frames=1,
256
+ axis=0,
257
+ moving_average=1,
258
+ verbose=False,
259
+ progress_callback=None,
260
+ suppress_axis_warning=False,
261
+ ):
262
+ """
263
+ Register a stack of images (movie).
264
+ Note that this function will not transform the image but only calculate the
265
+ transformation matrices.
266
+ For transformation use transform_stack() after this function or use
267
+ register_transform_stack() for a single call.
268
+
269
+ :type img: array_like(Ni..., Nj..., Nk...)
270
+ :param img: The 3D stack of images that should be aligned
271
+
272
+ :type reference: string, one of ['previous', 'first', 'mean']
273
+ :param reference:
274
+ * *'previous'*: Aligns each frame (image) to its previous frame in the
275
+ stack
276
+ * *'first:'* Aligns each frame (image) to the first frame in the stack -
277
+ if n_frames is > 1, then each frame is aligned to the
278
+ mean of the first n_frames of the stack
279
+ * *'mean'*: Aligns each frame (image) to the average of all images in the
280
+ stack
281
+
282
+ :type n_frames: int, optional
283
+ :param n_frames: If reference is 'first', then this parameter specifies the
284
+ number of frames from the beginning of the stack that should
285
+ be averaged to yield the reference image.
286
+
287
+ :type axis: int, optional
288
+ :param axis: The axis of the time dimension
289
+
290
+ :type moving_average: int, optional
291
+ :param moving_average:
292
+ If moving_average is greater than 1, a moving average of the stack is first
293
+ created (using a subset size of moving_average) before registration
294
+
295
+ :type verbose: bool, optional
296
+ :param verbose:
297
+ Specifies whether a progressbar should be shown using tqdm.
298
+
299
+ :type progress_callback: function, optional
300
+ :param progress_callback:
301
+ A function that is called after every iteration. This function should accept
302
+ the keyword arguments current_iteration:int and end_iteration:int.
303
+
304
+ :type suppress_axis_warning: function, optional
305
+ :param suppress_axis_warning:
306
+ pystackreg will automatically try to determine the time axis and raise a
307
+ warning when the detected time axis is not equal to the supplied axis.
308
+ Set this option to True to suppress this warning.
309
+
310
+ :rtype: ndarray(img.shape[axis], 3, 3)
311
+ :return: The transformation matrix for each image in the stack
312
+ """
313
+
314
+ if self._transformation == self.BILINEAR and reference == "previous":
315
+ raise Exception(
316
+ "Bilinear stack transformation not supported with reference "
317
+ '== "previous" as a combination of bilinear transformations does not '
318
+ "generally result in a bilinear transformation. Use another reference "
319
+ "or manually register/transform images to their previous image."
320
+ )
321
+
322
+ if len(img.shape) != 3:
323
+ raise Exception("Stack must have three dimensions")
324
+
325
+ if not suppress_axis_warning:
326
+ lowest_var_axis = self._detect_time_axis(img)
327
+ if axis != lowest_var_axis:
328
+ warnings.warn(
329
+ "Detected axis {} as the possible time axis for the stack due to "
330
+ "its low variability, but axis {} was supplied for registration. "
331
+ "Are you sure you supplied the correct axis?".format(
332
+ lowest_var_axis, axis
333
+ )
334
+ )
335
+
336
+ idx_start = 1
337
+
338
+ if moving_average > 1:
339
+ idx_start = 0
340
+ size = [0] * len(img.shape)
341
+ size[axis] = moving_average
342
+ img = running_mean(img, moving_average, axis=axis)
343
+
344
+ tmatdim = 4 if self._transformation == self.BILINEAR else 3
345
+
346
+ self._tmats = np.repeat(
347
+ np.identity(tmatdim).reshape((1, tmatdim, tmatdim)), img.shape[axis], axis=0
348
+ ).astype(np.double)
349
+
350
+ if reference == "first":
351
+ ref = np.mean(img.take(range(n_frames), axis=axis), axis=axis)
352
+ elif reference == "mean":
353
+ ref = img.mean(axis=axis)
354
+ idx_start = 0
355
+ elif reference == "previous":
356
+ pass
357
+ else:
358
+ raise ValueError('Unknown reference "{}"'.format(reference))
359
+
360
+ iterable = range(idx_start, img.shape[axis])
361
+
362
+ if verbose:
363
+ iterable = tqdm(iterable)
364
+
365
+ for i in iterable:
366
+ slc = [slice(None)] * len(img.shape)
367
+ slc[axis] = i
368
+
369
+ if reference == "previous":
370
+ ref = img.take(i - 1, axis=axis)
371
+
372
+ self._tmats[i, :, :] = self.register(ref, simple_slice(img, i, axis))
373
+
374
+ if reference == "previous" and i > 0:
375
+ self._tmats[i, :, :] = np.matmul(
376
+ self._tmats[i, :, :], self._tmats[i - 1, :, :]
377
+ )
378
+
379
+ if progress_callback is not None:
380
+ progress_callback(
381
+ current_iteration=i - idx_start + 1,
382
+ end_iteration=img.shape[axis] - idx_start,
383
+ )
384
+
385
+ return self._tmats
386
+
387
+ def transform_stack(self, img, axis=0, tmats=None):
388
+ """
389
+ Transform a stack after registration.
390
+
391
+ :type img: array_like(Ni..., Nj..., Nk...)
392
+ :param img: The 3D stack of images that should be aligned
393
+
394
+ :type axis: int, optional
395
+ :param axis: The axis of the time dimension
396
+
397
+ :type tmats: ndarray(img.shape[axis], 3, 3), optional
398
+ :param tmats: The transformation matrix for each image in the stack
399
+
400
+ :rtype: ndarray(Ni..., Nj..., Nk...)
401
+ :return: The transformed stack
402
+ """
403
+ if tmats is None:
404
+ if self._tmats is None:
405
+ raise Exception(
406
+ "No transformation matrices given. Please register first or pass "
407
+ "transformation matrices explicitly."
408
+ )
409
+ tmats = self._tmats
410
+
411
+ if tmats.shape[0] != img.shape[axis]:
412
+ raise Exception(
413
+ "Number of saved transformation matrices does not match stack length"
414
+ )
415
+
416
+ out = img.copy().astype(float)
417
+
418
+ for i in range(img.shape[axis]):
419
+ slc = [slice(None)] * len(out.shape)
420
+ slc[axis] = i
421
+ out[tuple(slc)] = self.transform(simple_slice(img, i, axis), tmats[i, :, :])
422
+
423
+ return out
424
+
425
+ def register_transform_stack(
426
+ self,
427
+ img,
428
+ reference="previous",
429
+ n_frames=1,
430
+ axis=0,
431
+ moving_average=1,
432
+ verbose=False,
433
+ progress_callback=None,
434
+ ):
435
+ """
436
+ Register and transform stack of images (movie).
437
+
438
+ :type img: array_like(Ni..., Nj..., Nk...)
439
+ :param img: The 3D stack of images that should be aligned
440
+
441
+ :type reference: string, one of ['previous', 'first', 'mean']
442
+ :param reference:
443
+ * *'previous'*: Aligns each frame (image) to its previous frame in the
444
+ stack
445
+ * *'first:'* Aligns each frame (image) to the first frame in the stack -
446
+ if n_frames is > 1, then each frame is aligned to the
447
+ mean of the first n_frames of the stack
448
+ * *'mean'*: Aligns each frame (image) to the average of all images in the
449
+ stack
450
+
451
+ :type n_frames: int, optional
452
+ :param n_frames: If reference is 'first', then this parameter specifies the
453
+ number of frames from the beginning of the stack that
454
+ should be averaged to yield the reference image.
455
+
456
+ :type axis: int, optional
457
+ :param axis: The axis of the time dimension
458
+
459
+ :type moving_average: int, optional
460
+ :param moving_average: If moving_average is greater than 1, a moving average of
461
+ the stack is first created (using a subset size of
462
+ moving_average) before registration
463
+
464
+ :type verbose: bool, optional
465
+ :param verbose:
466
+ Specifies whether a progressbar should be shown using tqdm.
467
+
468
+ :type progress_callback: function, optional
469
+ :param progress_callback:
470
+ A function that is called after every iteration. This function should accept
471
+ the keyword arguments current_iteration:int and end_iteration:int.
472
+
473
+ :rtype: ndarray(Ni..., Nj..., Nk...)
474
+ :return: The transformed stack
475
+ """
476
+ self.register_stack(
477
+ img, reference, n_frames, axis, moving_average, verbose, progress_callback
478
+ )
479
+
480
+ return self.transform_stack(img, axis)
@@ -0,0 +1,107 @@
1
+ """
2
+ Collection of utility functions for pystackreg
3
+ """
4
+
5
+ import numpy as np
6
+
7
+
8
+ def to_uint16(arr):
9
+ """
10
+ Converts image data array to a 16 bit unsigned integer array.
11
+
12
+ .. warning:: Data loss may occur as data points outside of 16 bit (0-65535) are
13
+ clipped.
14
+
15
+ StackReg generally output float arrays. This utility function can be used to convert
16
+ such an output array to 16 bit data by clipping to 16 bit (to remove values < 0 and
17
+ greater 16 bit) and rounding the floats.
18
+
19
+ :type arr: array_like (Ni..., M, Nk...)
20
+ :param arr: Source array (usually float)
21
+
22
+ :rtype: ndarray(Ni..., Nj..., Nk...)
23
+ :return: Input array clipped & rounded to unsigned 16 bit integer
24
+ """
25
+ return to_int_dtype(arr, np.uint16)
26
+
27
+
28
+ def to_int_dtype(arr: np.ndarray, dtype: type):
29
+ """
30
+ Converts image data array to an integer array of the given dtype.
31
+
32
+ .. warning:: Data loss may occur as data points outside of the datatypes min/max are
33
+ clipped.
34
+
35
+ StackReg generally output float arrays. This utility function can be used to convert
36
+ such an output array to integer data by clipping to the bounds of the integer dtype
37
+ and rounding the floats.
38
+
39
+ :type arr: array_like (Ni..., M, Nk...)
40
+ :param arr: Source array (usually float)
41
+
42
+ :type dtype: type
43
+ :param dtype: Integer datatype (e.g. np.uint16)
44
+
45
+ :rtype: ndarray(Ni..., Nj..., Nk...)
46
+ :return: Input array clipped & rounded to integer dtype
47
+ """
48
+ assert isinstance(arr, np.ndarray), "Input must be a numpy array"
49
+
50
+ if not np.issubdtype(dtype, np.integer):
51
+ return arr
52
+
53
+ ii = np.iinfo(dtype)
54
+
55
+ return np.round(arr.clip(min=ii.min, max=ii.max)).astype(dtype)
56
+
57
+
58
+ def simple_slice(arr, inds, axis):
59
+ """
60
+ Take elements from an array along an axis.
61
+
62
+ This does the same as np.take() except only supports simple slicing, not
63
+ advanced indexing, and thus is much faster
64
+
65
+ :type arr: array_like (Ni..., M, Nk...)
66
+ :param arr: The source array to slice from
67
+
68
+ :type inds: int or array_like (Nj...)
69
+ :param inds:
70
+ The indices of the values to extract
71
+
72
+ :type axis: int
73
+ :param axis: The axis over which to select values
74
+
75
+ :rtype: ndarray(Ni..., Nj..., Nk...)
76
+ :return: The returned array has the same type as arr
77
+ """
78
+
79
+ sl = [slice(None)] * arr.ndim
80
+ sl[axis] = inds
81
+ return arr[tuple(sl)]
82
+
83
+
84
+ def running_mean(x, N, axis=0):
85
+ """
86
+ Calculate running mean (=moving average) across a given axis.
87
+
88
+ The array is padded with the first and last value such that
89
+ the resulting running mean has the same dimensions as the input array.
90
+
91
+ :type x: array_like (Ni..., Nj..., Nk...)
92
+ :param x: The source array
93
+
94
+ :type N: int
95
+ :param N:
96
+ Number of elements to average over
97
+
98
+ :type axis: int, optional
99
+ :param axis: The axis across which the running mean is calculated
100
+
101
+ :rtype: ndarray(Ni..., Nj..., Nk...)
102
+ :return: The returned array has the same shape and type as x
103
+ """
104
+ pad_width = [[0, 0]] * len(x.shape)
105
+ pad_width[axis] = [int(np.ceil(N / 2)), int(np.floor(N / 2))]
106
+ cumsum = np.cumsum(np.pad(x, pad_width, "edge"), axis=axis)
107
+ return (cumsum[N:] - cumsum[:-N]) / float(N)
pystackreg/version.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.2.8"
@@ -0,0 +1,5 @@
1
+ Authors
2
+ =======
3
+
4
+ * Developer of the original ImageJ plugins TurboReg/StackReg: Philippe Thévenaz (http://bigwww.epfl.ch/thevenaz/)
5
+ * Developer of this package (Port of the Java code from P. Thévenaz to C++ and Python wrapper): Gregor Lichtner `@glichtner <https://github.com/glichtner>`_
@@ -0,0 +1,45 @@
1
+ /**
2
+ * C++ Port of the TurboReg/StackReg ImageJ Plugin
3
+ * Original code by Philippe Thevenaz (see below)
4
+ * Porting by Gregor Lichtner
5
+ */
6
+
7
+ /*====================================================================
8
+ | Philippe Thevenaz
9
+ | EPFL/STI/IMT/LIB/BM.4.137
10
+ | Station 17
11
+ | CH-1015 Lausanne VD
12
+ | Switzerland
13
+ |
14
+ | phone (CET): +41(21)693.51.61
15
+ | fax: +41(21)693.37.01
16
+ | RFC-822: philippe.thevenaz@epfl.ch
17
+ | X-400: /C=ch/A=400net/P=switch/O=epfl/S=thevenaz/G=philippe/
18
+ | URL: http://bigwww.epfl.ch/
19
+ \===================================================================*/
20
+
21
+ /*====================================================================
22
+ | This work is based on the following paper:
23
+ |
24
+ | P. Thevenaz, U.E. Ruttimann, M. Unser
25
+ | A Pyramid Approach to Subpixel Registration Based on Intensity
26
+ | IEEE Transactions on Image Processing
27
+ | vol. 7, no. 1, pp. 27-41, January 1998.
28
+ |
29
+ | This paper is available on-line at
30
+ | http://bigwww.epfl.ch/publications/thevenaz9801.html
31
+ |
32
+ | Other relevant on-line publications are available at
33
+ | http://bigwww.epfl.ch/publications/
34
+ \===================================================================*/
35
+
36
+ /*====================================================================
37
+ | You are free to use this software for commercial and non-commercial
38
+ | purposes. However, we expect you to include a citation or acknowledgement
39
+ | whenever you present or publish research results that are based
40
+ | on this software. You are free to modify this software or derive
41
+ | works from it, but you are only allowed to distribute it under the
42
+ | same terms as this license specifies. Additionally, you must include
43
+ | a reference to the research paper above in all software and works
44
+ | derived from this software.
45
+ \===================================================================*/
@@ -0,0 +1,362 @@
1
+ Metadata-Version: 2.1
2
+ Name: pystackreg
3
+ Version: 0.2.8
4
+ Summary: Image registration tool (python implementation of the ImageJ/FIJI Plugin TurboReg/StackReg)
5
+ Home-page: https://github.com/glichtner/pystackreg
6
+ Author: Gregor Lichtner (python/C++ port);TurboReg Author: Philippe Thévenaz, Biomedical Imaging Group,Swiss Federal Institute of Technology Lausanne
7
+ Classifier: Development Status :: 5 - Production/Stable
8
+ Classifier: Intended Audience :: Science/Research
9
+ Classifier: License :: Free To Use But Restricted
10
+ Classifier: Operating System :: Microsoft :: Windows
11
+ Classifier: Operating System :: Unix
12
+ Classifier: Operating System :: POSIX
13
+ Classifier: Programming Language :: C++
14
+ Classifier: Programming Language :: Python
15
+ Classifier: Programming Language :: Python :: 3.7
16
+ Classifier: Programming Language :: Python :: 3.8
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Topic :: Scientific/Engineering :: Image Processing
22
+ Classifier: Topic :: Utilities
23
+ Description-Content-Type: text/x-rst
24
+ License-File: LICENSE.txt
25
+ License-File: AUTHORS.rst
26
+ Requires-Dist: numpy
27
+ Requires-Dist: tqdm
28
+
29
+ pyStackReg
30
+ ==========
31
+
32
+ .. start-badges
33
+
34
+ .. image:: https://github.com/glichtner/pystackreg/actions/workflows/wheels-deploy.yml/badge.svg
35
+ :target: https://github.com/glichtner/pystackreg/actions/workflows/wheels-deploy.yml
36
+ :alt: Build & Test
37
+
38
+ .. image:: https://readthedocs.org/projects/pystackreg/badge/?version=latest
39
+ :target: https://pystackreg.readthedocs.io/en/latest/?badge=latest
40
+ :alt: Documentation Status
41
+
42
+ .. image:: https://badge.fury.io/py/pystackreg.svg
43
+ :alt: PyPI Package latest release
44
+ :target: https://pypi.org/project/pystackreg
45
+
46
+ .. image:: https://img.shields.io/pypi/pyversions/pystackreg.svg
47
+ :alt: Supported Python Versions
48
+ :target: https://pypi.org/project/pystackreg/
49
+
50
+ .. image:: https://pepy.tech/badge/pystackreg
51
+ :alt: Downloads
52
+ :target: https://pepy.tech/project/pystackreg/
53
+
54
+ .. end-badges
55
+
56
+
57
+
58
+
59
+
60
+ Summary
61
+ -------
62
+ Python/C++ port of the ImageJ extension TurboReg/StackReg written by Philippe Thevenaz/EPFL.
63
+
64
+ A python extension for the automatic alignment of a source image or a stack (movie) to a target image/reference frame.
65
+
66
+ Description
67
+ -----------
68
+ pyStackReg is used to align (register) one or more images to a common reference image, as is required usually in time-resolved fluorescence or wide-field microscopy. It is directly ported from the source code of the ImageJ plugin ``TurboReg`` and provides additionally the functionality of the ImageJ plugin ``StackReg``, both of which were written by Philippe Thevenaz/EPFL (available at http://bigwww.epfl.ch/thevenaz/turboreg/).
69
+
70
+ pyStackReg provides the following five types of distortion:
71
+
72
+ - translation
73
+ - rigid body (translation + rotation)
74
+ - scaled rotation (translation + rotation + scaling)
75
+ - affine (translation + rotation + scaling + shearing)
76
+ - bilinear (non-linear transformation; does not preserve straight lines)
77
+
78
+ pyStackReg supports the full functionality of StackReg plus some additional options, e.g., using different reference images and having access to the actual transformation matrices (please see the examples below). Note that pyStackReg uses the high quality (i.e. high accuracy) mode of TurboReg that uses cubic spline interpolation for transformation.
79
+
80
+ Please note: The bilinear transformation cannot be propagated, as a combination of bilinear transformations does not generally result in a bilinear transformation. Therefore, stack registration/transform functions won't work with bilinear transformation when using "previous" image as reference image. You can either use another reference ("first" or "mean" for first or mean image, respectively), or try to register/transform each image of the stack separately to its respective previous image (and use the already transformed previous image as reference for the next image).
81
+
82
+ Known issues
83
+ ............
84
+ - pystackreg (and StackReg/TurboReg) have known issues with processing strongly rotated images (e.g. by ~90°; see https://github.com/glichtner/pystackreg/issues/30 for a workaround).
85
+
86
+
87
+ Installation
88
+ ------------
89
+ The package is available on conda forge and on PyPi.
90
+
91
+ - Install using **conda**
92
+
93
+ .. code-block:: python
94
+
95
+ conda install pystackreg -c conda-forge
96
+
97
+ - Install using **pip**
98
+
99
+ .. code-block:: python
100
+
101
+ pip install pystackreg
102
+
103
+
104
+ Documentation
105
+ -------------
106
+ The documentation can be found on readthedocs:
107
+
108
+ https://pystackreg.readthedocs.io/
109
+
110
+ Tutorial
111
+ --------
112
+ * A tutorial notebook can be found in the `examples/notebooks` folder
113
+ or statically here: https://pystackreg.readthedocs.io/en/latest/tutorial.html
114
+
115
+ Usage
116
+ -----
117
+ The following example opens two different files and registers them using all different possible transformations
118
+
119
+ .. code-block:: python
120
+
121
+ from pystackreg import StackReg
122
+ from skimage import io
123
+
124
+ #load reference and "moved" image
125
+ ref = io.imread('some_original_image.tif')
126
+ mov = io.imread('some_changed_image.tif')
127
+
128
+ #Translational transformation
129
+ sr = StackReg(StackReg.TRANSLATION)
130
+ out_tra = sr.register_transform(ref, mov)
131
+
132
+ #Rigid Body transformation
133
+ sr = StackReg(StackReg.RIGID_BODY)
134
+ out_rot = sr.register_transform(ref, mov)
135
+
136
+ #Scaled Rotation transformation
137
+ sr = StackReg(StackReg.SCALED_ROTATION)
138
+ out_sca = sr.register_transform(ref, mov)
139
+
140
+ #Affine transformation
141
+ sr = StackReg(StackReg.AFFINE)
142
+ out_aff = sr.register_transform(ref, mov)
143
+
144
+ #Bilinear transformation
145
+ sr = StackReg(StackReg.BILINEAR)
146
+ out_bil = sr.register_transform(ref, mov)
147
+
148
+
149
+ The next example shows how to separate registration from transformation (e.g., to register in one color channel and then use that information to transform another color channel):
150
+
151
+
152
+ .. code-block:: python
153
+
154
+ from pystackreg import StackReg
155
+ from skimage import io
156
+
157
+ img0 = io.imread('some_multiframe_image.tif')
158
+ img1 = io.imread('another_multiframe_image.tif')
159
+ # img0.shape: frames x width x height (3D)
160
+
161
+ sr = StackReg(StackReg.RIGID_BODY)
162
+
163
+ # register 2nd image to 1st
164
+ sr.register(img0[0, :, :], img0[1,:,:])
165
+
166
+ # use the transformation from the above registration to register another frame
167
+ out = sr.transform(img1[1,:,:])
168
+
169
+ The next examples shows how to register and transform a whole stack:
170
+
171
+ .. code-block:: python
172
+
173
+ from pystackreg import StackReg
174
+ from skimage import io
175
+
176
+ img0 = io.imread('some_multiframe_image.tif') # 3 dimensions : frames x width x height
177
+
178
+ sr = StackReg(StackReg.RIGID_BODY)
179
+
180
+ # register each frame to the previous (already registered) one
181
+ # this is what the original StackReg ImageJ plugin uses
182
+ out_previous = sr.register_transform_stack(img0, reference='previous')
183
+
184
+ # register to first image
185
+ out_first = sr.register_transform_stack(img0, reference='first')
186
+
187
+ # register to mean image
188
+ out_mean = sr.register_transform_stack(img0, reference='mean')
189
+
190
+ # register to mean of first 10 images
191
+ out_first10 = sr.register_transform_stack(img0, reference='first', n_frames=10)
192
+
193
+ # calculate a moving average of 10 images, then register the moving average to the mean of
194
+ # the first 10 images and transform the original image (not the moving average)
195
+ out_moving10 = sr.register_transform_stack(img0, reference='first', n_frames=10, moving_average = 10)
196
+
197
+ The next example shows how to separate registration from transformation for a stack (e.g., to register in one color channel and then use that information to transform another color channel):
198
+
199
+ .. code-block:: python
200
+
201
+ from pystackreg import StackReg
202
+ from skimage import io
203
+
204
+ img0 = io.imread('some_multiframe_image.tif') # 3 dimensions : frames x width x height
205
+ img1 = io.imread('another_multiframe_image.tif') # same shape as img0
206
+
207
+ # both stacks must have the same shape
208
+ assert img0.shape == img1.shape
209
+
210
+ sr = StackReg(StackReg.RIGID_BODY)
211
+
212
+ # register each frame to the previous (already registered) one
213
+ # this is what the original StackReg ImageJ plugin uses
214
+ tmats = sr.register_stack(img0, reference='previous')
215
+ out = sr.transform_stack(img1)
216
+
217
+ # tmats contains the transformation matrices -> they can be saved
218
+ # and loaded at another time
219
+ import numpy as np
220
+ np.save('transformation_matrices.npy', tmats)
221
+
222
+ tmats_loaded = np.load('transformation_matrices.npy')
223
+
224
+ # make sure you use the correct transformation here!
225
+ sr = StackReg(StackReg.RIGID_BODY)
226
+
227
+ # transform stack using the tmats loaded from file
228
+ sr.transform_stack(img1, tmats=tmats_loaded)
229
+
230
+ # with the transformation matrices at hand you can also
231
+ # use the transformation algorithms from other packages:
232
+ from skimage import transform as tf
233
+
234
+ out = np.zeros(img0.shape).astype(np.float)
235
+
236
+ for i in range(tmats.shape[0]):
237
+ out[i, :, :] = tf.warp(img1[i, :, :], tmats[i, :, :], order=3)
238
+
239
+
240
+ Author information
241
+ -------------------
242
+ This is a port of the original Java code by Philippe Thevenaz to C++ with a Python wrapper around it. All credit goes to the original author:
243
+ ::
244
+
245
+ /*====================================================================
246
+ | Philippe Thevenaz
247
+ | EPFL/STI/IMT/LIB/BM.4.137
248
+ | Station 17
249
+ | CH-1015 Lausanne VD
250
+ | Switzerland
251
+ |
252
+ | phone (CET): +41(21)693.51.61
253
+ | fax: +41(21)693.37.01
254
+ | RFC-822: philippe.thevenaz@epfl.ch
255
+ | X-400: /C=ch/A=400net/P=switch/O=epfl/S=thevenaz/G=philippe/
256
+ | URL: http://bigwww.epfl.ch/
257
+ \===================================================================*/
258
+
259
+ /*====================================================================
260
+ | This work is based on the following paper:
261
+ |
262
+ | P. Thevenaz, U.E. Ruttimann, M. Unser
263
+ | A Pyramid Approach to Subpixel Registration Based on Intensity
264
+ | IEEE Transactions on Image Processing
265
+ | vol. 7, no. 1, pp. 27-41, January 1998.
266
+ |
267
+ | This paper is available on-line at
268
+ | http://bigwww.epfl.ch/publications/thevenaz9801.html
269
+ |
270
+ | Other relevant on-line publications are available at
271
+ | http://bigwww.epfl.ch/publications/
272
+ \===================================================================*/
273
+
274
+ License
275
+ -------
276
+
277
+ ::
278
+
279
+ You are free to use this software for commercial and non-commercial
280
+ purposes. However, we expect you to include a citation or acknowledgement
281
+ whenever you present or publish research results that are based
282
+ on this software. You are free to modify this software or derive
283
+ works from it, but you are only allowed to distribute it under the
284
+ same terms as this license specifies. Additionally, you must include
285
+ a reference to the research paper above in all software and works
286
+ derived from this software.
287
+
288
+
289
+ Changelog
290
+ =========
291
+
292
+ 0.2.8
293
+ -----
294
+
295
+ Fixed
296
+ .....
297
+ - Add NumPy 2 support
298
+
299
+ 0.2.7
300
+ -----
301
+
302
+ Fixed
303
+ .....
304
+ - Axis argument not used for method "mean" in register_stack() (`PR #26 <https://github.com/glichtner/pystackreg/pull/26>`_)
305
+
306
+ 0.2.6
307
+ -----
308
+
309
+ Added
310
+ .....
311
+ - Exposing `simple_slice` and `running_mean` functions in the util package
312
+ - Added conversion function to any integer dtype
313
+
314
+ 0.2.5
315
+ -----
316
+
317
+ Fixed
318
+ .....
319
+ - Compilation in environments without NumPy
320
+
321
+ 0.2.3
322
+ -----
323
+
324
+ Added
325
+ .....
326
+ - Added example data and tutorial notebook
327
+ - Added unit tests
328
+ - Additional documentation
329
+ - Detection of time series axis in stacks – will raise a warning if supplied axis in stack registration does not correspond to the detected axis
330
+
331
+ Changed
332
+ .....~~
333
+ - `progress_callback` function now gets called with the iteration number, not the iteration index (iteration number = iteration index + 1)
334
+
335
+ Fixed
336
+ .....
337
+ - Fixed exception when using a different axis than 0 for registering stacks
338
+
339
+ 0.2.2
340
+ -----
341
+
342
+ Changed
343
+ .....~~
344
+ - License changed to allow distribution on Python package repositories
345
+
346
+ 0.2.1
347
+ -----
348
+
349
+ Added
350
+ .....
351
+ - Progress callback function can be supplied to `register_stack()` and `register_transform_stack()` functions via the `progress_callback` parameter. It is called after every iteration (i.e., after each image registration).
352
+
353
+ Changed
354
+ .....~~
355
+ - Progress bar output is not shown by default, has to be enabled by using the `verbose=True` parameter in the `register_stack()` and `register_transform_stack()` functions
356
+
357
+ 0.2.0
358
+ -----
359
+
360
+ Added
361
+ .....
362
+ - Bilinear transformation
@@ -0,0 +1,12 @@
1
+ pystackreg/conftest.py,sha256=uxY9sruCWV4u38fOkiKUZbkXMJIgueCgH9-9o2psJTA,94
2
+ pystackreg/version.py,sha256=G6Dbxq2ws-1ZAXwDD8q0KWueYtso_Y6Uyvtj8sRWsPI,22
3
+ pystackreg/__init__.py,sha256=5J3C1ouoj-JQti6AvXiR3O2q9a_hLRRaiyqVkoE9r8c,90
4
+ pystackreg/pystackreg.py,sha256=VfIM_uqxo-i-6MK-B9Qi1A0jbwiaEwa25_cV8peFBMs,16082
5
+ pystackreg/turboreg.cpython-313-darwin.so,sha256=NDkErLp8am59a6l668e2j7skyLsZvUEhU9HbnzUGup8,183152
6
+ pystackreg/util/__init__.py,sha256=oWJXIvbiT2tfyINSxNcWyaQZNN6RVezaVhQdky0_wx8,3208
7
+ pystackreg-0.2.8.dist-info/RECORD,,
8
+ pystackreg-0.2.8.dist-info/WHEEL,sha256=L5Yzp3Ie3qzhKJYO8ywXtZfSISbcpXt4-U2h3P52Hng,109
9
+ pystackreg-0.2.8.dist-info/AUTHORS.rst,sha256=ZHn3Q1pwnIJAtUSo6nsZlc8JR_8iFKCRHlnE0tj6r8Q,291
10
+ pystackreg-0.2.8.dist-info/top_level.txt,sha256=qoYoHJMwck_foa97p1OZ--g0IdqGo7AFRQOsJmblwLY,11
11
+ pystackreg-0.2.8.dist-info/LICENSE.txt,sha256=krxPdzz7Jq9yg9IjsW_rKYvaW5f_GO-VBuBf4zlzJUk,1793
12
+ pystackreg-0.2.8.dist-info/METADATA,sha256=47m8oM_gb_DWg9Z3zjX1-ovTKGxe-Ilw0BUe7ZkzhPY,12388
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.1.0)
3
+ Root-Is-Purelib: false
4
+ Tag: cp313-cp313-macosx_11_0_arm64
5
+
@@ -0,0 +1 @@
1
+ pystackreg