[vtkusers] Faster way to create a vtkImageData with a single value

jmerkow jmerkow at gmail.com
Sun Jan 29 14:37:36 EST 2017


Hello,

I am working in creating volume images from PolyData using
vtkPolyDataToImageStencil and vtkImageStencil.
The process is outline here:[1] (for 2D images).
To do this, you need to fill a vtkImageData with a background (or
foreground) value.
Something like this:

    imgvtk = vtk.vtkImageData()
    imgvtk.SetSpacing(spacing)
    imgvtk.SetOrigin(origin)
    imgvtk.SetExtent(extent)
    imgvtk.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 1)
    
    # fill vtk image with background
    count = imgvtk.GetNumberOfPoints()
    for i in range(count):
        imgvtk.GetPointData().GetScalars().SetTuple1(i, backgroud_value);


However, this is very very slow, by far the slowest part of the process.  Is
there a faster way to do this?


Full code:
import vtk
from vtk.util import numpy_support

def pd_to_numpy_vol(pd, spacing=[1.,1.,1.], shape=None, origin=None
foreground_value=255, backgroud_value = 0):
    if shape is None:
        bnds = np.array(pd.GetBounds())
        shape = np.ceil((bnds[1::2]-bnds[::2])/spacing).astype(int)+15
    if origin is None:
        origin = bnds[::2]+(bnds[1::2]-bnds[::2])/2

    #make image
    extent = np.zeros(6).astype(int)
    extent[1::2] = np.array(shape)-1
    imgvtk = vtk.vtkImageData()
    imgvtk.SetSpacing(spacing)
    imgvtk.SetOrigin(origin)
    imgvtk.SetExtent(extent)
    imgvtk.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 1)
    
    # fill vtk image with background
    count = imgvtk.GetNumberOfPoints()
    for i in range(count):
        imgvtk.GetPointData().GetScalars().SetTuple1(i, backgroud_value);
    
    #poly2 stencil
    pol2stenc = vtk.vtkPolyDataToImageStencil()
    pol2stenc.SetInputData(pd)
    pol2stenc.SetOutputSpacing(spacing)
    pol2stenc.SetOutputOrigin(origin)
    pol2stenc.SetOutputWholeExtent(extent)
    pol2stenc.Update()
    
    #stencil to image
    imgstenc = vtk.vtkImageStencil()
    imgstenc.SetInputData(imgvtk)
    imgstenc.SetStencilConnection(pol2stenc.GetOutputPort())
    imgstenc.ReverseStencilOn()
    imgstenc.SetBackgroundValue(foreground_value)
    imgstenc.Update()
    
    ndseg =
numpy_support.vtk_to_numpy(imgstenc.GetOutputDataObject(0).GetPointData().GetArray(0))
    return ndseg.reshape(sitk.GetArrayFromImage(seg).shape)








--
View this message in context: http://vtk.1045678.n5.nabble.com/Faster-way-to-create-a-vtkImageData-with-a-single-value-tp5741978.html
Sent from the VTK - Users mailing list archive at Nabble.com.


More information about the vtkusers mailing list