Source code for paraview.python_view
r"""python_view is a module providing access to a PythonView. It is
possible to use the PythonView API directly, but this module provides
convenience classes in Python.
"""
#==============================================================================
#
# Program: ParaView
# Module: python_view.py
#
# Copyright (c) Kitware, Inc.
# All rights reserved.
# See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
#
# This software is distributed WITHOUT ANY WARRANTY without even
# the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
# PURPOSE. See the above copyright notice for more information.
#
#==============================================================================
import paraview
from vtkmodules.vtkCommonDataModel import vtkImageData
[docs]def numpy_to_image(numpy_array):
"""Convert a numpy 2D or 3D array to a vtkImageData object.
numpy_array
2D or 3D numpy array containing image data
return
vtkImageData with the numpy_array content
"""
try:
import numpy
except:
paraview.print_error("Error: Cannot import numpy")
shape = numpy_array.shape
if len(shape) < 2:
raise Exception('numpy array must have dimensionality of at least 2')
h, w = shape[0], shape[1]
c = 1
if len(shape) == 3:
c = shape[2]
# Reshape 2D image to 1D array suitable for conversion to a
# vtkArray with numpy_support.numpy_to_vtk()
linear_array = numpy.reshape(numpy_array, (w*h, c))
try:
from vtkmodules.util import numpy_support
except:
paraview.print_error("Error: Cannot import vtkmodules.util.numpy_support")
vtk_array = numpy_support.numpy_to_vtk(linear_array)
image = vtkImageData()
image.SetDimensions(w, h, 1)
image.AllocateScalars(vtk_array.GetDataType(), 4)
image.GetPointData().GetScalars().DeepCopy(vtk_array)
return image
[docs]def call_render(render_function, view, width, height):
"""Utility function to call the user-defined render function. This is called
by the C++ side of the vtkPythonView class.
view
vtkPythonView object
width
Width of view
height
Height of view
"""
if render_function == None:
return
# Check how many parameters it takes.
num_args = render_function.__code__.co_argcount
image = None
if (num_args == 3):
# Current-style render() function
image = render_function(view, width, height)
elif (num_args == 2):
# Old-style render() function introduced in ParaView 4.1
figure = matplotlib_figure(width, height)
render_function(view, figure)
image = figure_to_image(figure)
view.SetImageData(image)