a b/ants/ops/slice_image.py
1
2
__all__ = ['slice_image']
3
4
import math
5
import numpy as np
6
import ants
7
from ants.decorators import image_method
8
from ants.internal import get_lib_fn
9
10
@image_method
11
def slice_image(image, axis, idx, collapse_strategy=0):
12
    """
13
    Slice an image.
14
15
    Arguments
16
    ---------
17
    axis: integer 
18
        Which axis.
19
20
    idx: integer
21
        Which slice number.    
22
23
    collapse_strategy:  integer
24
        Collapse strategy for sub-matrix: 0, 1, or 2.  0: collapse to sub-matrix 
25
        if positive-definite.  Otherwise throw an exception. Default.  1: Collapse 
26
        to identity.  2:  Collapse to sub-matrix if positive definite. Otherwise
27
        collapse to identity.
28
29
    Example
30
    -------
31
    >>> import ants
32
    >>> mni = ants.image_read(ants.get_data('mni'))
33
    >>> mni2 = ants.slice_image(mni, axis=1, idx=100)
34
    """
35
    if image.has_components:
36
        ilist = ants.split_channels(image)
37
        if image.dimension == 2:
38
            return np.stack(tuple([i.slice_image(axis, idx, collapse_strategy) for i in ilist]), axis=-1)
39
        else:
40
            return ants.merge_channels([i.slice_image(axis, idx, collapse_strategy) for i in ilist])
41
    
42
    if axis == -1:
43
        axis = image.dimension - 1
44
        
45
    if axis > (image.dimension - 1) or axis < 0:
46
        raise Exception('The axis must be between 0 and image.dimension - 1')
47
        
48
    if image.dimension == 2:
49
        if axis == 0:
50
            return image[idx,:]
51
        elif axis == 1:
52
            return image[:,idx]
53
        raise Exception('Parameters not understood for 2D image.')
54
        
55
    if collapse_strategy != 0 and collapse_strategy != 1 and collapse_strategy != 2:
56
        raise ValueError('collapse_strategy must be 0, 1, or 2.') 
57
58
    inpixeltype = image.pixeltype
59
    ndim = image.dimension
60
    if image.pixeltype != 'float':
61
        image = image.clone('float')
62
63
    libfn = get_lib_fn('sliceImage')
64
    itkimage = libfn(image.pointer, axis, idx, collapse_strategy)
65
66
    return ants.from_pointer(itkimage).clone(inpixeltype)
67
68