c++vtk

VTK: Extracting Cell Data from vtu unstructured grids in c++


I need to extract all the cell data from a .vtu (XML unstructured grid) for further manipulations in a c++ program. I am quite new to VTK...

      //read all the data from the file
      vtkSmartPointer<vtkXMLUnstructuredGridReader> reader =
      vtkSmartPointer<vtkXMLUnstructuredGridReader>::New();
      reader->SetFileName(filename.c_str());
      reader->Update();

      unsigned int cellNumber = reader->GetOutput()->GetNumberOfCells();
      cout << "There are " << cellNumber << " input cells." << endl;

This is correct - the cell number is displayed correctly. How do access now the names of the different CellArrays properties stored in the .vtu file and then their actual numeric values? Any help is appreciated! Cheers, Domanov


Solution

  • //read all the data from the file
      vtkSmartPointer<vtkXMLUnstructuredGridReader> reader =
      vtkSmartPointer<vtkXMLUnstructuredGridReader>::New();
      reader->SetFileName(filename.c_str());
      reader->Update();
    
      unsigned int cellNumber = reader->GetOutput()->GetNumberOfCells();
      cout << "There are " << cellNumber << " input cells." << endl;
    

    To access the cell data of unstructured grid, you can do as following:

    vtkUnstructuredGrid* ugrid = reader->GetOutput();
    vtkCellData *cellData = ugrid->GetCellData();
    for (int i = 0; i < cellData->GetNumberOfArrays(); i++)
    {
        vtkDataArray* data = cellData->GetArray(i);
        cout << "name " << data->GetName() << endl;
        for (int j = 0; j < data->GetNumberOfTuples(); j++)
        {
            double value = data->GetTuple1(j);
            cout << "  value " << j << "th is " << value << endl;
        }
    }