Passed
Push — master ( 9ae791...b80c39 )
by Fernando
01:28
created

tests.data.test_io.TestIO.test_matrix_itk()   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
import tempfile
2
import unittest
3
from pathlib import Path
4
import torch
5
import numpy as np
6
import SimpleITK as sitk
7
from ..utils import TorchioTestCase
8
from torchio.data import io
9
10
11
class TestIO(TorchioTestCase):
12
    """Tests for `io` module."""
13
    def setUp(self):
14
        super().setUp()
15
        self.write_dicom()
16
        string = (
17
            '1.5 0.18088 -0.124887 0.65072 '
18
            '-0.20025 0.965639 -0.165653 -11.6452 '
19
            '0.0906326 0.18661 0.978245 11.4002 '
20
            '0 0 0 1 '
21
        )
22
        tensor = torch.from_numpy(np.fromstring(string, sep=' ').reshape(4, 4))
23
        self.matrix = tensor
24
25
    def write_dicom(self):
26
        self.dicom_dir = self.dir / 'dicom'
27
        self.dicom_dir.mkdir(exist_ok=True)
28
        self.dicom_path = self.dicom_dir / 'dicom.dcm'
29
        self.nii_path = self.get_image_path('read_image')
30
        writer = sitk.ImageFileWriter()
31
        writer.SetFileName(str(self.dicom_path))
32
        image = sitk.ReadImage(str(self.nii_path))
33
        image = sitk.Cast(image, sitk.sitkUInt16)
34
        image = image[0]  # dicom reader supports 2D only
35
        writer.Execute(image)
36
37
    def test_read_image(self):
38
        # I need to find something readable by nib but not sitk
39
        io.read_image(self.nii_path)
40
        io.read_image(self.nii_path, itk_first=True)
41
42
    def test_read_dicom_file(self):
43
        io.read_image(self.dicom_path)
44
45
    def test_read_dicom_dir(self):
46
        io.read_image(self.dicom_dir)
47
48
    def test_dicom_dir_missing(self):
49
        with self.assertRaises(FileNotFoundError):
50
            io._read_dicom('missing')
51
52
    def test_dicom_dir_no_files(self):
53
        empty = self.dir / 'empty'
54
        empty.mkdir()
55
        with self.assertRaises(FileNotFoundError):
56
            io._read_dicom(empty)
57
58
    def write_read_matrix(self, suffix):
59
        out_path = self.dir / f'matrix{suffix}'
60
        io.write_matrix(self.matrix, out_path)
61
        matrix = io.read_matrix(out_path)
62
        assert torch.allclose(matrix, self.matrix)
63
64
    def test_matrix_itk(self):
65
        self.write_read_matrix('.tfm')
66
        self.write_read_matrix('.h5')
67
68
    def test_matrix_txt(self):
69
        self.write_read_matrix('.txt')
70