a b/ants/utils/consistency.py
1
import numpy as np
2
import ants
3
from ants.decorators import image_method
4
5
__all__ = ['image_physical_space_consistency',
6
           'allclose']
7
8
@image_method
9
def image_physical_space_consistency(image1, image2, tolerance=1e-2, datatype=False):
10
    """
11
    Check if two or more ANTsImage objects occupy the same physical space
12
13
    ANTsR function: `antsImagePhysicalSpaceConsistency`
14
15
    Arguments
16
    ---------
17
    *images : ANTsImages
18
        images to compare
19
20
    tolerance : float
21
        tolerance when checking origin and spacing
22
23
    data_type : boolean
24
        If true, also check that the image data types are the same
25
26
    Returns
27
    -------
28
    boolean
29
        true if images share same physical space, false otherwise
30
    """
31
    images = [image1, image2]
32
33
    img1 = images[0]
34
    for img2 in images[1:]:
35
        if (not ants.is_image(img1)) or (not ants.is_image(img2)):
36
            raise ValueError('Both images must be of class `AntsImage`')
37
38
        # image dimension check
39
        if img1.dimension != img2.dimension:
40
            return False
41
42
        # image spacing check
43
        space_diffs = sum([abs(s1-s2)>tolerance for s1, s2 in zip(img1.spacing, img2.spacing)])
44
        if space_diffs > 0:
45
            return False
46
47
        # image origin check
48
        origin_diffs = sum([abs(s1-s2)>tolerance for s1, s2 in zip(img1.origin, img2.origin)])
49
        if origin_diffs > 0:
50
            return False
51
52
        # image direction check
53
        origin_diff = np.allclose(img1.direction, img2.direction, atol=tolerance)
54
        if not origin_diff:
55
            return False
56
57
        # data type
58
        if datatype == True:
59
            if img1.pixeltype != img2.pixeltype:
60
                return False
61
62
            if img1.components != img2.components:
63
                return False
64
65
    return True
66
67
68
@image_method
69
def allclose(image1, image2):
70
    """
71
    Check if two images have the same array values
72
    """
73
    return np.allclose(image1.numpy(), image2.numpy())