Converts a real numpy Array to a VTK array object. This function only works for real arrays. Complex arrays are NOT handled. It also works for multi-component arrays. However, only 1, and 2 dimensional arrays are supported. This function is very efficient, so large arrays should n
(num_array, deep=0, array_type=None)
| 102 | |
| 103 | |
| 104 | def numpy_to_vtk(num_array, deep=0, array_type=None): |
| 105 | """Converts a real numpy Array to a VTK array object. |
| 106 | |
| 107 | This function only works for real arrays. |
| 108 | Complex arrays are NOT handled. It also works for multi-component |
| 109 | arrays. However, only 1, and 2 dimensional arrays are supported. |
| 110 | This function is very efficient, so large arrays should not be a |
| 111 | problem. |
| 112 | |
| 113 | If the second argument is set to 1, the array is deep-copied from |
| 114 | from numpy. This is not as efficient as the default behavior |
| 115 | (shallow copy) and uses more memory but detaches the two arrays |
| 116 | such that the numpy array can be released. |
| 117 | |
| 118 | WARNING: You must maintain a reference to the passed numpy array, if |
| 119 | the numpy data is gc'd and VTK will point to garbage which will in |
| 120 | the best case give you a segfault. |
| 121 | |
| 122 | Parameters: |
| 123 | |
| 124 | num_array |
| 125 | a 1D or 2D, real numpy array. |
| 126 | |
| 127 | """ |
| 128 | |
| 129 | z = numpy.asarray(num_array) |
| 130 | if not z.flags.contiguous: |
| 131 | z = numpy.ascontiguousarray(z) |
| 132 | |
| 133 | shape = z.shape |
| 134 | assert z.flags.contiguous, 'Only contiguous arrays are supported.' |
| 135 | assert len(shape) < 3, \ |
| 136 | "Only arrays of dimensionality 2 or lower are allowed!" |
| 137 | assert not numpy.issubdtype(z.dtype, numpy.dtype(complex).type), \ |
| 138 | "Complex numpy arrays cannot be converted to vtk arrays."\ |
| 139 | "Use real() or imag() to get a component of the array before"\ |
| 140 | " passing it to vtk." |
| 141 | |
| 142 | # First create an array of the right type by using the typecode. |
| 143 | if array_type: |
| 144 | vtk_typecode = array_type |
| 145 | else: |
| 146 | vtk_typecode = get_vtk_array_type(z.dtype) |
| 147 | result_array = create_vtk_array(vtk_typecode) |
| 148 | |
| 149 | # Fixup shape in case its empty or scalar. |
| 150 | try: |
| 151 | testVar = shape[0] |
| 152 | except: |
| 153 | shape = (0,) |
| 154 | |
| 155 | # Find the shape and set number of components. |
| 156 | if len(shape) == 1: |
| 157 | result_array.SetNumberOfComponents(1) |
| 158 | else: |
| 159 | result_array.SetNumberOfComponents(shape[1]) |
| 160 | |
| 161 | # We don't need to call result_array.SetNumberOfTuples(shape[0]) |