Search code examples
vtkparaview

How to convert vtk legacy files to vtu format


I want to convert legacy .vtk files into binary files, preferably .vtu files, because I am using an Unstructured Grid. To do so I adapted the ConvertFile-Example from http://www.vtk.org/Wiki/VTK/Examples/Cxx/IO/ConvertFile

#include <string>
#include <vtkSmartPointer.h>
#include <vtkGenericDataObjectReader.h>
#include <vtkVersion.h>
#include <vtkXMLUnstructuredGridWriter.h>
#include <vtkUnstructuredGrid.h>
    
int main(int argc, char *argv[])
{
  if(argc < 3)
    {
    std::cerr << "Required arguments: input.vtk output.vtu" << std::endl;
    return EXIT_FAILURE;
    }

  std::string inputFileName = argv[1];
  std::string outputFileName = argv[2];

  vtkSmartPointer<vtkGenericDataObjectReader> reader = vtkSmartPointer<vtkGenericDataObjectReader>::New();
  reader->SetFileName(inputFileName.c_str());
  reader->Update();

  vtkSmartPointer<vtkXMLUnstructuredGridWriter> writer = vtkSmartPointer<vtkXMLUnstructuredGridWriter>::New();
  writer->SetFileName(outputFileName.c_str());
  writer->SetInputConnection(reader->GetOutputPort());
  writer->Update();

  return EXIT_SUCCESS;
}

But when I use this to convert my legacy file, I lose all Cell Data after the first set. In this minimal example of my legacy file Scal_1 is in the .vtu file but Scal_2 is not.

# vtk DataFile Version 3.1
Lattice Boltzmann data
ASCII
DATASET UNSTRUCTURED_GRID
POINTS 9 INT 
0 0 0 1 0 0 2 0 0 
0 1 0 1 1 0 2 1 0 
0 2 0 1 2 0 2 2 0 

CELLS 4 20
4 0 1 3 4 
4 1 2 4 5 
4 3 4 6 7 
4 4 5 7 8 

CELL_TYPES 4
8 8 8 8 

CELL_DATA 4
SCALARS Scal_1 DOUBLE
LOOKUP_TABLE default
1 2 1 0 

SCALARS Scal_2 DOUBLE
LOOKUP_TABLE default
1 3 2 1

I am still new to vtk. Should I use another reader or writer? Or is something completely wrong?


Solution

  • The issue here is that the reader you chose is getting confused by having the input file containing 2 cell data arrays both marked as scalars. So with this the reader only outputs one cell data array. My suggestion is to use ParaView, specifically the pvpython executable, to convert the files. The corresponding Python code would look something like:

    from paraview.simple import *
    r = LegacyVTKReader( FileNames=['input.vtk'] )
    w = XMLUnstructuredGridWriter()
    w.FileName = 'output.vtu'
    w.UpdatePipeline()