<jupyter_start><jupyter_text>Conversion of Image Data from SimpleITK to Numpy and VTK   Imports<jupyter_code>import numpy
import vtk
import SimpleITK
from vtk.util.numpy_support import numpy_to_vtk
import matplotlib.pyplot as plt
%matplotlib inline<jupyter_output><empty_output><jupyter_text>---  Helper-functions<jupyter_code>def sitk_show(img, title=None, margin=0.05, dpi=40 ):
    nda = SimpleITK.GetArrayFromImage(img)
    spacing = img.GetSpacing()
    figsize = (1 + margin) * nda.shape[0] / dpi, (1 + margin) * nda.shape[1] / dpi
    extent = (0, nda.shape[1]*spacing[1], nda.shape[0]*spacing[0], 0)
    fig = plt.figure(figsize=figsize, dpi=dpi)
    ax = fig.add_axes([margin, margin, 1 - 2*margin, 1 - 2*margin])

    plt.set_cmap("gray")
    ax.imshow(nda,extent=extent,interpolation=None)
    
    if title:
        plt.title(title)
    
    plt.show()<jupyter_output><empty_output><jupyter_text>We're gonna use this function to embed a still image of a VTK render<jupyter_code>from IPython.display import Image
def vtk_show(renderer, width=400, height=300):
    """
    Takes vtkRenderer instance and returns an IPython Image with the rendering.
    """
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetOffScreenRendering(1)
    renderWindow.AddRenderer(renderer)
    renderWindow.SetSize(width, height)
    renderWindow.Render()
     
    windowToImageFilter = vtk.vtkWindowToImageFilter()
    windowToImageFilter.SetInput(renderWindow)
    windowToImageFilter.Update()
     
    writer = vtk.vtkPNGWriter()
    writer.SetWriteToMemory(1)
    writer.SetInputConnection(windowToImageFilter.GetOutputPort())
    writer.Write()
    data = str(buffer(writer.GetResult()))
    
    return Image(data)<jupyter_output><empty_output><jupyter_text>We're gonna use these functions to quickly 'convert' between SimpleITK and VTK data types<jupyter_code>dctITKtoVTK = {SimpleITK.sitkInt8: vtk.VTK_TYPE_INT8,
               SimpleITK.sitkInt16: vtk.VTK_TYPE_INT16,
               SimpleITK.sitkInt32: vtk.VTK_TYPE_INT32,
               SimpleITK.sitkInt64: vtk.VTK_TYPE_INT64,
               SimpleITK.sitkUInt8: vtk.VTK_TYPE_UINT8,
               SimpleITK.sitkUInt16: vtk.VTK_TYPE_UINT16,
               SimpleITK.sitkUInt32: vtk.VTK_TYPE_UINT32,
               SimpleITK.sitkUInt64: vtk.VTK_TYPE_UINT64,
               SimpleITK.sitkFloat32: vtk.VTK_TYPE_FLOAT32,
               SimpleITK.sitkFloat64: vtk.VTK_TYPE_FLOAT64}
dctVTKtoITK = dict(zip(dctITKtoVTK.values(), 
                       dctITKtoVTK.keys()))

def convertTypeITKtoVTK(typeITK):
    if typeITK in dctITKtoVTK:
        return dctITKtoVTK[typeITK]
    else:
        raise ValueError("Type not supported")

def convertTypeVTKtoITK(typeVTK):
    if typeVTK in dctVTKtoITK:
        return dctVTKtoITK[typeVTK]
    else:
        raise ValueError("Type not supported")<jupyter_output><empty_output><jupyter_text>---  Options<jupyter_code>filenameMyHead = "./MyHead.nii"<jupyter_output><empty_output><jupyter_text>Read in data with SimpleITK<jupyter_code>imgMyHead_SimpleITK = SimpleITK.ReadImage(filenameMyHead)
sitk_show(imgMyHead_SimpleITK[:,100,:])<jupyter_output><empty_output><jupyter_text>Convert `SimpleITK.Image` object to a `numpy.ndarray`<jupyter_code>imgMyHead_NumPy = numpy.ravel(SimpleITK.GetArrayFromImage(imgMyHead_SimpleITK), order='C')
info_vec = vtk.vtkInformationVector()
info_vec.SetNumberOfInformationObjects(1)
info_obj = info_vec.GetInformationObject(0)
print info_obj
vtk.vtkDataObject.SetPointDataActiveScalarInfo(info_obj,
                                              convertTypeITKtoVTK(imgMyHead_SimpleITK.GetPixelID()),
                                              imgMyHead_SimpleITK.GetNumberOfComponentsPerPixel())
print info_obj, info_vec<jupyter_output>vtkInformation (0x120b74610)
  Debug: Off
  Modified Time: 43
  Reference Count: 2
  Registered Events: (none)


vtkInformation (0x120b74610)
  Debug: Off
  Modified Time: 45
  Reference Count: 2
  Registered Events: (none)
  POINT_DATA_VECTOR: vtkInformationVector(0x1210cfb20)

 vtkInformationVector (0x12100f2a0)
  Debug: Off
  Modified Time: 41
  Reference Count: 1
  Registered Events: (none)
  Number of Information Objects: 1
  Information Objects:
    vtkInformation(0x120b74610):
      Debug: Off
      Modified Time: 45
      Reference Count: 2
      Registered Events: (none)
      POINT_DATA_VECTOR: vtkInformationVector(0x1210cfb20)<jupyter_text>Convert `numpy.ndarray` to a `vtk.vtkImageData` object<jupyter_code>imgMyHead_VTK = vtk.vtkImageData()
imgMyHead_VTK.SetSpacing(imgMyHead_SimpleITK.GetSpacing())
imgMyHead_VTK.SetOrigin(imgMyHead_SimpleITK.GetOrigin())
imgMyHead_VTK.SetDimensions(imgMyHead_SimpleITK.GetSize())
# imgMyHead_VTK.SetScalarType(convertTypeITKtoVTK(imgMyHead_SimpleITK.GetPixelID()), info_obj)
imgMyHead_VTK.AllocateScalars(convertTypeITKtoVTK(imgMyHead_SimpleITK.GetPixelID()),
                             imgMyHead_SimpleITK.GetNumberOfComponentsPerPixel())
# imgMyHead_VTK.SetNumberOfScalarComponents(imgMyHead_SimpleITK.GetNumberOfComponentsPerPixel())
imgMyHead_NumPyToVTK = numpy_to_vtk(imgMyHead_NumPy, 
                                    deep=True, 
                                    array_type=convertTypeITKtoVTK(imgMyHead_SimpleITK.GetPixelID()))

imgMyHead_VTK.GetPointData().SetScalars(imgMyHead_NumPyToVTK)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.0919776119402985, 'fraction_numerical': 0.024253731343283583, 'mean_word_length': 4.164739884393064, 'pattern_counts': {'":': 0, '<': 32, '<?xml version=': 0, '>': 32, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '8', 'dir': 'jupyter-structured-clean-dedup', 'id': '322158', 'license': 'MIT', 'n_tokens_mistral': 1982, 'n_tokens_neox': 1891, 'n_words': 288, 'path': '20150215_ConvertSimpleITKtoVTK/_Material/ConvertSimpleITKtoVTK.ipynb', 'repo_name': 'kmader/PyScienceBlog', 'size': '5360'}