#!/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= ' ')