Archive

Posts Tagged ‘VTK’

Fast Python VTK import

August 24, 2016 Leave a comment

he Python VTK module is long to import because it load all the native VTK libraries which most of the time you won’t need. With VTK already in memory (disk cache):

$ time python -c "import vtk"

real 0m2.951s
user 0m2.964s
sys 0m1.860s

Here is a way to make it fast:

import sys
import types

class FastVTKLoader(object):
def __init__(self, modules):
self.modules = modules

def imp(self):
if not sys.meta_path:
sys.meta_path.append(self)
else:
sys.meta_path[0] = self
import vtk
sys.meta_path.remove(self)
return vtk

def load_module(self, name):
return types.ModuleType(name)

def find_module(self, name, path=None):
if name.startswith("vtk.vtk") and not name.endswith("Python"):
vm = name[7:]
if vm not in self.modules:
return self

vtk = FastVTKLoader(["CommonCore", "CommonDataModel", "IOXML", "FiltersExtraction"]).imp()
$ time python myvtkloader.py

real 0m0.077s
user 0m0.076s
sys 0m0.000s

Inspired by this Stackoverflow answer.

Advertisements
Tags: ,

Array exchange between VTK and python

February 6, 2012 1 comment

Here is a sample program which demonstrate how to use python arrays with VTK. It can be used with almost no changes with numpy arrays. Similar code snippets for Java can be taken from jCAE, here. Using such array API is required to work with decent size mesh because it’s much faster than working at the VTK cell level.

#! /usr/bin/env python
from array import *
from vtk import *

def create_points(array):
    """Create vtkPoints from double array"""
    vtk_points = vtkPoints()
    double_array = vtkDoubleArray()
    double_array.SetVoidArray(array, len(array), 1)
    double_array.SetNumberOfComponents(3)
    vtk_points.SetData(double_array)
    return vtk_points

def create_cells(array):
    """Create a vtkCellArray from long array"""
    vtk_cells = vtkCellArray()
    vtk_id_array = vtkIdTypeArray()
    vtk_id_array.SetVoidArray(array, len(array), 1)
    vtk_cells.SetCells(len(array)/4, vtk_id_array)
    return vtk_cells

def vtk_to_array(vtk_array):
    at = vtk_array.GetDataType()
    if at == 11:
        #vtkDoubleArray
        pt='d'
    elif at == 12:
        #vtkIdTypeArray
        pt='l'
    #this is slow. numpy.zeros would be faster.
    r = array(pt, [0]*vtk_array.GetSize())
    vtk_array.ExportToVoidPointer(r)
    return r

#Create polydata
points = array('d', [0,0,0,1,0,0,1,1,0,1,1,1])
triangles = array('l', [3 ,0,1,2, 3, 0,1,3])
polydata = vtkPolyData()
polydata.SetPoints(create_points(points))
polydata.SetPolys(create_cells(triangles))

#Save it
writer = vtkXMLPolyDataWriter()
writer.SetFileName("zob.vtp")
writer.SetInput(polydata)
writer.Write()

#Read it
reader = vtkXMLPolyDataReader()
reader.SetFileName("zob.vtp")
reader.Update()
polydata = reader.GetOutput()

#Display arrays
print vtk_to_array(polydata.GetPoints().GetData())
print vtk_to_array(polydata.GetPolys().GetData())
Tags: ,