Newer
Older
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 17 16:06:05 2019
@author: vand
"""
import numpy as np
def save_gray2vtk(volume,filename,filetype='ASCII',origin=(0,0,0),\
spacing=(1,1,1),dataname='gray'):
''' Writes a vtk file with grayscace volume data
Arguments:
volume: a grayscale volume, values will be saved as floats
filename: filename with .vtk extension
filetype: file type 'ASCII' or 'BINARY'. Writing a binary file might not
work for all OS due to big/little endian issues.
origin: volume origin, defaluls to (0,0,0)
spacing: volume spacing, defaults to 1
dataname: name associated wiht data (will be visible in Paraview)
Author:vand@dtu.dk, 2019
'''
with open(filename, 'w') as f:
# writing header
f.write('# vtk DataFile Version 3.0\n')
f.write('saved from python using save_gray2vtk\n')
f.write('{}\n'.format(filetype))
f.write('DATASET STRUCTURED_POINTS\n')
f.write('DIMENSIONS {} {} {}\n'.format(\
volume.shape[0],volume.shape[1],volume.shape[2]))
f.write('ORIGIN {} {} {}\n'.format(origin[0],origin[1],origin[2]))
f.write('SPACING {} {} {}\n'.format(spacing[0],spacing[1],spacing[2]))
f.write('POINT_DATA {}\n'.format(volume.size))
f.write('SCALARS {} float 1\n'.format(dataname))
f.write('LOOKUP_TABLE default\n')
# writing volume data
if filetype.upper()=='BINARY':
with open(filename, 'ab') as f:
volume = volume.astype('float32') # Pareview expects 4-bytes float
volume.byteswap(True) # Paraview expects big-endian
volume.tofile(f)
else: # ASCII
with open(filename, 'a') as f:
np.savetxt(f,volume.ravel(),fmt='%.5g', newline= ' ')