File: vmtkimagewriter.py

package info (click to toggle)
vmtk 1.0.1-3
  • links: PTS, VCS
  • area: non-free
  • in suites: jessie, jessie-kfreebsd
  • size: 8,632 kB
  • ctags: 8,076
  • sloc: cpp: 79,872; ansic: 31,817; python: 18,860; perl: 381; makefile: 118; sh: 15; tcl: 1
file content (270 lines) | stat: -rw-r--r-- 11,310 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
#!/usr/bin/env python

## Program:   VMTK
## Module:    $RCSfile: vmtkimagewriter.py,v $
## Language:  Python
## Date:      $Date: 2006/07/27 08:27:40 $
## Version:   $Revision: 1.18 $

##   Copyright (c) Luca Antiga, David Steinman. All rights reserved.
##   See LICENCE file for details.

##      This software is distributed WITHOUT ANY WARRANTY; without even 
##      the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
##      PURPOSE.  See the above copyright notices for more information.

import vtk
import vtkvmtk
import sys

import pypes

vmtkimagewriter = 'vmtkImageWriter'

class vmtkImageWriter(pypes.pypeScript):

    def __init__(self):

        pypes.pypeScript.__init__(self)

        self.Format = ''
        self.GuessFormat = 1
        self.UseITKIO = 1
        self.ApplyTransform = 0
        self.OutputFileName = ''
        self.OutputRawFileName = ''
        self.OutputDirectoryName = ''
      	self.PixelRepresentation = ''
        self.Image = None
        self.Input = None
      	self.WindowLevel = [1.0, 0.0]
        self.RasToIjkMatrixCoefficients = [1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]

        self.SetScriptName('vmtkimagewriter')
        self.SetScriptDoc('write an image to disk')
        self.SetInputMembers([
            ['Image','i','vtkImageData',1,'','the input image','vmtkimagereader'],
            ['Format','f','str',1,'["vtkxml","vtk","meta","tiff","png","pointdata"]','file format'],
            ['GuessFormat','guessformat','bool',1,'','guess file format from extension'],
            ['UseITKIO','useitk','bool',1,'','use ITKIO mechanism'],
            ['ApplyTransform','transform','bool',1,'','apply transform on writing - ITKIO only'],
            ['OutputFileName','ofile','str',1,'','output file name'],
            ['OutputFileName','o','str',1,'','output file name (deprecated: use -ofile)'],
            ['OutputRawFileName','rawfile','str',1,'','name of the output raw file - meta image only'],
            ['OutputDirectoryName','d','str',1,'','output directory name - png, tiff'],
            ['PixelRepresentation','r','str',1,'["double","float","short"]','output scalar type'],
            ['WindowLevel','windowlevel','float',2,'','window and level for mapping graylevels to 0-255 before writing - png, tiff'],
            ['RasToIjkMatrixCoefficients','matrix','float',16]
            ])
        self.SetOutputMembers([])

    def WriteVTKImageFile(self):
        if (self.OutputFileName == ''):
            self.PrintError('Error: no OutputFileName.')
        self.PrintLog('Writing VTK image file.')
        writer = vtk.vtkStructuredPointsWriter()
        writer.SetInput(self.Image)
        writer.SetFileName(self.OutputFileName)
        writer.Write()

    def WriteVTKXMLImageFile(self):
        if (self.OutputFileName == ''):
            self.PrintError('Error: no OutputFileName.')
        self.PrintLog('Writing VTK XML image file.')
        writer = vtk.vtkXMLImageDataWriter()
        writer.SetInput(self.Image)
        writer.SetFileName(self.OutputFileName)
        writer.Write()

    def WriteMetaImageFile(self):
        if (self.OutputFileName == ''):
            self.PrintError('Error: no OutputFileName.')
        self.PrintLog('Writing meta image file.')
        writer = vtk.vtkMetaImageWriter()
        writer.SetInput(self.Image)
        writer.SetFileName(self.OutputFileName)
        if (self.OutputRawFileName != ''):
            writer.SetRAWFileName(self.OutputRawFileName)
        writer.Write()

    def WritePNGImageFile(self):
        if (self.OutputFileName == ''):
            self.PrintError('Error: no OutputFileName.')
        self.PrintLog('Writing PNG image file.')
        outputImage = self.Image
        if self.Image.GetScalarTypeAsString() != 'unsigned char':
            shiftScale = vtk.vtkImageShiftScale()
            shiftScale.SetInput(self.Image)
            if self.WindowLevel[0] == 0.0:
                scalarRange = self.Image.GetScalarRange()
                shiftScale.SetShift(-scalarRange[0])
                shiftScale.SetScale(255.0/(scalarRange[1]-scalarRange[0]))
            else:
                shiftScale.SetShift(-(self.WindowLevel[1]-self.WindowLevel[0]/2.0))
                shiftScale.SetScale(255.0/self.WindowLevel[0])
            shiftScale.SetOutputScalarTypeToUnsignedChar()
            shiftScale.ClampOverflowOn()
            shiftScale.Update()
            outputImage = shiftScale.GetOutput()
        writer = vtk.vtkPNGWriter()
        writer.SetInput(outputImage)
        if self.Image.GetDimensions()[2] == 1:
            writer.SetFileName(self.OutputFileName)
        else:
            writer.SetFilePrefix(self.OutputFileName)
            writer.SetFilePattern("%s%04d.png")
        writer.Write()

    def WriteTIFFImageFile(self):
        if (self.OutputFileName == ''):
            self.PrintError('Error: no OutputFileName.')
        self.PrintLog('Writing TIFF image file.')
        outputImage = self.Image
        if self.Image.GetScalarTypeAsString() != 'unsigned char':
            shiftScale = vtk.vtkImageShiftScale()
            shiftScale.SetInput(self.Image)
            if self.WindowLevel[0] == 0.0:
                scalarRange = self.Image.GetScalarRange()
                shiftScale.SetShift(-scalarRange[0])
                shiftScale.SetScale(255.0/(scalarRange[1]-scalarRange[0]))
            else: 
                shiftScale.SetShift(-(self.WindowLevel[1]-self.WindowLevel[0]/2.0))
                shiftScale.SetScale(255.0/self.WindowLevel[0])
            shiftScale.SetOutputScalarTypeToUnsignedChar()
            shiftScale.ClampOverflowOn()
            shiftScale.Update()
            outputImage = shiftScale.GetOutput()
        writer = vtk.vtkTIFFWriter()
        writer.SetInput(outputImage)
        if self.Image.GetDimensions()[2] == 1:
            writer.SetFileName(self.OutputFileName)
        else:
            writer.SetFilePrefix(self.OutputFileName)
            writer.SetFilePattern("%s%04d.tif")
        writer.Write()

    def WritePointDataImageFile(self):
        if (self.OutputFileName == ''):
            self.PrintError('Error: no OutputFileName.')
        self.PrintLog('Writing PointData file.')
        f=open(self.OutputFileName, 'w')
        line = "X Y Z"
        arrayNames = []
        if self.Image.GetPointData().GetScalars().GetName() == None:
            self.Image.GetPointData().GetScalars().SetName('__Scalars')
        for i in range(self.Image.GetPointData().GetNumberOfArrays()):
            array = self.Image.GetPointData().GetArray(i)
            arrayName = array.GetName()
            if arrayName == None:
                continue
            if arrayName[-1]=='_':
                continue
            arrayNames.append(arrayName)
            if array.GetNumberOfComponents() == 1:
                line = line + ' ' + arrayName
            else:
                for j in range(array.GetNumberOfComponents()):
                    line = line + ' ' + arrayName + str(j)
        line = line + '\n'
        f.write(line)
        for i in range(self.Image.GetNumberOfPoints()):
            point = self.Image.GetPoint(i)
            line = str(point[0]) + ' ' + str(point[1]) + ' ' + str(point[2])
            for arrayName in arrayNames:
                array = self.Image.GetPointData().GetArray(arrayName)
                for j in range(array.GetNumberOfComponents()):
                    line = line + ' ' + str(array.GetComponent(i,j))
            line = line + '\n'
            f.write(line)

    def WriteITKIO(self):
        if self.OutputFileName == '':
            self.PrintError('Error: no OutputFileName.')
        writer = vtkvmtk.vtkvmtkITKImageWriter()
        writer.SetInput(self.Image)
        writer.SetFileName(self.OutputFileName)
        writer.SetUseCompression(1)
        if self.ApplyTransform and self.RasToIjkMatrixCoefficients:
            matrix = vtk.vtkMatrix4x4()
            matrix.DeepCopy(self.RasToIjkMatrixCoefficients)
            writer.SetRasToIJKMatrix(matrix)
        writer.Write()
 
    def Execute(self):

        if self.Image == None:
            if self.Input == None:
                self.PrintError('Error: no Image.')
            self.Image = self.Input

        extensionFormats = {'vti':'vtkxml', 
                            'vtkxml':'vtkxml', 
                            'vtk':'vtk',
                            'mhd':'meta',
                            'mha':'meta',
                            'tif':'tiff',
                            'png':'png',
                            'dat':'pointdata'}

        if self.OutputFileName == 'BROWSER':
            import tkFileDialog
            import os.path
            initialDir = pypes.pypeScript.lastVisitedPath
            self.OutputFileName = tkFileDialog.asksaveasfilename(title="Output image",initialdir=initialDir)
            pypes.pypeScript.lastVisitedPath = os.path.dirname(self.OutputFileName)
            if not self.OutputFileName:
                self.PrintError('Error: no OutputFileName.')

        if self.OutputDirectoryName == 'BROWSER':
            import tkFileDialog
            initialDir = pypes.pypeScript.lastVisitedPath
            self.OutputDirectoryName = tkFileDialog.askdirectory(title="Output directory",initialdir=initialDir)
            pypes.pypeScript.lastVisitedPath = self.OutputDirectoryName
            if not self.OutputDirectoryName:
                self.PrintError('Error: no OutputDirectoryName.')

        if self.GuessFormat and self.OutputFileName and not self.Format:
            import os.path
            extension = os.path.splitext(self.OutputFileName)[1]
            if extension:
                extension = extension[1:]
                if extension in extensionFormats.keys():
                    self.Format = extensionFormats[extension]

      	if self.PixelRepresentation != '':
            cast = vtk.vtkImageCast()
            cast.SetInput(self.Image)
            if self.PixelRepresentation == 'double':
                cast.SetOutputScalarTypeToDouble()
            elif self.PixelRepresentation == 'float':
                cast.SetOutputScalarTypeToFloat()
            elif self.PixelRepresentation == 'short':
                cast.SetOutputScalarTypeToShort()
      	    else:
                self.PrintError('Error: unsupported pixel representation '+ self.PixelRepresentation + '.')
            cast.Update()
            self.Image = cast.GetOutput()

        if self.UseITKIO and self.Format not in ['vtkxml','vtk','tiff','png','dat']:
            self.WriteITKIO()
        else:	
            if (self.Format == 'vtkxml'):
                self.WriteVTKXMLImageFile()
            elif (self.Format == 'vtk'):
                self.WriteVTKImageFile()
            elif (self.Format == 'meta'):
                self.WriteMetaImageFile()
            elif (self.Format == 'png'):
                self.WritePNGImageFile()
            elif (self.Format == 'tiff'):
                self.WriteTIFFImageFile()
            elif (self.Format == 'pointdata'):
                self.WritePointDataImageFile()
            else:
                self.PrintError('Error: unsupported format '+ self.Format + '.')


if __name__=='__main__':
    main = pypes.pypeMain()
    main.Arguments = sys.argv
    main.Execute()