Reading a VTR file with Python using vtkXMLRectilinearGridReader()

I am a new user of VTR files and have inherited some legacy code that intends to read in a VTR file with Python using the vtkXMLRectilinearGridReader(). I am having difficulties getting this to work and am hoping someone may have a suggestion for me. My overall goal is to be able to access the underlying data stored in the VTR file (i.e. see the quantity of data present as well as specific data values).

The first part of the code I am using is below:

#=======================================================================
from sys import argv
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection=‘3d’)
import sys
sys.path.append(’/usr/lib/python2.7/dist-packages’)
import vtk
#===========================================================
#set input variables
#===========================================================

infile= ‘filename.vtr’

outfile=infile.split(’/’)[-1]
outfile=outfile.split(’.’)[0]+‘mor.’+outfile.split(’.’)[1]

kerthreshold=250.
strucsize=10
connectval=50.
constructsize=10

#===========================================================
#loading data
#===========================================================
reader=vtk.vtkXMLRectilinearGridReader()
reader.SetFileName(infile)
reader.Update()

#===========================================================
#get information from vtk file
#===========================================================
datainfo=reader.GetOutput()
pointdata=datainfo.GetPointData()
extents=[]
extents=datainfo.GetExtent()
num=datainfo.GetNumberOfPoints()

oricube=[]

print (“Read datacube…”)
for pid in range(0,num):
value=pointdata.GetScalars().GetValue(pid)
oricube.append(value)
#=======================================================================

The code processes fine until it gets to the for loop at the end. At this point, I get an error stating AttributeError: ‘NoneType’ object has no attribute ‘GetValue’. Apparently, the reader.GetOutput().GetPointData().GetScalars() is not recognized as an actual object, and therefore the GetValue() method is not recognized as a method.

It’s possible that there is a better way to read in and access the VTR file data that the code I am currently working with, but for now I am limited to working with the code that I have. If anyone has any suggestions for me, please let me know! Thank you

You might benefit from using PyVista - PyVista simplifies routines like this so that you don’t have to worry about properly setting up the reader pipeline and PyVista will handle the creation of NumPy arrays from the VTR dataset for you.

Try this:

...

import pyvista as pv
# Read the file
datainfo = pv.read(infile)
extents = datainfo.extent
# Get the data array you fetch
oricube = datainfo.active_scalar

...
1 Like