|
| 1 | +"""Read/write ITK transforms.""" |
| 2 | +import numpy as np |
| 3 | +from .base import StringBasedStruct |
| 4 | + |
| 5 | + |
| 6 | +class ITKLinearTransform(StringBasedStruct): |
| 7 | + template_dtype = np.dtype([ |
| 8 | + ('type', 'i4'), |
| 9 | + ('id', 'i4'), |
| 10 | + ('parameters', 'f4', (4, 4)), |
| 11 | + ('offset', 'f4', 3), # Center of rotation |
| 12 | + ]) |
| 13 | + dtype = template_dtype |
| 14 | + |
| 15 | + def __init__(self): |
| 16 | + super().__init__() |
| 17 | + self.structarr['offset'] = [0, 0, 0] |
| 18 | + self.structarr['id'] = 1 |
| 19 | + |
| 20 | + def to_string(self, banner=True): |
| 21 | + sa = self.structarr |
| 22 | + lines = [ |
| 23 | + '#Transform {:d}'.format(sa['id']), |
| 24 | + 'Transform: MatrixOffsetTransformBase_double_3_3', |
| 25 | + 'Parameters: {}'.format(' '.join( |
| 26 | + ['%g' % p |
| 27 | + for p in sa['parameters'][:3, :3].reshape(-1).tolist() + |
| 28 | + sa['parameters'][:3, 3].tolist()])), |
| 29 | + 'FixedParameters: {:g} {:g} {:g}'.format(*sa['offset']), |
| 30 | + '', |
| 31 | + ] |
| 32 | + if banner: |
| 33 | + lines.insert(0, '#Insight Transform File V1.0') |
| 34 | + return '\n'.join(lines) |
| 35 | + |
| 36 | + @classmethod |
| 37 | + def from_string(klass, string): |
| 38 | + tf = klass() |
| 39 | + sa = tf.structarr |
| 40 | + lines = [l for l in string.splitlines() |
| 41 | + if l.strip()] |
| 42 | + assert lines[0][0] == '#' |
| 43 | + if lines[1][0] == '#': |
| 44 | + lines = lines[1:] # Drop banner with version |
| 45 | + |
| 46 | + parameters = np.eye(4, dtype='f4') |
| 47 | + sa['id'] = int(lines[0][lines[0].index('T'):].split()[1]) |
| 48 | + sa['offset'] = np.genfromtxt([lines[3].split(':')[-1].encode()], |
| 49 | + dtype=klass.dtype['offset']) |
| 50 | + vals = np.genfromtxt([lines[2].split(':')[-1].encode()], |
| 51 | + dtype='f4') |
| 52 | + parameters[:3, :3] = vals[:-3].reshape((3, 3)) |
| 53 | + parameters[:3, 3] = vals[-3:] |
| 54 | + sa['parameters'] = parameters |
| 55 | + return tf |
| 56 | + |
| 57 | + @classmethod |
| 58 | + def from_fileobj(klass, fileobj, check=True): |
| 59 | + return klass.from_string(fileobj.read()) |
| 60 | + |
| 61 | + |
| 62 | +class ITKLinearTransformArray(StringBasedStruct): |
| 63 | + template_dtype = np.dtype([('nxforms', 'i4')]) |
| 64 | + dtype = template_dtype |
| 65 | + _xforms = None |
| 66 | + |
| 67 | + def __init__(self, |
| 68 | + xforms=None, |
| 69 | + binaryblock=None, |
| 70 | + endianness=None, |
| 71 | + check=True): |
| 72 | + super().__init__(binaryblock, endianness, check) |
| 73 | + self._xforms = [] |
| 74 | + for mat in xforms or []: |
| 75 | + xfm = ITKLinearTransform() |
| 76 | + xfm['parameters'] = mat |
| 77 | + self._xforms.append(xfm) |
| 78 | + |
| 79 | + def __getitem__(self, idx): |
| 80 | + if idx == 'xforms': |
| 81 | + return self._xforms |
| 82 | + if idx == 'nxforms': |
| 83 | + return len(self._xforms) |
| 84 | + return super().__getitem__(idx) |
| 85 | + |
| 86 | + def to_string(self): |
| 87 | + strings = [] |
| 88 | + for i, xfm in enumerate(self._xforms): |
| 89 | + xfm.structarr['id'] = i + 1 |
| 90 | + strings.append(xfm.to_string(banner=False)) |
| 91 | + strings.insert(0, '#Insight Transform File V1.0') |
| 92 | + return '\n'.join(strings) |
| 93 | + |
| 94 | + @classmethod |
| 95 | + def from_string(klass, string): |
| 96 | + _self = klass() |
| 97 | + sa = _self.structarr |
| 98 | + |
| 99 | + lines = [l.strip() for l in string.splitlines() |
| 100 | + if l.strip()] |
| 101 | + |
| 102 | + if lines[0][0] != '#' or 'Insight Transform File V1.0' not in lines[0]: |
| 103 | + raise ValueError('Unknown Insight Transform File format.') |
| 104 | + |
| 105 | + string = '\n'.join(lines[1:]) |
| 106 | + for xfm in string.split('#')[1:]: |
| 107 | + _self._xforms.append(ITKLinearTransform.from_string( |
| 108 | + '#%s' % xfm)) |
| 109 | + return _self |
| 110 | + |
| 111 | + @classmethod |
| 112 | + def from_fileobj(klass, fileobj, check=True): |
| 113 | + return klass.from_string(fileobj.read()) |
0 commit comments