[5d12a0]: / ants / core / ants_image.py

Download this file

689 lines (550 with data), 20.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
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
__all__ = ['ANTsImage',
'copy_image_info',
'set_origin',
'get_origin',
'set_direction',
'get_direction',
'set_spacing',
'get_spacing',
'is_image',
'from_pointer']
import os
import numpy as np
import pandas as pd
from functools import partialmethod
import inspect
import ants
from ants.internal import get_lib_fn
_supported_ptypes = {'unsigned char', 'unsigned int', 'float', 'double'}
_supported_dtypes = {'uint8', 'uint32', 'float32', 'float64'}
_itk_to_npy_map = {
'unsigned char': 'uint8',
'unsigned int': 'uint32',
'float': 'float32',
'double': 'float64'}
_npy_to_itk_map = {
'uint8': 'unsigned char',
'uint32':'unsigned int',
'float32': 'float',
'float64': 'double'}
class ANTsImage(object):
def __init__(self, pointer):
"""
Initialize an ANTsImage.
Creating an ANTsImage requires a pointer to an underlying ITK image that
is stored via a nanobind class wrapping a AntsImage struct.
Arguments
---------
pointer : nb::class
nanobind class wrapping the struct holding the pointer to the underlying ITK image object
"""
self.pointer = pointer
self.channels_first = False
self._array = None
@property
def _libsuffix(self):
return str(type(self.pointer)).split('AntsImage')[-1].split("'")[0]
@property
def shape(self):
return tuple(get_lib_fn('getShape')(self.pointer))
@property
def physical_shape(self):
return tuple([round(sh*sp,3) for sh,sp in zip(self.shape, self.spacing)])
@property
def is_rgb(self):
return 'RGB' in self._libsuffix
@property
def has_components(self):
suffix = self._libsuffix
return suffix.startswith('V') or suffix.startswith('RGB')
@property
def components(self):
if not self.has_components:
return 1
return get_lib_fn('getComponents')(self.pointer)
@property
def pixeltype(self):
ptype = self._libsuffix[:-1]
if self.has_components:
if self.is_rgb:
ptype = ptype[3:]
else:
ptype = ptype[1:]
ptype_map = {'UC': 'unsigned char',
'UI': 'unsigned int',
'F': 'float',
'D': 'double'}
return ptype_map[ptype]
@property
def dtype(self):
return _itk_to_npy_map[self.pixeltype]
@property
def dimension(self):
return int(self._libsuffix[-1])
@property
def spacing(self):
"""
Get image spacing
Returns
-------
tuple
"""
return tuple(get_lib_fn('getSpacing')(self.pointer))
def set_spacing(self, new_spacing):
"""
Set image spacing
Arguments
---------
new_spacing : tuple or list
updated spacing for the image.
should have one value for each dimension
Returns
-------
None
"""
if not isinstance(new_spacing, (tuple, list)):
raise ValueError('arg must be tuple or list')
if len(new_spacing) != self.dimension:
raise ValueError('must give a spacing value for each dimension (%i)' % self.dimension)
get_lib_fn('setSpacing')(self.pointer, new_spacing)
@property
def origin(self):
"""
Get image origin
Returns
-------
tuple
"""
return tuple(get_lib_fn('getOrigin')(self.pointer))
def set_origin(self, new_origin):
"""
Set image origin
Arguments
---------
new_origin : tuple or list
updated origin for the image.
should have one value for each dimension
Returns
-------
None
"""
if not isinstance(new_origin, (tuple, list)):
raise ValueError('arg must be tuple or list')
if len(new_origin) != self.dimension:
raise ValueError('must give a origin value for each dimension (%i)' % self.dimension)
get_lib_fn('setOrigin')(self.pointer, new_origin)
@property
def direction(self):
"""
Get image direction
Returns
-------
tuple
"""
return np.array(get_lib_fn('getDirection')(self.pointer)).reshape(self.dimension,self.dimension)
def set_direction(self, new_direction):
"""
Set image direction
Arguments
---------
new_direction : numpy.ndarray or tuple or list
updated direction for the image.
should have one value for each dimension
Returns
-------
None
"""
if isinstance(new_direction, (tuple,list)):
new_direction = np.asarray(new_direction)
if not isinstance(new_direction, np.ndarray):
raise ValueError('arg must be np.ndarray or tuple or list')
if len(new_direction) != self.dimension:
raise ValueError('must give a origin value for each dimension (%i)' % self.dimension)
get_lib_fn('setDirection')(self.pointer, new_direction)
@property
def orientation(self):
if self.dimension == 3:
return self.get_orientation()
else:
return None
def view(self, single_components=False):
"""
Geet a numpy array providing direct, shared access to the image data.
IMPORTANT: If you alter the view, then the underlying image data
will also be altered.
Arguments
---------
single_components : boolean (default is False)
if True, keep the extra component dimension in returned array even
if image only has one component (i.e. self.has_components == False)
Returns
-------
ndarray
"""
if self.is_rgb:
img = self.rgb_to_vector()
else:
img = self
dtype = img.dtype
shape = img.shape[::-1]
if img.has_components or (single_components == True):
shape = list(shape) + [img.components]
memview = get_lib_fn('toNumpy')(img.pointer)
return np.asarray(memview).view(dtype = dtype).reshape(shape).view(np.ndarray).T
def numpy(self, single_components=False):
"""
Get a numpy array copy representing the underlying image data. Altering
this ndarray will have NO effect on the underlying image data.
Arguments
---------
single_components : boolean (default is False)
if True, keep the extra component dimension in returned array even
if image only has one component (i.e. self.has_components == False)
Returns
-------
ndarray
"""
array = np.array(self.view(single_components=single_components), copy=True, dtype=self.dtype)
if self.has_components or (single_components == True):
if not self.channels_first:
array = np.rollaxis(array, 0, self.dimension+1)
return array
def astype(self, dtype):
"""
Cast & clone an ANTsImage to a given numpy datatype.
Map:
uint8 : unsigned char
uint32 : unsigned int
float32 : float
float64 : double
"""
if dtype not in _supported_dtypes:
raise ValueError('Datatype %s not supported. Supported types are %s' % (dtype, _supported_dtypes))
pixeltype = _npy_to_itk_map[dtype]
return self.clone(pixeltype)
def to_file(self, filename):
"""
Write the ANTsImage to file
Args
----
filename : string
filepath to which the image will be written
"""
filename = os.path.expanduser(filename)
get_lib_fn('toFile')(self.pointer, filename)
to_filename = to_file
def apply(self, fn):
"""
Apply an arbitrary function to ANTsImage.
Args
----
fn : python function or lambda
function to apply to ENTIRE image at once
Returns
-------
ANTsImage
image with function applied to it
"""
this_array = self.numpy()
new_array = fn(this_array)
return self.new_image_like(new_array)
## NUMPY FUNCTIONS ##
def abs(self, axis=None):
""" Return absolute value of image """
return np.abs(self.numpy())
def mean(self, axis=None):
""" Return mean along specified axis """
return self.numpy().mean(axis=axis)
def median(self, axis=None):
""" Return median along specified axis """
return np.median(self.numpy(), axis=axis)
def std(self, axis=None):
""" Return std along specified axis """
return self.numpy().std(axis=axis)
def sum(self, axis=None, keepdims=False):
""" Return sum along specified axis """
return self.numpy().sum(axis=axis, keepdims=keepdims)
def min(self, axis=None):
""" Return min along specified axis """
return self.numpy().min(axis=axis)
def max(self, axis=None):
""" Return max along specified axis """
return self.numpy().max(axis=axis)
def range(self, axis=None):
""" Return range tuple along specified axis """
return (self.min(axis=axis), self.max(axis=axis))
def argmin(self, axis=None):
""" Return argmin along specified axis """
return self.numpy().argmin(axis=axis)
def argmax(self, axis=None):
""" Return argmax along specified axis """
return self.numpy().argmax(axis=axis)
def argrange(self, axis=None):
""" Return argrange along specified axis """
amin = self.argmin(axis=axis)
amax = self.argmax(axis=axis)
if axis is None:
return (amin, amax)
else:
return np.stack([amin, amax]).T
def flatten(self):
""" Flatten image data """
return self.numpy().flatten()
def nonzero(self):
""" Return non-zero indices of image """
return self.numpy().nonzero()
def unique(self, sort=False):
""" Return unique set of values in image """
unique_vals = np.unique(self.numpy())
if sort:
unique_vals = np.sort(unique_vals)
return unique_vals
## OVERLOADED OPERATORS ##
def __add__(self, other):
this_array = self.numpy()
if is_image(other):
if not ants.image_physical_space_consistency(self, other):
raise ValueError('images do not occupy same physical space')
other = other.numpy()
new_array = this_array + other
return self.new_image_like(new_array)
__radd__ = __add__
def __sub__(self, other):
this_array = self.numpy()
if is_image(other):
if not ants.image_physical_space_consistency(self, other):
raise ValueError('images do not occupy same physical space')
other = other.numpy()
new_array = this_array - other
return self.new_image_like(new_array)
def __rsub__(self, other):
this_array = self.numpy()
if is_image(other):
if not ants.image_physical_space_consistency(self, other):
raise ValueError('images do not occupy same physical space')
other = other.numpy()
new_array = other - this_array
return self.new_image_like(new_array)
def __mul__(self, other):
this_array = self.numpy()
if is_image(other):
if not ants.image_physical_space_consistency(self, other):
raise ValueError('images do not occupy same physical space')
other = other.numpy()
new_array = this_array * other
return self.new_image_like(new_array)
__rmul__ = __mul__
def __truediv__(self, other):
this_array = self.numpy()
if is_image(other):
if not ants.image_physical_space_consistency(self, other):
raise ValueError('images do not occupy same physical space')
other = other.numpy()
new_array = this_array / other
return self.new_image_like(new_array)
def __pow__(self, other):
this_array = self.numpy()
if is_image(other):
if not ants.image_physical_space_consistency(self, other):
raise ValueError('images do not occupy same physical space')
other = other.numpy()
new_array = this_array ** other
return self.new_image_like(new_array)
def __gt__(self, other):
this_array = self.numpy()
if is_image(other):
if not ants.image_physical_space_consistency(self, other):
raise ValueError('images do not occupy same physical space')
other = other.numpy()
new_array = this_array > other
return self.new_image_like(new_array.astype('uint8'))
def __ge__(self, other):
this_array = self.numpy()
if is_image(other):
if not ants.image_physical_space_consistency(self, other):
raise ValueError('images do not occupy same physical space')
other = other.numpy()
new_array = this_array >= other
return self.new_image_like(new_array.astype('uint8'))
def __lt__(self, other):
this_array = self.numpy()
if is_image(other):
if not ants.image_physical_space_consistency(self, other):
raise ValueError('images do not occupy same physical space')
other = other.numpy()
new_array = this_array < other
return self.new_image_like(new_array.astype('uint8'))
def __le__(self, other):
this_array = self.numpy()
if is_image(other):
if not ants.image_physical_space_consistency(self, other):
raise ValueError('images do not occupy same physical space')
other = other.numpy()
new_array = this_array <= other
return self.new_image_like(new_array.astype('uint8'))
def __eq__(self, other):
this_array = self.numpy()
if is_image(other):
if not ants.image_physical_space_consistency(self, other):
raise ValueError('images do not occupy same physical space')
other = other.numpy()
new_array = this_array == other
return self.new_image_like(new_array.astype('uint8'))
def __ne__(self, other):
this_array = self.numpy()
if is_image(other):
if not ants.image_physical_space_consistency(self, other):
raise ValueError('images do not occupy same physical space')
other = other.numpy()
new_array = this_array != other
return self.new_image_like(new_array.astype('uint8'))
def __getitem__(self, idx):
if self.has_components:
return ants.merge_channels([
img[idx] for img in ants.split_channels(self)
])
if isinstance(idx, ANTsImage):
if not ants.image_physical_space_consistency(self, idx):
raise ValueError('images do not occupy same physical space')
return self.numpy().__getitem__(idx.numpy().astype('bool'))
# convert idx to tuple if it is not, eg im[10] or im[10:20]
if not isinstance(idx, tuple):
idx = (idx,)
ndim = len(self.shape)
if len(idx) > ndim:
raise ValueError('Too many indices for image')
if len(idx) < ndim:
# If not all dimensions are indexed, assume the rest are full slices
# eg im[10] -> im[10, :, :]
idx = idx + (slice(None),) * (ndim - len(idx))
sizes = list(self.shape)
starts = [0] * ndim
stops = list(self.shape)
for i in range(ndim):
ti = idx[i]
if isinstance(ti, slice):
if ti.start:
starts[i] = ti.start
if ti.stop:
if ti.stop < 0:
stops[i] = self.shape[i] + ti.stop
else:
stops[i] = ti.stop
sizes[i] = stops[i] - starts[i]
if stops[i] < starts[i]:
raise ValueError('Reverse indexing is not supported.')
elif isinstance(ti, int):
starts[i] = ti
sizes[i] = 0
if sizes[i] == 0:
ndim -= 1
if ndim < 2:
return self.numpy().__getitem__(idx)
libfn = get_lib_fn('getItem%i' % ndim)
new_ptr = libfn(self.pointer, starts, sizes)
new_image = from_pointer(new_ptr)
return new_image
def __setitem__(self, idx, value):
arr = self.view()
if is_image(value):
value = value.numpy()
if is_image(idx):
if not ants.image_physical_space_consistency(self, idx):
raise ValueError('images do not occupy same physical space')
arr.__setitem__(idx.numpy().astype('bool'), value)
else:
arr.__setitem__(idx, value)
def __iter__(self):
# Do not allow iteration on ANTsImage. Builtin iteration, eg sum(), will generally be much slower
# than using numpy methods. We need to explicitly disallow it to prevent breaking object state.
raise TypeError("ANTsImage is not iterable. See docs for available functions, or use numpy.")
def __repr__(self):
if self.dimension == 3:
s = 'ANTsImage ({})\n'.format(self.orientation)
else:
s = 'ANTsImage\n'
s = s +\
'\t {:<10} : {} ({})\n'.format('Pixel Type', self.pixeltype, self.dtype)+\
'\t {:<10} : {}{}\n'.format('Components', self.components, ' (RGB)' if 'RGB' in self._libsuffix else '')+\
'\t {:<10} : {}\n'.format('Dimensions', self.shape)+\
'\t {:<10} : {}\n'.format('Spacing', tuple([round(s,4) for s in self.spacing]))+\
'\t {:<10} : {}\n'.format('Origin', tuple([round(o,4) for o in self.origin]))+\
'\t {:<10} : {}\n'.format('Direction', np.round(self.direction.flatten(),4))
return s
def __getstate__(self):
"""
import ants
import pickle
import numpy as np
from copy import deepcopy
img = ants.image_read( ants.get_ants_data("r16"))
img_pickled = pickle.dumps(img)
img2 = pickle.loads(img_pickled)
img3 = deepcopy(img)
img += 10
print(img.mean(), img3.mean())
"""
return self.numpy(), self.origin, self.spacing, self.direction, self.has_components, self.is_rgb
def __setstate__(self, state):
data, origin, spacing, direction, has_components, is_rgb = state
image = ants.from_numpy(np.copy(data), origin=origin, spacing=spacing, direction=direction, has_components=has_components, is_rgb=is_rgb)
self.__dict__ = image.__dict__
def copy_image_info(reference, target):
"""
Copy origin, direction, and spacing from one antsImage to another
ANTsR function: `antsCopyImageInfo`
Arguments
---------
reference : ANTsImage
Image to get values from.
target : ANTsImAGE
Image to copy values to
Returns
-------
ANTsImage
Target image with reference header information
"""
target.set_origin(reference.origin)
target.set_direction(reference.direction)
target.set_spacing(reference.spacing)
return target
def set_origin(image, origin):
"""
Set origin of ANTsImage
ANTsR function: `antsSetOrigin`
"""
image.set_origin(origin)
def get_origin(image):
"""
Get origin of ANTsImage
ANTsR function: `antsGetOrigin`
"""
return image.origin
def set_direction(image, direction):
"""
Set direction of ANTsImage
ANTsR function: `antsSetDirection`
"""
image.set_direction(direction)
def get_direction(image):
"""
Get direction of ANTsImage
ANTsR function: `antsGetDirection`
"""
return image.direction
def set_spacing(image, spacing):
"""
Set spacing of ANTsImage
ANTsR function: `antsSetSpacing`
"""
image.set_spacing(spacing)
def get_spacing(image):
"""
Get spacing of ANTsImage
ANTsR function: `antsGetSpacing`
"""
return image.spacing
def is_image(object):
return isinstance(object, ANTsImage)
def from_pointer(pointer):
return ANTsImage(pointer)