Vedo: Saving numpy meshgrid to vtk file

Created on 18 Dec 2019  路  5Comments  路  Source: marcomusy/vedo

I am looking through vtkplotter examples to find an example on how to write a numpy array as a structured grid to a VTK file. But unfortunately, I couldn't find it.

  • Is it possible to write a vtk file from a numpy array?
    Here is an example:
import numpy as np

X, Y = np.meshgrid(np.linspace(0, 2, 10), np.linspace(0, 1, 5))
x = X.ravel()
y = Y.ravel()
z = np.zeros_like(x)

# Is it possible to use vtkplotter to save these arrays (x,  y, z) as  a vtk file assuming a structured topology?

The expected result is a vtk file as shown here:

 vtkfile

All 5 comments

I managed to implement that in tvtk as follows (how can I achieve this in vtkplotter without using tvtk?):

from tvtk.api import tvtk, write_data
import numpy as np


x_ = np.linspace(0, 2, 10)
y_ = np.linspace(0, 1, 5)

X, Y = np.meshgrid(x_, y_)

x = X.ravel()
y = Y.ravel()
z = np.zeros_like(x)

print("x shape", x.shape)
points = np.stack((x, y, z), axis=1)


quads = []

imax= x_.size
jmax= y_.size

for j in range(y_.size-1):
    for i in range(x_.size-1):
        q = [i+1, i , (j+1)*imax+i, (j+1)*imax+i+1] # Note here that I am using CW ordering not CCW
        quads.append(q)

poly_edge = np.array(quads)


mesh = tvtk.PolyData(points=points, polys=poly_edge)


write_data(mesh, 'rect_mesh.vtk')

Thank you

Yes, you can do it easily:

from vtkplotter import Actor
import numpy as np

def CustomGrid(xarr, yarr):
    verts = []
    for y in yarr:
        for x in xarr:
            verts.append([x, y, 0])
    faces = []
    n = len(xarr)
    m = len(yarr)
    for j in range(m-1):
        for i in range(n-1):
            faces.append([i+j*n, i+j*n+1, i+1+(j+1)*n, i+(j+1)*n])
    return Actor([verts, faces])

x = np.linspace(0, 2, 10)
y = np.linspace(0, 1,  5)

grid = CustomGrid(x, y)
grid.c('gray').lineWidth(1).lc('db') #.shrink(0.9)
grid.write('rect_mesh.vtk', binary=False)
grid.show(axes=8, bg='w')

image

and:
vtkplotter rect_mesh.vtk

Obviously if the grid has regular spacing it's even simpler:

from vtkplotter import Grid

grid = Grid(sx=2, sy=1, resx=10, resy=5)
grid.write('rect_mesh.vtk')
grid.show(axes=8, bg='w')

image

I've integrated this functionality in shapes.Grid, so from the next release on you can do things like:

from vtkplotter import *

xcoords = arange(0, 2, 0.2)
ycoords = arange(0, 1,  0.2)
sqrtx = sqrt(xcoords)

grid = Grid(sx=sqrtx, sy=ycoords)
grid.show(axes=8, bg='w')

image

Thank you very much
:1st_place_medal: :1st_place_medal: :1st_place_medal:

Was this page helpful?
0 / 5 - 0 ratings

Related issues

FedeClaudi picture FedeClaudi  路  7Comments

DeepaMahm picture DeepaMahm  路  5Comments

m-albert picture m-albert  路  7Comments

vigji picture vigji  路  3Comments

drew-parsons picture drew-parsons  路  7Comments