Converts a VTK data array to a numpy array. Given a subclass of vtkDataArray, this function returns an appropriate numpy array containing the same data -- it actually points to the same data. Parameters vtk_array The VTK data array to be converted.
(vtk_array)
| 202 | return numpy_to_vtk(num_array, deep, vtkConstants.VTK_ID_TYPE) |
| 203 | |
| 204 | def vtk_to_numpy(vtk_array): |
| 205 | """Converts a VTK data array to a numpy array. |
| 206 | |
| 207 | Given a subclass of vtkDataArray, this function returns an |
| 208 | appropriate numpy array containing the same data -- it actually |
| 209 | points to the same data. |
| 210 | |
| 211 | Parameters |
| 212 | |
| 213 | vtk_array |
| 214 | The VTK data array to be converted. |
| 215 | |
| 216 | """ |
| 217 | typ = vtk_array.GetDataType() |
| 218 | assert typ in get_vtk_to_numpy_typemap().keys(), \ |
| 219 | "Unsupported array type %s"%typ |
| 220 | |
| 221 | shape = vtk_array.GetNumberOfTuples(), \ |
| 222 | vtk_array.GetNumberOfComponents() |
| 223 | |
| 224 | # Get the data via the buffer interface |
| 225 | dtype = get_numpy_array_type(typ) |
| 226 | try: |
| 227 | if typ != vtkConstants.VTK_BIT: |
| 228 | result = numpy.frombuffer(vtk_array, dtype=dtype) |
| 229 | else: |
| 230 | result = numpy.unpackbits(vtk_array, count=shape[0]) |
| 231 | except ValueError: |
| 232 | # http://mail.scipy.org/pipermail/numpy-tickets/2011-August/005859.html |
| 233 | # numpy 1.5.1 (and maybe earlier) has a bug where if frombuffer is |
| 234 | # called with an empty buffer, it throws ValueError exception. This |
| 235 | # handles that issue. |
| 236 | if shape[0] == 0: |
| 237 | # create an empty array with the given shape. |
| 238 | result = numpy.empty(shape, dtype=dtype) |
| 239 | else: |
| 240 | raise |
| 241 | if shape[1] == 1: |
| 242 | shape = (shape[0], ) |
| 243 | try: |
| 244 | result.shape = shape |
| 245 | except ValueError: |
| 246 | if shape[0] == 0: |
| 247 | # Refer to https://github.com/numpy/numpy/issues/2536 . |
| 248 | # For empty array, reshape fails. Create the empty array explicitly |
| 249 | # if that happens. |
| 250 | result = numpy.empty(shape, dtype=dtype) |
| 251 | else: raise |
| 252 | return result |