Example #1
0
def is_numpy_vtk_type(newscalars):
    # Indicate whether the type is known/supported by VTK to NumPy routines.
    try:
        np_s.get_vtk_array_type(newscalars.dtype)
    except TypeError:
        return False
    else:
        return True
Example #2
0
def is_numpy_vtk_type(newscalars):
    # Indicate whether the type is known/supported by VTK to NumPy routines.
    try:
        np_s.get_vtk_array_type(newscalars.dtype)
    except TypeError:
        return False
    else:
        return True
Example #3
0
 def _check_array_types(self, table, types=[int, float, float]):
     # Check data array types:
     typ = table.GetColumn(0).GetDataType()
     self.assertEqual(typ, nps.get_vtk_array_type(int))
     typ = table.GetColumn(1).GetDataType()
     self.assertEqual(typ, 13)
     typ = table.GetColumn(2).GetDataType()
     self.assertEqual(typ, nps.get_vtk_array_type(float))
     return
Example #4
0
def create_image(w, h, num_channels=1, dtype=np.uint8):
    """ Creates a VTK image. """
    image = vtk.vtkImageData()
    image.SetExtent(0, w - 1, 0, h - 1, 0, 0)
    image.SetSpacing(1., 1., 1.)
    image.SetOrigin(0., 0., 0.)
    if _is_vtk_5:
        image.SetWholeExtent(image.GetExtent())
        image.SetScalarType(get_vtk_array_type(dtype))
        image.SetNumberOfScalarComponents(num_channels)
        image.AllocateScalars()
    else:
        image.AllocateScalars(get_vtk_array_type(dtype), num_channels)
    return image
Example #5
0
def create_image(w, h, num_channels=1, dtype=np.uint8):
    """ Creates a VTK image. """
    image = vtk.vtkImageData()
    image.SetExtent(0, w - 1, 0, h - 1, 0, 0)
    image.SetSpacing(1., 1., 1.)
    image.SetOrigin(0., 0., 0.)
    if _is_vtk_5:
        image.SetWholeExtent(image.GetExtent())
        image.SetScalarType(get_vtk_array_type(dtype))
        image.SetNumberOfScalarComponents(num_channels)
        image.AllocateScalars()
    else:
        image.AllocateScalars(get_vtk_array_type(dtype), num_channels)
    return image
Example #6
0
def RegData_to_vtkImageData(grid, dtype=None):
  """Convert RegData to vtkImageData data."""
  require_isinstance(grid, gd.RegData)
  
  dat = grid.data
  if dtype is None: 
    dtype = dat.dtype 
  else:
    dtype   = np.dtype(dtype)
  #
  vtype   = numpy_support.get_vtk_array_type(dtype)
  
  flt     = dat.ravel(order='F')
  varray  = numpy_support.numpy_to_vtk(num_array=flt, 
                  deep=True, array_type=vtype)
                  
  shape   = grid.shape()
  x0      = grid.x0()
  dx      = grid.dx()

  imgdat  = vtk.vtkImageData()
  imgdat.GetPointData().SetScalars(varray)
  imgdat.SetDimensions(shape[0], shape[1], shape[2]) 
  imgdat.SetOrigin(x0[0],x0[1],x0[2])
  imgdat.SetSpacing(dx[0], dx[1], dx[2]) 
  return imgdat
Example #7
0
File: io.py Project: piro0321/AI
def numpy_to_vtk(numpy_data, spacing):
    """
    Parameters
    ----------
    image : 3d numpy array
    spacing : 解像度情報.(float, float, float)のタプル型.

    Returns
    -------
    numpy data : vtk data 
    """
    w, h, d = numpy_data.shape
    scalar_type = numpy_support.get_vtk_array_type(numpy_data.dtype)

    # データ順序がC形式でなければならないため,Fortran形式から変換.
    if numpy_data.flags.c_contiguous != True:
        numpy_data = np.ndarray.flatten(numpy_data, order='F')
        numpy_data = np.reshape(numpy_data, (w, h, d), order='C')

    vtk_data = vtk.vtkImageImport()
    vtk_data.SetDataScalarType(scalar_type)
    vtk_data.SetDataSpacing(spacing)
    vtk_data.SetDataOrigin(0, 0, 0)
    vtk_data.SetDataExtent(0, w - 1, 0, h - 1, 0, d - 1)
    vtk_data.SetWholeExtent(0, w - 1, 0, h - 1, 0, d - 1)
    vtk_data.SetNumberOfScalarComponents(1)
    vtk_data.CopyImportVoidPointer(numpy_data, numpy_data.nbytes)
    vtk_data.Update()

    return vtk_data
Example #8
0
def to_vtk(n_array, spacing):
    dz, dy, dx = n_array.shape
    n_array.shape = dx * dy * dz

    print n_array.shape

    v_image = numpy_support.numpy_to_vtk(n_array)

    # Generating the vtkImageData
    image = vtk.vtkImageData()
    image.SetDimensions(dx, dy, dz)
    image.SetOrigin(0, 0, 0)
    image.SetSpacing(spacing)
    #image.SetNumberOfScalarComponents(1)
    image.SetExtent(0, dx - 1, 0, dy - 1, 0, dz - 1)
    #image.SetScalarType(numpy_support.get_vtk_array_type(n_array.dtype))
    image.AllocateScalars(numpy_support.get_vtk_array_type(n_array.dtype), 1)
    image.GetPointData().SetScalars(v_image)
    #image.Update()

    image_copy = vtk.vtkImageData()
    image_copy.DeepCopy(image)
    #image_copy.Update()

    n_array.shape = dz, dy, dx
    return image_copy
Example #9
0
def to_vtk_mask(n_array, spacing=(1.0, 1.0, 1.0), origin=(0.0, 0.0, 0.0)):
    dz, dy, dx = n_array.shape
    ox, oy, oz = origin
    sx, sy, sz = spacing

    ox -= sx
    oy -= sy
    oz -= sz

    v_image = numpy_support.numpy_to_vtk(n_array.flat)
    extent = (0, dx - 1, 0, dy - 1, 0, dz - 1)

    # Generating the vtkImageData
    image = vtk.vtkImageData()
    image.SetOrigin(ox, oy, oz)
    image.SetSpacing(sx, sy, sz)
    image.SetDimensions(dx - 1, dy - 1, dz - 1)
    # SetNumberOfScalarComponents and SetScalrType were replaced by
    # AllocateScalars
    #  image.SetNumberOfScalarComponents(1)
    #  image.SetScalarType(numpy_support.get_vtk_array_type(n_array.dtype))
    image.AllocateScalars(numpy_support.get_vtk_array_type(n_array.dtype), 1)
    image.SetExtent(extent)
    image.GetPointData().SetScalars(v_image)

    #  image_copy = vtk.vtkImageData()
    #  image_copy.DeepCopy(image)

    return image
Example #10
0
def to_vtk(n_array, spacing, slice_number, orientation):
    try:
        dz, dy, dx = n_array.shape
    except ValueError:
        dy, dx = n_array.shape
        dz = 1

    v_image = numpy_support.numpy_to_vtk(n_array.flat)

    if orientation == 'AXIAL':
        extent = (0, dx -1, 0, dy -1, slice_number, slice_number + dz - 1)
    elif orientation == 'SAGITAL':
        dx, dy, dz = dz, dx, dy
        extent = (slice_number, slice_number + dx - 1, 0, dy - 1, 0, dz - 1)
    elif orientation == 'CORONAL':
        dx, dy, dz = dx, dz, dy
        extent = (0, dx - 1, slice_number, slice_number + dy - 1, 0, dz - 1)

    # Generating the vtkImageData
    image = vtk.vtkImageData()
    image.SetOrigin(0, 0, 0)
    image.SetSpacing(spacing)
    image.SetDimensions(dx, dy, dz)
    # SetNumberOfScalarComponents and SetScalrType were replaced by
    # AllocateScalars
    #  image.SetNumberOfScalarComponents(1)
    #  image.SetScalarType(numpy_support.get_vtk_array_type(n_array.dtype))
    image.AllocateScalars(numpy_support.get_vtk_array_type(n_array.dtype), 1)
    image.SetExtent(extent)
    image.GetPointData().SetScalars(v_image)

    image_copy = vtk.vtkImageData()
    image_copy.DeepCopy(image)

    return image_copy
Example #11
0
 def set_point_colors(self, **kwargs):
     if self.polydata is None:
         print("Points are not yet available")
     else:
         vtk_color_data = kwargs.get('data', None)
         if vtk_color_data is None:
             sample_labels = kwargs.get('labels', None)
             if sample_labels is None:
                 sample_labels = np.full(shape=[
                     self.polydata.GetPointData().GetNumberOfTuples()
                 ],
                                         fill_value=0)
             labels = np.where(sample_labels >= 0, sample_labels, 0)
             colors = self.colormap[labels]
             vtk_color_data: vtk.vtkUnsignedCharArray = npsup.numpy_to_vtk(
                 colors.ravel(),
                 deep=1,
                 array_type=npsup.get_vtk_array_type(np.uint8))
             vtk_color_data.SetNumberOfComponents(colors.shape[1])
             vtk_color_data.SetNumberOfTuples(colors.shape[0])
             vtk_color_data.SetName('colors')
         vtkpts = self.polydata.GetPointData()
         vtkpts.SetScalars(vtk_color_data)
         vtkpts.SetActiveScalars('colors')
         vtkpts.Modified()
Example #12
0
def numpy_to_vtk_cells(data, is_coords=True):
    """Convert numpy array to a vtk cell array.

    Parameters
    ----------
    data : ndarray
        points coordinate or connectivity array (e.g triangles).
    is_coords : ndarray
        Select the type of array. default: True.

    Returns
    -------
    vtk_cell : vtkCellArray
        connectivity + offset information

    """
    data = np.array(data)
    nb_cells = len(data)

    # Get lines_array in vtk input format
    connectivity = data.flatten() if not is_coords else []
    offset = [0, ]
    current_position = 0

    cell_array = vtk.vtkCellArray()

    if vtk.vtkVersion.GetVTKMajorVersion() >= 9:
        for i in range(nb_cells):
            current_len = len(data[i])
            offset.append(offset[-1] + current_len)

            if is_coords:
                end_position = current_position + current_len
                connectivity += list(range(current_position, end_position))
                current_position = end_position

        connectivity = np.array(connectivity, np.intp)
        offset = np.array(offset, dtype=connectivity.dtype)

        vtk_array_type = numpy_support.get_vtk_array_type(connectivity.dtype)
        cell_array.SetData(
            numpy_support.numpy_to_vtk(offset, deep=True,
                                       array_type=vtk_array_type),
            numpy_support.numpy_to_vtk(connectivity, deep=True,
                                       array_type=vtk_array_type))
    else:
        for i in range(nb_cells):
            current_len = len(data[i])
            end_position = current_position + current_len
            connectivity += [current_len]
            connectivity += list(range(current_position, end_position))
            current_position = end_position

        connectivity = np.array(connectivity)
        cell_array.GetData().DeepCopy(numpy_support.numpy_to_vtk(connectivity))

    cell_array.SetNumberOfCells(nb_cells)
    return cell_array
Example #13
0
def get_vtk_type(typ):
    """This looks up the VTK type for a give python data type.

    Return:
        int : the integer type id specified in vtkType.h
    """
    typ = nps.get_vtk_array_type(typ)
    if typ is 3:
        return 13
    return typ
Example #14
0
def exportPython2VTK(img):
    """
    This function creates a vtk image from a python array
    Args:
        img: python ndarray of the image
    Returns:
        imageData: vtk image
    """
    vtkArray = numpy_to_vtk(num_array=img.flatten('F'),
                            deep=True,
                            array_type=get_vtk_array_type(img.dtype))
    #vtkArray = numpy_to_vtk(img.flatten())
    return vtkArray
Example #15
0
def get_vtk_type(typ):
    """This looks up the VTK type for a give python data type. Corrects for
    string type mapping issues.

    Return
    ------
    int : the integer type id specified in vtkType.h
    """
    typ = nps.get_vtk_array_type(typ)
    # This handles a silly string type bug
    if typ is 3:
        return 13
    return typ
Example #16
0
def set_scalars(dataobject, newscalars):
    do = dsa.WrapDataObject(dataobject)
    oldscalars = do.PointData.GetScalars()
    name = oldscalars.GetName()
    del oldscalars

    # handle the case if the newscalars array has a type that
    # cannot be passed on to VTK. In which case, we convert to
    # convert to float64
    vtk_typecode = np_s.get_vtk_array_type(newscalars.dtype)
    if vtk_typecode is None:
        newscalars = newscalars.astype(np.float64)
    do.PointData.append(newscalars, name)
    do.PointData.SetActiveScalars(name)
Example #17
0
def set_scalars(dataobject, newscalars):
    do = dsa.WrapDataObject(dataobject)
    oldscalars = do.PointData.GetScalars()
    name = oldscalars.GetName()
    del oldscalars

    # handle the case if the newscalars array has a type that
    # cannot be passed on to VTK. In which case, we convert to
    # convert to float64
    vtk_typecode = np_s.get_vtk_array_type(newscalars.dtype)
    if vtk_typecode is None:
        newscalars = newscalars.astype(np.float64)
    do.PointData.append(newscalars, name)
    do.PointData.SetActiveScalars(name)
Example #18
0
def NumToVTKImage(numarray,name=None):
   dims = numarray.shape
   if len(dims) ==1:
      return NumToVTKArray(numarray, name)
   ii = vtk.vtkImageData()
   ii.SetDimensions(numarray.shape[0], numarray.shape[1], 1)
   ii.SetSpacing(1,1,1)
   ii.SetOrigin(0,0,0)
   ii.SetExtent(0, numarray.shape[0]-1, 0, numarray.shape[1]-1, 0, 0)
   vtktype = numpy_support.get_vtk_array_type(numarray.dtype)
   ii.AllocateScalars(vtktype, 1)
   pd = ii.GetPointData()
   arr = numpy_support.numpy_to_vtk(np.ndarray.flatten(numarray, 'F'))
   pd.SetScalars(arr)
   return ii
Example #19
0
    def md_to_vti(self, md):
        array = md.getSignalArray()
        origin = [md.getDimension(n).getMinimum() for n in range(3)]
        spacing = [md.getDimension(n).getBinWidth() for n in range(3)]
        dimensions = [n + 1 for n in array.shape]

        vtkArray = numpy_to_vtk(num_array=array.flatten('F'),
                                deep=True,
                                array_type=get_vtk_array_type(array.dtype))

        imageData = vtk.vtkImageData()
        imageData.SetOrigin(origin)
        imageData.SetSpacing(spacing)
        imageData.SetDimensions(dimensions)
        imageData.GetCellData().SetScalars(vtkArray)

        return imageData
Example #20
0
def numpyToImageData(img, flip=True, vtktype=None):
    if flip:
        img = np.flipud(img)
    assert len(img.shape) in (2, 3)
    height, width = img.shape[:2]
    numChannels = 1 if len(img.shape) == 2 else img.shape[2]
    image = vtk.vtkImageData()
    image.SetDimensions(width, height, 1)
    if vtktype is None:
        vtktype = numpy_support.get_vtk_array_type(img.dtype)
    image.AllocateScalars(vtktype, numChannels)
    scalars = getNumpyFromVtk(image, 'ImageScalars')
    if numChannels > 1:
        scalars[:] = img.reshape(width*height, numChannels)[:]
    else:
        scalars[:] = img.reshape(width*height)[:]
    return image
Example #21
0
    def __init__(self, array, type_array=None):
        '''

        :param array: Receives a pandas DataFrame, or numpy array or vtkDataArray
        :param type_array: Receives the vtk data type or a numpy array type
        '''
        self._vtk = None
        array = self._convert_list_pandas_to_numpy(array)

        vtk_type = None
        np_type = None
        if isinstance(type_array, int):
            vtk_type = type_array
            np_type = ns.get_vtk_to_numpy_typemap()[type_array]
        elif isinstance(type_array, type):
            vtk_type = ns.get_vtk_array_type(type_array)
            np_type = type_array

        if isinstance(array, np.ndarray):
            if not array.flags.contiguous:
                array = np.ascontiguousarray(array)
            if np_type:
                array = array.astype(np_type)
            self._numpy = array
            self._vtk = ns.numpy_to_vtk(self._numpy, array_type=vtk_type)
            self._vtk._np = array
        elif isinstance(array, vtk.vtkDataArray):
            if type_array is None or array.GetDataType() == vtk_type:
                self._vtk = array
                self._numpy = ns.vtk_to_numpy(array)
            else:
                if type_array is None:
                    np_type = np.double
                    vtk_type = vtk.VTK_DOUBLE
                np_array = ns.vtk_to_numpy(array).astype(np_type)
                self._vtk = ns.create_vtk_array(vtk_type)
                self._vtk.SetName(array.GetName())
                self.numpy_to_vtk(np_array)
        else:
            raise ValueError(
                'Expected a Numpy array, but received a: {}'.format(
                    type(array)))
        self._vtk.AddObserver(vtk.vtkCommand.ModifiedEvent, self._update_numpy)
Example #22
0
def to_vtk(n_array, dim, spacing=(1,1,1)):
    dz, dy, dx = dim
    data_type = n_array.dtype

    v_image = numpy_support.numpy_to_vtk(n_array)

    # Generating the vtkImageData
    image = vtk.vtkImageData()
    image.SetDimensions(dx, dy, dz)
    image.SetOrigin(0, 0, 0)
    image.SetSpacing(spacing)
    image.SetNumberOfScalarComponents(1)
    image.SetExtent(0, dx -1, 0, dy -1, 0, dz - 1)
    # getattr(image, NUMPY_TO_VTK_TYPE[n_array.dtype.name])()
    image.SetScalarType(numpy_support.get_vtk_array_type(n_array.dtype))
    image.AllocateScalars()
    image.GetPointData().SetScalars(v_image)

    return image
Example #23
0
def to_vtk(n_array, spacing, slice_number=0, orientation='AXIAL'):

    """
    This function defines orientation or the TPMS.
    Starts vtk.
    """


    try:
        dz, dy, dx = n_array.shape
    except ValueError:
        dy, dx = n_array.shape
        dz = 1

    v_image = numpy_support.numpy_to_vtk(n_array.flat)

    if orientation == 'AXIAL':
        extent = (0, dx -1, 0, dy -1, slice_number, slice_number + dz - 1)
    elif orientation == 'SAGITAL':
        dx, dy, dz = dz, dx, dy
        extent = (slice_number, slice_number + dx - 1, 0, dy - 1, 0, dz - 1)
    elif orientation == 'CORONAL':
        dx, dy, dz = dx, dz, dy
        extent = (0, dx - 1, slice_number, slice_number + dy - 1, 0, dz - 1)

    # Generating the vtkImageData
    image = vtk.vtkImageData()
    image.SetOrigin(0, 0, 0)
    image.SetSpacing(spacing)
    #  image.SetNumberOfScalarComponents(1)
    image.SetDimensions(dx, dy, dz)
    image.SetExtent(extent)
    #  image.SetScalarType(numpy_support.get_vtk_array_type(n_array.dtype))
    image.AllocateScalars(numpy_support.get_vtk_array_type(n_array.dtype), 1)
    image.GetPointData().SetScalars(v_image)
    #  image.Update()
    #  image.UpdateInformation()

    #  image_copy = vtk.vtkImageData()
    #  image_copy.DeepCopy(image)
    #  image_copy.Update()

    return image
Example #24
0
File: app.py Project: jcdinis/POMES
def to_vtk(n_array, spacing):
   dz, dy, dx = n_array.shape
   n_array.shape = dx * dy * dz

   v_image = numpy_support.numpy_to_vtk(n_array)

   # Generating the vtkImageData
   image = vtk.vtkImageData()
   image.SetOrigin(0, 0, 0)
   image.SetDimensions(dx, dy, dz)
   image.SetSpacing(spacing)
   image.SetExtent(0, dx -1, 0, dy -1, 0, dz - 1)
   image.AllocateScalars(numpy_support.get_vtk_array_type(n_array.dtype), 1)
   image.GetPointData().SetScalars(v_image)

   image_copy = vtk.vtkImageData()
   image_copy.DeepCopy(image)

   n_array.shape = dz, dy, dx 
   return image_copy
Example #25
0
def np_rgba_to_vtk(n_array, spacing=(1.0, 1.0, 1.0)):
    dy, dx, dc = n_array.shape
    v_image = numpy_support.numpy_to_vtk(n_array.reshape(dy * dx, dc))

    extent = (0, dx - 1, 0, dy - 1, 0, 0)

    # Generating the vtkImageData
    image = vtk.vtkImageData()
    image.SetOrigin(0, 0, 0)
    image.SetSpacing(spacing)
    image.SetDimensions(dx, dy, 1)
    # SetNumberOfScalarComponents and SetScalrType were replaced by
    # AllocateScalars
    #  image.SetNumberOfScalarComponents(1)
    #  image.SetScalarType(numpy_support.get_vtk_array_type(n_array.dtype))
    image.AllocateScalars(numpy_support.get_vtk_array_type(n_array.dtype), dc)
    image.SetExtent(extent)
    image.GetPointData().SetScalars(v_image)

    return image
Example #26
0
def np_rgba_to_vtk(n_array, spacing=(1.0, 1.0, 1.0)):
    dy, dx, dc = n_array.shape
    v_image = numpy_support.numpy_to_vtk(n_array.reshape(dy*dx, dc))

    extent = (0, dx -1, 0, dy -1, 0, 0)

    # Generating the vtkImageData
    image = vtk.vtkImageData()
    image.SetOrigin(0, 0, 0)
    image.SetSpacing(spacing)
    image.SetDimensions(dx, dy, 1)
    # SetNumberOfScalarComponents and SetScalrType were replaced by
    # AllocateScalars
    #  image.SetNumberOfScalarComponents(1)
    #  image.SetScalarType(numpy_support.get_vtk_array_type(n_array.dtype))
    image.AllocateScalars(numpy_support.get_vtk_array_type(n_array.dtype), dc)
    image.SetExtent(extent)
    image.GetPointData().SetScalars(v_image)

    return image
Example #27
0
def to_vtk(n_array, spacing, slice_number, orientation):
    """
    It transforms a numpy array into a vtkImageData.
    """
    # TODO Merge this function with imagedata_utils.to_vtk to eliminate
    # duplicated code
    try:
        dz, dy, dx = n_array.shape
    except ValueError:
        dy, dx = n_array.shape
        dz = 1

    v_image = numpy_support.numpy_to_vtk(n_array.flat)

    if orientation == 'AXIAL':
        extent = (0, dx -1, 0, dy -1, slice_number, slice_number + dz - 1)
    elif orientation == 'SAGITAL':
        extent = (slice_number, slice_number + dx - 1, 0, dy - 1, 0, dz - 1)
    elif orientation == 'CORONAL':
        extent = (0, dx - 1, slice_number, slice_number + dy - 1, 0, dz - 1)

    image = vtk.vtkImageData()
    image.SetOrigin(0, 0, 0)
    image.SetSpacing(spacing)
    image.SetNumberOfScalarComponents(1)
    image.SetDimensions(dx, dy, dz)
    image.SetExtent(extent)
    image.SetScalarType(numpy_support.get_vtk_array_type(n_array.dtype))
    image.AllocateScalars()
    image.Update()
    image.GetCellData().SetScalars(v_image)
    image.GetPointData().SetScalars(v_image)
    image.Update()

    image_copy = vtk.vtkImageData()
    image_copy.DeepCopy(image)
    image_copy.Update()

    return image_copy
Example #28
0
def to_vtk(n_array, spacing, slice_number, orientation):
    """
    It transforms a numpy array into a vtkImageData.
    """
    # TODO Merge this function with imagedata_utils.to_vtk to eliminate
    # duplicated code
    try:
        dz, dy, dx = n_array.shape
    except ValueError:
        dy, dx = n_array.shape
        dz = 1

    v_image = numpy_support.numpy_to_vtk(n_array.flat)

    if orientation == 'AXIAL':
        extent = (0, dx - 1, 0, dy - 1, slice_number, slice_number + dz - 1)
    elif orientation == 'SAGITAL':
        extent = (slice_number, slice_number + dx - 1, 0, dy - 1, 0, dz - 1)
    elif orientation == 'CORONAL':
        extent = (0, dx - 1, slice_number, slice_number + dy - 1, 0, dz - 1)

    image = vtk.vtkImageData()
    image.SetOrigin(0, 0, 0)
    image.SetSpacing(spacing)
    image.SetNumberOfScalarComponents(1)
    image.SetDimensions(dx, dy, dz)
    image.SetExtent(extent)
    image.SetScalarType(numpy_support.get_vtk_array_type(n_array.dtype))
    image.AllocateScalars()
    image.Update()
    image.GetCellData().SetScalars(v_image)
    image.GetPointData().SetScalars(v_image)
    image.Update()

    image_copy = vtk.vtkImageData()
    image_copy.DeepCopy(image)
    image_copy.Update()

    return image_copy
Example #29
0
    def write_vti(self,
                  array,
                  spacing,
                  filename='Polydata.vti',
                  origin=(0, 0, 0)):
        vtkArray = numpy_to_vtk(num_array=array.flatten('F'),
                                deep=True,
                                array_type=get_vtk_array_type(array.dtype))

        imageData = vtk.vtkImageData()
        imageData.SetOrigin(origin)
        imageData.SetSpacing(spacing)
        imageData.SetDimensions(array.shape)
        imageData.GetPointData().SetScalars(vtkArray)

        writer = vtk.vtkXMLImageDataWriter()
        if os.sep == '\\':
            writer.SetFileName(".\\__vtk_files__\\{}".format(filename))
        else:
            writer.SetFileName("__vtk_files__/{}".format(filename))
        writer.SetInputData(imageData)
        writer.Write()
        self.vti_write = True
Example #30
0
def numpy_to_vtk(num_array, deep=0, array_type=None):
    """Converts a contiguous real numpy Array to a VTK array object.

    This function only works for real arrays that are contiguous.
    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 not be a
    problem.

    If the second argument is set to 1, the array is deep-copied from
    from numpy. This is not as efficient as the default behavior
    (shallow copy) and uses more memory but detaches the two arrays
    such that the numpy array can be released.

    WARNING: You must maintain a reference to the passed numpy array, if
    the numpy data is gc'd and VTK will point to garbage which will in
    the best case give you a segfault.

    Parameters
    ----------
    - num_array :  a contiguous 1D or 2D, real numpy array.

    Notes
    -----
    This was pulled from VTK and modified to eliminate numpy 1.14 warnings.
    VTK uses a BSD license, so it's OK to do  that.
    """
    z = np.asarray(num_array)
    if not z.flags.contiguous:
        z = np.ascontiguousarray(z)

    shape = z.shape
    assert z.flags.contiguous, 'Only contiguous arrays are supported.'
    assert len(shape) < 3, \
           "Only arrays of dimensionality 2 or lower are allowed!"
    assert not np.issubdtype(z.dtype, np.complexfloating), \
           "Complex numpy arrays cannot be converted to vtk arrays."\
           "Use real() or imag() to get a component of the array before"\
           " passing it to vtk."

    # First create an array of the right type by using the typecode.
    if array_type:
        vtk_typecode = array_type
    else:
        vtk_typecode = get_vtk_array_type(z.dtype)
    result_array = create_vtk_array(vtk_typecode)

    # Fixup shape in case its empty or scalar.
    try:
        test_var = shape[0]
    except:
        shape = (0, )

    # Find the shape and set number of components.
    if len(shape) == 1:
        result_array.SetNumberOfComponents(1)
    else:
        result_array.SetNumberOfComponents(shape[1])

    result_array.SetNumberOfTuples(shape[0])

    # Ravel the array appropriately.
    arr_dtype = get_numpy_array_type(vtk_typecode)
    if np.issubdtype(z.dtype, arr_dtype) or \
       z.dtype == np.dtype(arr_dtype):
        z_flat = np.ravel(z)
    else:
        z_flat = np.ravel(z).astype(arr_dtype)
        # z_flat is now a standalone object with no references from the caller.
        # As such, it will drop out of this scope and cause memory issues if we
        # do not deep copy its data.
        deep = 1

    # Point the VTK array to the numpy data.  The last argument (1)
    # tells the array not to deallocate.
    result_array.SetVoidArray(z_flat, len(z_flat), 1)
    if deep:
        copy = result_array.NewInstance()
        copy.DeepCopy(result_array)
        result_array = copy
    else:
        result_array._numpy_reference = z
    return result_array
Example #31
0
def load_image(filename, as_vtktype=False, use_pillow=True):
    """Load an image.

    Parameters
    ----------
    filename: str
        should be png, bmp, jpeg or jpg files
    as_vtktype: bool, optional
        if True, return vtk output otherwise an ndarray. Default False.
    use_pillow: bool, optional
        Use pillow python library to load the files. Default True

    Returns
    -------
    image: ndarray or vtk output
        desired image array

    """
    if use_pillow:
        with Image.open(filename) as pil_image:
            if pil_image.mode in ['RGBA', 'RGB', 'L']:
                image = np.asarray(pil_image)
            elif pil_image.mode.startswith('I;16'):
                raw = pil_image.tobytes('raw', pil_image.mode)
                dtype = '>u2' if pil_image.mode.endswith('B') else '<u2'
                image = np.frombuffer(raw, dtype=dtype)
                image.reshape(pil_image.size[::-1]).astype('=u2')
            else:
                try:
                    image = pil_image.convert('RGBA')
                except ValueError:
                    raise RuntimeError('Unknown image mode {}'.format(
                        pil_image.mode))
                image = np.asarray(pil_image)

        if as_vtktype:
            if image.ndim not in [2, 3]:
                raise IOError("only 2D (L, RGB, RGBA) or 3D image available")

            vtk_image = vtk.vtkImageData()
            depth = 1 if image.ndim == 2 else image.shape[2]

            # width, height
            vtk_image.SetDimensions(image.shape[1], image.shape[0], depth)
            vtk_image.SetExtent(0, image.shape[1] - 1, 0, image.shape[0] - 1,
                                0, 0)
            vtk_image.SetSpacing(1.0, 1.0, 1.0)
            vtk_image.SetOrigin(0.0, 0.0, 0.0)
            arr_tmp = np.flipud(image)
            arr_tmp = arr_tmp.reshape(image.shape[1] * image.shape[0], depth)
            arr_tmp = np.ascontiguousarray(arr_tmp, dtype=image.dtype)
            vtk_array_type = numpy_support.get_vtk_array_type(image.dtype)
            uchar_array = numpy_support.numpy_to_vtk(arr_tmp,
                                                     deep=True,
                                                     array_type=vtk_array_type)
            vtk_image.GetPointData().SetScalars(uchar_array)
            image = vtk_image

        return image

    d_reader = {
        ".png": vtk.vtkPNGReader,
        ".bmp": vtk.vtkBMPReader,
        ".jpeg": vtk.vtkJPEGReader,
        ".jpg": vtk.vtkJPEGReader,
        ".tiff": vtk.vtkTIFFReader,
        ".tif": vtk.vtkTIFFReader
    }

    extension = os.path.splitext(os.path.basename(filename).lower())[1]

    if extension.lower() not in d_reader.keys():
        raise IOError(
            "Impossible to read the file {0}: Unknown extension {1}".format(
                filename, extension))

    reader = d_reader.get(extension)()
    reader.SetFileName(filename)
    reader.Update()
    reader.GetOutput().GetPointData().GetArray(0).SetName("original")

    if not as_vtktype:
        w, h, _ = reader.GetOutput().GetDimensions()
        vtk_array = reader.GetOutput().GetPointData().GetScalars()

        components = vtk_array.GetNumberOfComponents()
        image = numpy_support.vtk_to_numpy(vtk_array).reshape(h, w, components)
        image = np.flipud(image)

    return reader.GetOutput() if as_vtktype else image
Example #32
0
    def addGrid(self, grid):
        nx, ny, nz = grid.shape[1:]

        self.display.append(True)

        self.grids.append(vtk.vtkStructuredGrid())

        self.grids[-1].SetExtent(0, nz-1, 0, ny-1, 0, nx-1)
        p = vtk.vtkPoints()

        shp = grid.shape
        grid.shape = (3, nx*ny*nz)
        p.SetData(vtknp.numpy_to_vtk(np.ascontiguousarray(grid.T), deep=True, array_type=vtknp.get_vtk_array_type(grid.dtype)))
        grid.shape = shp
        self.grids[-1].SetPoints(p)

        #Couleur
        color = np.random.rand(3)
        #Create a vtkOutlineFilter to draw the bounding box of the data set.
        ol = vtk.vtkOutlineFilter()
        if (vtk.vtkVersion().GetVTKMajorVersion()>=6):
          ol.SetInputData(self.grids[-1])
        else:
          ol.SetInput(self.grids[-1])      
        olm = vtk.vtkPolyDataMapper()
        olm.SetInputConnection(ol.GetOutputPort())
        ola = vtk.vtkActor()
        ola.SetMapper(olm)
        ola.GetProperty().SetColor(color)

        s=vtk.vtkShrinkFilter()
        if (vtk.vtkVersion().GetVTKMajorVersion()>=6):
          s.SetInputData(self.grids[-1])
        else:
          s.SetInput(self.grids[-1])      
        s.SetShrinkFactor(0.8)
        #
        mapper = vtk.vtkDataSetMapper()
        #map.SetInputData(data)
        mapper.SetInputConnection(s.GetOutputPort())
        act = vtk.vtkLODActor()
        act.SetMapper(mapper)
        #act.GetProperty().SetRepresentationToWireframe()
        #act.GetProperty().SetRepresentationToPoints()	
        act.GetProperty().SetColor(color)
        act.GetProperty().SetEdgeColor(color)
        act.GetProperty().EdgeVisibilityOff()	
        self.actors.append(act)
        self.setBounds()
        self.ren.SetActiveCamera(self.cam)
Example #33
0
File: io.py Project: bosecodes/fury
def save_image(arr,
               filename,
               compression_quality=75,
               compression_type='deflation',
               use_pillow=True):
    """Save a 2d or 3d image.

    Parameters
    ----------
    arr : ndarray
        array to save
    filename : string
        should be png, bmp, jpeg or jpg files
    compression_quality : int
        compression_quality for jpeg data.
        0 = Low quality, 100 = High quality
    compression_type : str
        compression type for tiff file
        select between: None, lzw, deflation (default)
    use_pillow : bool
        Use imageio python library to save the files.
    """
    if arr.ndim > 3:
        raise IOError("Image Dimensions should be <=3")

    d_writer = {
        ".png": vtk.vtkPNGWriter,
        ".bmp": vtk.vtkBMPWriter,
        ".jpeg": vtk.vtkJPEGWriter,
        ".jpg": vtk.vtkJPEGWriter,
        ".tiff": vtk.vtkTIFFWriter,
        ".tif": vtk.vtkTIFFWriter,
    }

    extension = os.path.splitext(os.path.basename(filename).lower())[1]

    if extension.lower() not in d_writer.keys():
        raise IOError(
            "Impossible to save the file {0}: Unknown extension {1}".format(
                filename, extension))

    if use_pillow:
        im = Image.fromarray(arr)
        im.save(filename, quality=compression_quality)
        return

    if arr.ndim == 2:
        arr = arr[..., None]

    vtk_array_type = numpy_support.get_vtk_array_type(arr.dtype)
    vtk_array = numpy_support.numpy_to_vtk(num_array=arr.ravel(),
                                           deep=True,
                                           array_type=vtk_array_type)

    # Todo, look the following link for managing png 16bit
    # https://stackoverflow.com/questions/15667947/vtkpngwriter-printing-out-black-images
    vtk_data = vtk.vtkImageData()
    vtk_data.SetDimensions(arr.shape)
    vtk_data.SetSpacing(1.0, 1.0, 1.0)
    vtk_data.SetOrigin(0.0, 0.0, 0.0)
    vtk_data.GetPointData().SetScalars(vtk_array)

    writer = d_writer.get(extension)()
    writer.SetFileName(filename)
    writer.SetInputData(vtk_data)
    if extension.lower() in [".jpg", ".jpeg"]:
        writer.ProgressiveOn()
        writer.SetQuality(compression_quality)
    if extension.lower() in [".tif", ".tiff"]:
        if not compression_type:
            writer.SetCompressionToNoCompression()
        elif compression_type.lower() == 'lzw':
            writer.SetCompressionToLZW()
        elif compression_type.lower() == 'deflation':
            writer.SetCompressionToDeflate()

    writer.Write()
Example #34
0
def to_vtk(
        n_array,
        spacing=(1.0, 1.0, 1.0),
        slice_number=0,
        orientation="AXIAL",
        origin=(0, 0, 0),
        padding=(0, 0, 0),
):
    if orientation == "SAGITTAL":
        orientation = "SAGITAL"

    try:
        dz, dy, dx = n_array.shape
    except ValueError:
        dy, dx = n_array.shape
        dz = 1

    px, py, pz = padding

    v_image = numpy_support.numpy_to_vtk(n_array.flat)

    if orientation == "AXIAL":
        extent = (
            0 - px,
            dx - 1 - px,
            0 - py,
            dy - 1 - py,
            slice_number - pz,
            slice_number + dz - 1 - pz,
        )
    elif orientation == "SAGITAL":
        dx, dy, dz = dz, dx, dy
        extent = (
            slice_number - px,
            slice_number + dx - 1 - px,
            0 - py,
            dy - 1 - py,
            0 - pz,
            dz - 1 - pz,
        )
    elif orientation == "CORONAL":
        dx, dy, dz = dx, dz, dy
        extent = (
            0 - px,
            dx - 1 - px,
            slice_number - py,
            slice_number + dy - 1 - py,
            0 - pz,
            dz - 1 - pz,
        )

    # Generating the vtkImageData
    image = vtk.vtkImageData()
    image.SetOrigin(origin)
    image.SetSpacing(spacing)
    image.SetDimensions(dx, dy, dz)
    # SetNumberOfScalarComponents and SetScalrType were replaced by
    # AllocateScalars
    #  image.SetNumberOfScalarComponents(1)
    #  image.SetScalarType(numpy_support.get_vtk_array_type(n_array.dtype))
    image.AllocateScalars(numpy_support.get_vtk_array_type(n_array.dtype), 1)
    image.SetExtent(extent)
    image.GetPointData().SetScalars(v_image)

    image_copy = vtk.vtkImageData()
    image_copy.DeepCopy(image)

    return image_copy
Example #35
0
def _points_to_vtk_cells(points, points_per_line=2):
    """
    Returns the VTK cell array for the peaks given the set of points
    coordinates.

    Parameters
    ----------
    points : (N, 3) array or ndarray
        points coordinates array.
    points_per_line : int (1 or 2), optional
        number of points per peak direction.

    Returns
    -------
    cell_array : vtkCellArray
        connectivity + offset information.

    """
    num_pnts = len(points)
    num_cells = num_pnts // points_per_line

    cell_array = vtk.vtkCellArray()

    if vtk.vtkVersion.GetVTKMajorVersion() >= 9:
        """
        Connectivity is an array that contains the indices of the points that
        need to be connected in the visualization. The indices start from 0.
        """
        connectivity = np.asarray(list(range(0, num_pnts)), dtype=int)
        """
        Offset is an array that contains the indices of the first point of
        each line. The indices start from 0 and given the known geometry of
        this actor the creation of this array requires a 2 points padding
        between indices.
        """
        offset = np.asarray(list(range(0, num_pnts + 1, points_per_line)),
                            dtype=int)

        vtk_array_type = numpy_support.get_vtk_array_type(connectivity.dtype)
        cell_array.SetData(
            numpy_support.numpy_to_vtk(offset,
                                       deep=True,
                                       array_type=vtk_array_type),
            numpy_support.numpy_to_vtk(connectivity,
                                       deep=True,
                                       array_type=vtk_array_type))
    else:
        connectivity = np.array([], dtype=int)
        i_pos = 0
        while i_pos < num_pnts:
            e_pos = i_pos + points_per_line
            """
            In old versions of VTK (<9.0) the connectivity array should include
            the length of each line and immediately after the indices of the
            points in each line.
            """
            connectivity = np.append(connectivity,
                                     [points_per_line, i_pos, e_pos - 1])
            i_pos = e_pos

        cell_array.GetData().DeepCopy(numpy_support.numpy_to_vtk(connectivity))

    cell_array.SetNumberOfCells(num_cells)
    return cell_array