File Exchange

image thumbnail

vtkwrite : Exports various 2D/3D data to ParaView in VTK file format

version 2.3 (14.6 KB) by

Exports 2D/3D image volume, vector field, surface, lines, polygons, etc. to ParaView

4.91304
26 Ratings

116 Downloads

Updated

Paraview is a powerful open-source software for visualization of large 3D dataset. It offers more options, details and much better performance than built-in Matlab 3D visualization modules. This function is an integration of several previous submissions regarding export of 3D data into VTK format. The function can save multiple vector and scalar field of the same size into a single VTK-formatted file to be viewed in ParaView. It can also export line or polygon objects. To maximize compatibility between different operating system, numerical data is by default saved in ascii format with precision of 3 digits behind decimal point. User can specify precision , e.g. vtkwrite('execute', 'structured_points', 'mri', D, 'precision, 5), instead of vtkwrite('execute', 'structured_points', 'mri', D). User can also choose to save numerical data in 'float' data type ( this option is not available for POLYDATA dataset type) by adding 'binary' to the command, e.g. vtkwrite('execute', 'structured_points', 'mri', D, binary).
Here are some example usages. Just type in the following codes.
Example 1 : export 3D array (typical of an image volume )

load mri
D = squeeze(D);
vtkwrite('mri.vtk', 'structured_points', 'mri', D)

If you've already setup system path to include the folder containing the ParaView binary, you can invoke ParaView directly by:

vtkwrite('execute', 'structured_points', 'mri', D)

In this case, a file named 'matlab_export.vtk' is saved and passed on to ParaView.

Example 2 : export 3D vector and scalar field

load wind
[cu,cv,cw] = curl(x, y, z, u, v, w);
div = divergence(x, y, z, u, v, w);
vtkwrite('wind.vtk', 'structured_grid', x, y, z, ...
'vectors', 'vector_field', u, v, w, 'vectors', 'vorticity', cu, cv, cw, 'scalars', 'divergence', div);

Usage is very similar for unstructured 3D data. Just change 'structured_grid' to 'unstructured_grid'. For example :

vtkwrite('random_vector.vtk', 'unstructured_grid',x,y,z, 'vectors','random_vector',u,v,w,)

Example 3 : export 3D line

x = 1:100;
y = sin(x);
z = sqrt(x);
vtkwrite('execute','polydata','lines',x,y,z);
optionally, user can specify precision of data output(default is 3). for example:

vtkwrite('line.vtk','polydata','lines',x,y,z,'precision',5);
Example 4 : export triangular data

[x,y,z] = peaks(100);
z = .4*z;
tri = delaunay(x,y);
vtkwrite('peaks.vtk','polydata','triangle',x,y,z,tri);

Example 5 : export tetrahedral data

d = [-1 1];
[x, y, z] = meshgrid(d, d, d);
DT = delaunayTriangulation(x(:), y(:), z(:));
vtkwrite('execute', 'polydata','tetrahedron', x, y, z, DT.ConnectivityList);

The usage of vector and scalar field input is the same as built-in quiver3 and scatter3 function, where x,y,z specifies the coordinates of the grid points and u,v,w the vector components. For multiple data array entry, they must have the same number of grid points. x,y,z only need to be specified once, followed by combination of [keyword, title, data]. You can add however many data arrays as you want. In the example above, you'll end up with a single VTK file with three data arrays of the same number of grid points. In the sample screenshot, the color of the arrow represents the magnitude of divergence.

In Paraview, press 'ctrl+o' to open file. Then on properties page immediately below pipeline browser, click 'Apply'. For line and polygon data, you should already see the correct representation of data. For 3D vector field, you have to further click on 'glyph' in the common toolbar, then choose the glyph object in the pipeline browser and click 'Apply'.

See file for more details on usage.

Comments and Ratings (59)

Javad

Javad (view profile)

Dear Joe
I have a set of data points the same as for "wind" file in Matlab (x, y and z 3D matrix+ Vx, Vy, and Vz (velocity)).
I have employed your function to convert this set of data points to a *.vtk file. But when I run the Example #2 (as you have mentioned) it does not work and an error happens as "Error using vtkwrite (line 83)
1 or 4 numeric inputs expected!
Error in paraa (line 12)
vtkwrite('wind.vtk', 'structured_grid', x, y, z, ... "

If possible please help me. How can I correct this error?

Regards

Dante

Dante (view profile)

Henry Zhou

Hi Joe,
When I run example 2 with unstructured grid in 2017b and read it into paraview5.4 on Mac, it seems like there`s a file format issue which causes paraview to crash. Can you fix this?
Thanks!

OPITEC

OPITEC (view profile)

Hi Joe,

Does your script support non-uniform grid?

I want to show a scalar dataset on a non-uniform grid.

[X,Y,Z] = meshgrid(x,y,z) ; % x,y,z are non-uniform
vtkwrite('file.vtk', 'structured_grid', X,Y,Z, 'scalars', 'Intensity', intensity);

However, Paraview did not show anything.

I tried to use: vtkwrite('file.vtk','structured_points','Intensity',intensity);
and then Paraview showed the dataset.

DongHo Shin

I found some error. At the line 75, 'vin' is not defined variable. It should be modified to 'varargin'. This code is great.

Ashish Kumar

Hey Chaitanya!
Use meshgrid in matlab to create your mesh.

Lolaylak

Thanks!!!!

Joe Yeh

Joe Yeh (view profile)

m p, maybe you can try : !/usr/bin/paraview --data='matlab_export.vtk' &

Swarup

Swarup (view profile)

m p

m p (view profile)

Hello, Thanks for the script. I am using linux and Octave. I get the error while setting the path, I am using this:
!cd /usr/bin/paraview --data='matlab_export.vtk' &
^
as you can see it indicates error in data. Do you have any suggestion to correct this?
Thanks and best regards, Mahmoud

Michael Tso

excellent!

I found out you left out a 1 after "SCALAR (title) float" in the generated .vtk file. But everything else works perfectly!

AlessandroM

Hello Joe,

I have a matrix of size (100, 4). Out of these 4 columns, 2 columns contain the 'x' and 'y' coordinates of all the points on the mesh while the other 2 columns contain the value of solution 'u' and 'v' on that point. 'u' is the solution in 'x' direction while 'v' is the solution in 'y' direction. The matrix is sorted like this:

x y u v
0 0 0.55 -0.03
1 0 0.04 0.34
. . . .
. . . .
100 0 -0.9 0.1
0 1 . .
1 1 . .

I use the following command to generate vtk, but I don't see anything in paraview. Here 'out' is the name of my matrix. 'Z' and 'w' are zero valued vectors.

X = out(:, 1); Y = out(:, 2); Z = out(:,3); u = out(:,4); v = out(:,5); w = out(:,6);
vtkwrite('crg.vtk', 'structured_grid', X, Y, Z, 'vectors', 'vector_field', u, v, w);

Could you please help me resolve this! Thanks!

Thanks for your code, But I have thousands of lines to convert, those lines will collapse Paraview. Can you help me?

CY Y

CY Y (view profile)

Smyng

Smyng (view profile)

This may be a naive question but can you use vtkwrite to export my solution in cylindrical coordinates (i.e., r, theta, z) as a scalar field? Say my solution is psi and its scalar field is distributed throughout a concentric cylinder with r1 and r2. Please let me know and thanks in advance!

Joe Yeh

Joe Yeh (view profile)

@mohammad, I've just added support for this kind of dataset. Check out example usage 1.

Joe Yeh

Joe Yeh (view profile)

@Leonie, I had a similar situation. I exported data at each time points separately and gave them serial file names. I could then load them as a time series in Paraview. It worked quite well for me.

Hello,

thank you for this submission. I would like to export 4D data to Paraview (3D + time). My data represents velocities at each point in a volume which change through time. Is there a way I could use this function to export this type of data?

mohammad

Hi Joe and thanks for your submission
I have a question, I have voxel data which are for hippocampus(let's say a 3D voxel shape with .mat format). How can I convert it to vtk fromat but still I'll have a voxel data in vtk format?
thanks

h2so4

h2so4 (view profile)

Another simple way to specify the correct path to paraview.exe: replace (for example) line 176 with

!cd C:\Program Files\ParaView-5.0.1-Qt4-OpenGL2-Windows-64bit\bin & paraview.exe --data='C:\Users\CURRENTPATHWHEREINYOUREWORKING\matlab_export.vtk' &

The & symbol lets you perform multiple commands on only one line.
Great script, really useful!

cheng joylin

Joe Yeh, the problem is that the data saved in this binary VTK file is not represented as a surface. It shows up a volume with no rendering in Paraview. Ultimately, I specify a X and Y array and a Z array that has a constant value in it.

Joe Yeh

Joe Yeh (view profile)

To Ricardo and Venkatesh, scalars are stored in binary format(using fwrite function), so you can't use text editor the read the .vtk data and make sense of it. These files are meant to be read by ParaView.

I have the same problem as Ricardo Oliveira. Please advise solution.

The functions seems amazing but I can't really use it. I wanna plot a Temperature field and I have 4 arrays (size 81x1) with X,Y,Z,T values. I am trying to use the function as following:

vtkwrite('Parede.vtk','structured_grid',X,Y,Z,'scalars','Parede_plana',T)

But the output file is full of crazy characters such as: "=cŽ9=cŽ9 =cŽ9>*ª« =cŽ9>Ž8ä " where should be numbers. I can't understand what I am doing wrong. Could anyone help me with that? It is anything wrong with my X, Y,Z, T arrays?

Joe Yeh

Joe Yeh (view profile)

Hi Yous, I'm not familiar with this type of data you're talking about. See if you find any data type specified here that is similar to what you want, http://www.vtk.org/wp-content/uploads/2015/04/file-formats.pdf If there is, maybe I can implement it.

Joe Yeh

Joe Yeh (view profile)

Sorry Sebastiano, I have to change it back. Changing those two lines would result in erroneous display. Specifically I'm referring to the fprintf(fid,'3 %d %d %d\n',(varargin{5}-1)'); I have to change it back. But you'll see how the (0, 0, 0) is generated. It's because 1 is subtracted. This part of code is from another person's script, file id #22602

Joe Yeh

Joe Yeh (view profile)

Hi Seabastiano, thank you for pointing this out. I think I fixed that problem. It's coming from line 165 and line 169. Download the updated version and see if works fine now.

Sebastiano

Dear Joe,

many thanks for the files, they are really helpful for me.
I have just a problem writing vtk file. I would like to write two different files, one for the surface and one for the volume of a mesh, with something like that:
vtkwrite(name_surf,'polydata','triangle',x,y,z,faces_0); vtkwrite(name_vol,'polydata','tetrahedron',x,y,z,elem_0);
In both files two nodes are added at (0, 0, 0) right at the end of the nodes list. These nodes are not present in the inputs x, y, z. I really do not know why these two points are added. Do you have any suggestions?
Thank you!

Yous

Yous (view profile)

Hi Joe,

I was wondering how I can use this script for a quadrilateral 2D mesh and color every element according to a certain value (for CFD purposes)?

Thanks for the great work you did!!

Joe Yeh

Joe Yeh (view profile)

@ Michael, Thanks for the comment. The dimension assignment in line 81 is mostly for image data where the first dimension represents y axis and second dimension represents x axis. Of course, this may be different for your application.

Michael

Hi Joe,

I have got problems exporting structured grids with a non quadratic base area. In my opinion the dimensions declaration in line 81 were mixed up. I changed the x and y direction to solve the problem.

Michael,

PS: thanks for your work

cheng joylin

cheng joylin

cheng joylin

Max Yin

Hi, thanks for the hard work. This may come as stupid, but how do I export 2D scalar and vector fields into paraview?

Joe Yeh

Joe Yeh (view profile)

Hi Dimitry, isn't example 4 what you're looking for ? It's exporting triangular data.

Joe Yeh

Joe Yeh (view profile)

Hi Ted, ParaView does support RGBA lookup table but I haven't implemented it yet. I'll probably do it soon.

Joe Yeh

Joe Yeh (view profile)

Hi Rob, here's an example on how to export volume data to ParaView.

load mri
D = squeeze(D);
[x,y,z] = ndgrid(1:size(D,1),1:size(D,2),1:size(D,3));
vtkwrite('mri.vtk','structured_grid',x,y,z,'scalars','intensity',D);

And yes, ParaView does seem to be slow when rendering 3D volume. You'd probably want to try ImageJ 3D viewer for this purpose.

rob

rob (view profile)

Hi Joe,
First of all, Nice script!! I am trying to put my double matrix(medical image slices) into vtk and also some vector data. However when i load the double matrix in paraview it only works as point data. When i select volume in paraview it becomes extremely slow. What do i do to get volume data?

Best regards,

Rob

Ted

Ted (view profile)

Can this tool write scalar RGB and alpha datacubes to a vtk file?

Dmitry

Dmitry (view profile)

Thank you Joe, nice job! Is it possible to export a scalar field on triangular mesh with this function? Something like

vtkwrite('tri.vtk','polydata','triangle',x,y, zeros(size(x)),tri, 'unstructured_grid', x,y,z,'scalars','SCALAR_FIELD',field);

Or it is a different way to see a such field in ParaView?

Joe Yeh

Joe Yeh (view profile)

I'm sorry I don't really understand what 'cell-wise-constant' truly means. By discontinuous, do you mean there are grid points that contain no value? If so, you can probably use unstructured grid? I feel I might not be answering your questions correctly because I don't know the structure of your data. I can answer better if you could provide me with a set of your data (or example).

Niels Aage

Hi Joe, Thanks for you fast reply:-) I think might have been unclear in my question. Example 1 dumps nodal fields, and what I am looking for is a cell-wise-constant field (which could be stresses, densities, etc.) So generally something that is discontinuous between elements. Is this possible ?

Joe Yeh

Joe Yeh (view profile)

Hi Niels, I believe what you're hoping to do is listed in example 1 (see above) ? You can include multiple sets of scalar and vector data in the same grid points.

Niels Aage

This is great! Fast, simple and it just works. Are you planning to include cell-wise-constant datat (both vectors and scalars) as a possibility ?

Joe Yeh

Joe Yeh (view profile)

Jameson, you can use this for volume image, assuming you have only one intensity value at each grid point:

vtkwrite('volume.vtk', 'structured_grid',x,y,z, 'scalars','Intensity',int);

Jameson

Oops I missed the first call with 'r'.

Jameson

Can I use this to write a volume image?
Maybe used meshgrid to setup a structured grid for x,y,z, then set u=v=w to the intensity value? (or maybe just one and other two to 0)

Joe Yeh

Joe Yeh (view profile)

Hao, I just added support for unstructured grid. See if that works for you.

Thanks a lot for adding the option to export tetrahedron. It works as expected

Joe Yeh

Joe Yeh (view profile)

Hao, currently this script does not support unstructured grid data type. If you could provide me with a sample dataset, I should be able to add this function.

Hao

Hao (view profile)

This is wonderful!

Can this be used for unstructured grid 3D velocity data? I have vectors distributed at the random locations in a 3D volume.

Updates

2.3

Updated description

2.3

Edited tags

2.3

Added support for STRUCTURED_POINTS dataset, option to save in binary or ascii format. Added example.

2.2.1

Updated description.

2.2.1

linked to github repo

2.2.1

Revert to an earlier version.

2.2.1

Fix a small bug in previous version regarding triangular and tetrahedron datatypes.

1.14

corrected typo in description

1.13

Added support for unstructured datatype. 'Execute' feature now also works in Unix and Macs OS.

1.12

Updated file description.

1.11

Adding option to export tetrahedron (3D triangulation) data

1.10

Update title

1.9

Corrected in mistake in line 97 where sidx was originally vidx.

1.8

corrected a mistake made in previous update (argument parsing for 'structured_grid' datatype)

1.7

Added option to call ParaView and load data automatically

1.6

Added option for user-specified precision for 'polydata' datatype and improved documentation.

1.5

yet another mistake...If you find it not working with the examples, please download it again. thanks

1.4

correct a mistake in the file

1.3

Addition of POLYDATA options.

1.2

added comments in the file

1.1

corrected typos

MATLAB Release
MATLAB 9.0 (R2016a)

MATLAB Online Live Editor Challenge

Win cash prizes and have your live script featured on our website

Learn more

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video