a b/ants/utils/channels.py
1
2
 
3
4
__all__ = ['merge_channels',
5
           'split_channels']
6
7
8
9
10
import ants
11
from ants.internal import get_lib_fn
12
from ants.decorators import image_method
13
14
15
def merge_channels(image_list, channels_first=False):
16
    """
17
    Merge channels of multiple scalar ANTsImage types into one 
18
    multi-channel ANTsImage
19
    
20
    ANTsR function: `mergeChannels`
21
22
    Arguments
23
    ---------
24
    image_list : list/tuple of ANTsImage types
25
        scalar images to merge
26
    
27
    Returns
28
    -------
29
    ANTsImage
30
31
    Example
32
    -------
33
    >>> import ants
34
    >>> image = ants.image_read(ants.get_ants_data('r16'))
35
    >>> image2 = ants.image_read(ants.get_ants_data('r16'))
36
    >>> image3 = ants.merge_channels([image,image2])
37
    >>> image3 = ants.merge_channels([image,image2], channels_first=True)
38
    >>> image3.numpy()
39
    >>> image3.components == 2
40
    """
41
    inpixeltype = image_list[0].pixeltype
42
    dimension = image_list[0].dimension
43
    components = len(image_list)
44
45
    for image in image_list:
46
        if not ants.is_image(image):
47
            raise ValueError('list may only contain ANTsImage objects')
48
        if image.pixeltype != inpixeltype:
49
            raise ValueError('all images must have the same pixeltype')
50
51
    libfn = get_lib_fn('mergeChannels')
52
    image_ptr = libfn([image.pointer for image in image_list])
53
    
54
    image = ants.from_pointer(image_ptr)
55
    image.channels_first = channels_first
56
    return image
57
58
@image_method
59
def split_channels(image):
60
    """
61
    Split channels of a multi-channel ANTsImage into a collection
62
    of scalar ANTsImage types
63
    
64
    Arguments
65
    ---------
66
    image : ANTsImage
67
        multi-channel image to split
68
69
    Returns
70
    -------
71
    list of ANTsImage types
72
73
    Example
74
    -------
75
    >>> import ants
76
    >>> image = ants.image_read(ants.get_ants_data('r16'), 'float')
77
    >>> image2 = ants.image_read(ants.get_ants_data('r16'), 'float')
78
    >>> imagemerge = ants.merge_channels([image,image2])
79
    >>> imagemerge.components == 2
80
    >>> images_unmerged = ants.split_channels(imagemerge)
81
    >>> len(images_unmerged) == 2
82
    >>> images_unmerged[0].components == 1
83
    """
84
    inpixeltype = image.pixeltype
85
    dimension = image.dimension
86
    components = 1
87
88
    libfn = get_lib_fn('splitChannels')
89
    itkimages = libfn(image.pointer)
90
    antsimages = [ants.from_pointer(itkimage) for itkimage in itkimages]
91
    return antsimages
92
93
94
95