[5d12a0]: / ants / contrib / sampling / affine2d.py

Download this file

655 lines (538 with data), 21.7 kB

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
"""
Affine transforms
See http://www.cs.cornell.edu/courses/cs4620/2010fa/lectures/03transforms3D.pdf
"""
__all__ = [
"Zoom2D",
"RandomZoom2D",
"Rotate2D",
"RandomRotate2D",
"Shear2D",
"RandomShear2D",
"Translate2D",
"RandomTranslate2D",
]
import random
import math
import numpy as np
from ...core import ants_transform as tio
class Translate2D(object):
"""
Create an ANTs Affine Transform with a specified translation.
"""
def __init__(self, translation, reference=None, lazy=False):
"""
Initialize a Translate2D object
Arguments
---------
translation : list or tuple
translation values for each axis, in degrees.
Negative values can be used for translation in the
other direction
reference : ANTsImage (optional but recommended)
image providing the reference space for the transform.
this will also set the transform fixed parameters.
lazy : boolean (default = False)
if True, calling the `transform` method only returns
the randomly generated transform and does not actually
transform the image
"""
if (not isinstance(translation, (list, tuple))) or (len(translation) != 2):
raise ValueError("translation argument must be list/tuple with two values!")
self.translation = translation
self.lazy = lazy
self.reference = reference
self.tx = tio.ANTsTransform(
precision="float", dimension=2, transform_type="AffineTransform"
)
if self.reference is not None:
self.tx.set_fixed_parameters(self.reference.get_center_of_mass())
def transform(self, X=None, y=None):
"""
Transform an image using an Affine transform with the given
translation parameters. Return the transform if X=None.
Arguments
---------
X : ANTsImage
Image to transform
y : ANTsImage (optional)
Another image to transform
Returns
-------
ANTsImage if y is None, else a tuple of ANTsImage types
Examples
--------
>>> import ants
>>> img = ants.image_read(ants.get_data('r16'))
>>> tx = ants.contrib.Translate2D(translation=(10,0))
>>> img2_x = tx.transform(img)
>>> tx = ants.contrib.Translate2D(translation=(-10,0)) # other direction
>>> img2_x = tx.transform(img)
>>> tx = ants.contrib.Translate2D(translation=(0,10))
>>> img2_z = tx.transform(img)
>>> tx = ants.contrib.Translate2D(translation=(10,10))
>>> img2 = tx.transform(img)
"""
# convert to radians and unpack
translation_x, translation_y = self.translation
translation_matrix = np.array([[1, 0, translation_x], [0, 1, translation_y]])
self.tx.set_parameters(translation_matrix)
if self.lazy or X is None:
return self.tx
else:
if y is None:
return self.tx.apply_to_image(X, reference=self.reference)
else:
return (
self.tx.apply_to_image(X, reference=self.reference),
self.tx.apply_to_image(y, reference=self.reference),
)
class RandomTranslate2D(object):
"""
Apply a Translate2D transform to an image, but with the
parameters randomly generated from a user-specified range.
The range is determined by a mean (first parameter) and standard deviation
(second parameter) via calls to random.gauss.
"""
def __init__(self, translation_range, reference=None, lazy=False):
"""
Initialize a RandomTranslate2D object
Arguments
---------
translation_range : list or tuple
Lower and Upper bounds on rotation parameter, in degrees.
e.g. translation_range = (-10,10) will result in a random
draw of the rotation parameters between -10 and 10 degrees
reference : ANTsImage (optional but recommended)
image providing the reference space for the transform.
this will also set the transform fixed parameters.
lazy : boolean (default = False)
if True, calling the `transform` method only returns
the randomly generated transform and does not actually
transform the image
"""
if (not isinstance(translation_range, (list, tuple))) or (
len(translation_range) != 2
):
raise ValueError("shear_range argument must be list/tuple with two values!")
self.translation_range = translation_range
self.reference = reference
self.lazy = lazy
def transform(self, X=None, y=None):
"""
Transform an image using an Affine transform with
translation parameters randomly generated from the user-specified
range. Return the transform if X=None.
Arguments
---------
X : ANTsImage
Image to transform
y : ANTsImage (optional)
Another image to transform
Returns
-------
ANTsImage if y is None, else a tuple of ANTsImage types
Examples
--------
>>> import ants
>>> img = ants.image_read(ants.get_data('r16'))
>>> tx = ants.contrib.RandomShear2D(translation_range=(-10,10))
>>> img2 = tx.transform(img)
"""
# random draw in translation range
translation_x = random.gauss(
self.translation_range[0], self.translation_range[1]
)
translation_y = random.gauss(
self.translation_range[0], self.translation_range[1]
)
self.params = (translation_x, translation_y)
tx = Translate2D(
(translation_x, translation_y), reference=self.reference, lazy=self.lazy
)
return tx.transform(X, y)
class Shear2D(object):
"""
Create an ANTs Affine Transform with a specified shear.
"""
def __init__(self, shear, reference=None, lazy=False):
"""
Initialize a Shear2D object
Arguments
---------
shear : list or tuple
shear values for each axis, in degrees.
Negative values can be used for shear in the
other direction
reference : ANTsImage (optional but recommended)
image providing the reference space for the transform.
this will also set the transform fixed parameters.
lazy : boolean (default = False)
if True, calling the `transform` method only returns
the randomly generated transform and does not actually
transform the image
"""
if (not isinstance(shear, (list, tuple))) or (len(shear) != 2):
raise ValueError("shear argument must be list/tuple with two values!")
self.shear = shear
self.lazy = lazy
self.reference = reference
self.tx = tio.ANTsTransform(
precision="float", dimension=2, transform_type="AffineTransform"
)
if self.reference is not None:
self.tx.set_fixed_parameters(self.reference.get_center_of_mass())
def transform(self, X=None, y=None):
"""
Transform an image using an Affine transform with the given
shear parameters. Return the transform if X=None.
Arguments
---------
X : ANTsImage
Image to transform
y : ANTsImage (optional)
Another image to transform
Returns
-------
ANTsImage if y is None, else a tuple of ANTsImage types
Examples
--------
>>> import ants
>>> img = ants.image_read(ants.get_data('r16'))
>>> tx = ants.contrib.Shear2D(shear=(10,0,0))
>>> img2_x = tx.transform(img)# x axis stays same
>>> tx = ants.contrib.Shear2D(shear=(-10,0,0)) # other direction
>>> img2_x = tx.transform(img)# x axis stays same
>>> tx = ants.contrib.Shear2D(shear=(0,10,0))
>>> img2_y = tx.transform(img) # y axis stays same
>>> tx = ants.contrib.Shear2D(shear=(0,0,10))
>>> img2_z = tx.transform(img) # z axis stays same
>>> tx = ants.contrib.Shear2D(shear=(10,10,10))
>>> img2 = tx.transform(img)
"""
# convert to radians and unpack
shear = [math.pi / 180 * s for s in self.shear]
shear_x, shear_y = shear
shear_matrix = np.array([[1, shear_x, 0], [shear_y, 1, 0]])
self.tx.set_parameters(shear_matrix)
if self.lazy or X is None:
return self.tx
else:
if y is None:
return self.tx.apply_to_image(X, reference=self.reference)
else:
return (
self.tx.apply_to_image(X, reference=self.reference),
self.tx.apply_to_image(y, reference=self.reference),
)
class RandomShear2D(object):
"""
Apply a Shear2D transform to an image, but with the shear
parameters randomly generated from a user-specified range.
The range is determined by a mean (first parameter) and standard deviation
(second parameter) via calls to random.gauss.
"""
def __init__(self, shear_range, reference=None, lazy=False):
"""
Initialize a RandomShear2D object
Arguments
---------
shear_range : list or tuple
Lower and Upper bounds on rotation parameter, in degrees.
e.g. shear_range = (-10,10) will result in a random
draw of the rotation parameters between -10 and 10 degrees
reference : ANTsImage (optional but recommended)
image providing the reference space for the transform.
this will also set the transform fixed parameters.
lazy : boolean (default = False)
if True, calling the `transform` method only returns
the randomly generated transform and does not actually
transform the image
"""
if (not isinstance(shear_range, (list, tuple))) or (len(shear_range) != 2):
raise ValueError("shear_range argument must be list/tuple with two values!")
self.shear_range = shear_range
self.reference = reference
self.lazy = lazy
def transform(self, X=None, y=None):
"""
Transform an image using an Affine transform with
shear parameters randomly generated from the user-specified
range. Return the transform if X=None.
Arguments
---------
X : ANTsImage
Image to transform
y : ANTsImage (optional)
Another image to transform
Returns
-------
ANTsImage if y is None, else a tuple of ANTsImage types
Examples
--------
>>> import ants
>>> img = ants.image_read(ants.get_data('r16'))
>>> tx = ants.contrib.RandomShear2D(shear_range=(-10,10))
>>> img2 = tx.transform(img)
"""
# random draw in shear range
shear_x = random.gauss(self.shear_range[0], self.shear_range[1])
shear_y = random.gauss(self.shear_range[0], self.shear_range[1])
self.params = (shear_x, shear_y)
tx = Shear2D((shear_x, shear_y), reference=self.reference, lazy=self.lazy)
return tx.transform(X, y)
class Rotate2D(object):
"""
Create an ANTs Affine Transform with a specified level
of rotation.
"""
def __init__(self, rotation, reference=None, lazy=False):
"""
Initialize a Rotate2D object
Arguments
---------
rotation : scalar
rotation value in degrees.
Negative values can be used for rotation in the
other direction
reference : ANTsImage (optional but recommended)
image providing the reference space for the transform.
this will also set the transform fixed parameters.
lazy : boolean (default = False)
if True, calling the `transform` method only returns
the randomly generated transform and does not actually
transform the image
"""
self.rotation = rotation
self.lazy = lazy
self.reference = reference
self.tx = tio.ANTsTransform(
precision="float", dimension=2, transform_type="AffineTransform"
)
if self.reference is not None:
self.tx.set_fixed_parameters(self.reference.get_center_of_mass())
def transform(self, X=None, y=None):
"""
Transform an image using an Affine transform with the given
rotation parameters. Return the transform if X=None.
Arguments
---------
X : ANTsImage
Image to transform
y : ANTsImage (optional)
Another image to transform
Returns
-------
ANTsImage if y is None, else a tuple of ANTsImage types
Examples
--------
>>> import ants
>>> img = ants.image_read(ants.get_data('r16'))
>>> tx = ants.contrib.Rotate2D(rotation=(10,-5,12))
>>> img2 = tx.transform(img)
"""
# unpack zoom range
rotation = self.rotation
# Rotation about X axis
theta = math.pi / 180 * rotation
rotation_matrix = np.array(
[[np.cos(theta), -np.sin(theta), 0], [np.sin(theta), np.cos(theta), 0]]
)
self.tx.set_parameters(rotation_matrix)
if self.lazy or X is None:
return self.tx
else:
if y is None:
return self.tx.apply_to_image(X, reference=self.reference)
else:
return (
self.tx.apply_to_image(X, reference=self.reference),
self.tx.apply_to_image(y, reference=self.reference),
)
class RandomRotate2D(object):
"""
Apply a Rotated2D transform to an image, but with the zoom
parameters randomly generated from a user-specified range.
The range is determined by a mean (first parameter) and standard deviation
(second parameter) via calls to random.gauss.
"""
def __init__(self, rotation_range, reference=None, lazy=False):
"""
Initialize a RandomRotate2D object
Arguments
---------
rotation_range : list or tuple
Lower and Upper bounds on rotation parameter, in degrees.
e.g. rotation_range = (-10,10) will result in a random
draw of the rotation parameters between -10 and 10 degrees
reference : ANTsImage (optional but recommended)
image providing the reference space for the transform.
this will also set the transform fixed parameters.
lazy : boolean (default = False)
if True, calling the `transform` method only returns
the randomly generated transform and does not actually
transform the image
"""
if (not isinstance(rotation_range, (list, tuple))) or (
len(rotation_range) != 2
):
raise ValueError(
"rotation_range argument must be list/tuple with two values!"
)
self.rotation_range = rotation_range
self.reference = reference
self.lazy = lazy
def transform(self, X=None, y=None):
"""
Transform an image using an Affine transform with
rotation parameters randomly generated from the user-specified
range. Return the transform if X=None.
Arguments
---------
X : ANTsImage
Image to transform
y : ANTsImage (optional)
Another image to transform
Returns
-------
ANTsImage if y is None, else a tuple of ANTsImage types
Examples
--------
>>> import ants
>>> img = ants.image_read(ants.get_data('r16'))
>>> tx = ants.contrib.RandomRotate2D(rotation_range=(-10,10))
>>> img2 = tx.transform(img)
"""
# random draw in rotation range
rotation = random.gauss(self.rotation_range[0], self.rotation_range[1])
self.params = rotation
tx = Rotate2D(rotation, reference=self.reference, lazy=self.lazy)
return tx.transform(X, y)
class Zoom2D(object):
"""
Create an ANTs Affine Transform with a specified level
of zoom. Any value greater than 1 implies a "zoom-out" and anything
less than 1 implies a "zoom-in".
"""
def __init__(self, zoom, reference=None, lazy=False):
"""
Initialize a Zoom2D object
Arguments
---------
zoom_range : list or tuple
Lower and Upper bounds on zoom parameter.
e.g. zoom_range = (0.7,0.9) will result in a random
draw of the zoom parameters between 0.7 and 0.9
reference : ANTsImage (optional but recommended)
image providing the reference space for the transform.
this will also set the transform fixed parameters.
lazy : boolean (default = False)
if True, calling the `transform` method only returns
the randomly generated transform and does not actually
transform the image
"""
if (not isinstance(zoom, (list, tuple))) or (len(zoom) != 2):
raise ValueError("zoom_range argument must be list/tuple with two values!")
self.zoom = zoom
self.lazy = lazy
self.reference = reference
self.tx = tio.ANTsTransform(
precision="float", dimension=2, transform_type="AffineTransform"
)
if self.reference is not None:
self.tx.set_fixed_parameters(self.reference.get_center_of_mass())
def transform(self, X=None, y=None):
"""
Transform an image using an Affine transform with the given
zoom parameters. Return the transform if X=None.
Arguments
---------
X : ANTsImage
Image to transform
y : ANTsImage (optional)
Another image to transform
Returns
-------
ANTsImage if y is None, else a tuple of ANTsImage types
Examples
--------
>>> import ants
>>> img = ants.image_read(ants.get_data('r16'))
>>> tx = ants.contrib.Zoom2D(zoom=(0.8,0.8,0.8))
>>> img2 = tx.transform(img)
"""
# unpack zoom range
zoom_x, zoom_y = self.zoom
self.params = (zoom_x, zoom_y)
zoom_matrix = np.array([[zoom_x, 0, 0], [0, zoom_y, 0]])
self.tx.set_parameters(zoom_matrix)
if self.lazy or X is None:
return self.tx
else:
if y is None:
return self.tx.apply_to_image(X, reference=self.reference)
else:
return (
self.tx.apply_to_image(X, reference=self.reference),
self.tx.apply_to_image(y, reference=self.reference),
)
class RandomZoom2D(object):
"""
Apply a Zoom2D transform to an image, but with the zoom
parameters randomly generated from a user-specified range.
The range is determined by a mean (first parameter) and standard deviation
(second parameter) via calls to random.gauss.
"""
def __init__(self, zoom_range, reference=None, lazy=False):
"""
Initialize a RandomZoom2D object
Arguments
---------
zoom_range : list or tuple
Lower and Upper bounds on zoom parameter.
e.g. zoom_range = (0.7,0.9) will result in a random
draw of the zoom parameters between 0.7 and 0.9
reference : ANTsImage (optional but recommended)
image providing the reference space for the transform.
this will also set the transform fixed parameters.
lazy : boolean (default = False)
if True, calling the `transform` method only returns
the randomly generated transform and does not actually
transform the image
"""
if (not isinstance(zoom_range, (list, tuple))) or (len(zoom_range) != 2):
raise ValueError("zoom_range argument must be list/tuple with two values!")
self.zoom_range = zoom_range
self.reference = reference
self.lazy = lazy
def transform(self, X=None, y=None):
"""
Transform an image using an Affine transform with
zoom parameters randomly generated from the user-specified
range. Return the transform if X=None.
Arguments
---------
X : ANTsImage
Image to transform
y : ANTsImage (optional)
Another image to transform
Returns
-------
ANTsImage if y is None, else a tuple of ANTsImage types
Examples
--------
>>> import ants
>>> img = ants.image_read(ants.get_data('r16'))
>>> tx = ants.contrib.RandomZoom2D(zoom_range=(0.8,0.9))
>>> img2 = tx.transform(img)
"""
# random draw in zoom range
zoom_x = np.exp(
random.gauss(np.log(self.zoom_range[0]), np.log(self.zoom_range[1]))
)
zoom_y = np.exp(
random.gauss(np.log(self.zoom_range[0]), np.log(self.zoom_range[1]))
)
self.params = (zoom_x, zoom_y)
tx = Zoom2D((zoom_x, zoom_y), reference=self.reference, lazy=self.lazy)
return tx.transform(X, y)