Esempio n. 1
0
def VTKImageToNum(i):
   __typeDict = { vtk.VTK_ID_TYPE: np.int64, 
         vtk.VTK_CHAR:np.int8, 
         vtk.VTK_UNSIGNED_CHAR:np.uint8,
         vtk.VTK_SHORT:np.int16, 
         vtk.VTK_UNSIGNED_SHORT:np.uint16, 
         vtk.VTK_INT:np.int32, 
         vtk.VTK_FLOAT:np.float32, 
         vtk.VTK_DOUBLE:np.float64, 
         vtk.VTK_LONG:np.int64}
   ie = vtk.vtkImageExport()
   d = list(i.GetDimensions())
   d.reverse()
   if d[0] == 1: d = d[1:]
   if d[0] == 1: d = d[1:]
   #d.reverse()
   it = i.GetScalarType()
   scalars = i.GetPointData().GetScalars()
   if scalars: it = scalars.GetDataType()
   else: it = vtk.VTK_FLOAT
   nat = __typeDict[it]
   x = np.zeros(d,nat)
   ie.SetExportVoidPointer(x)
   ie.ImageLowerLeftOn()
   ie.SetInputData(i)
   ie.Export()
   return np.squeeze(x).T
Esempio n. 2
0
def VTKtoNumpy(vol):
    """
    Implemented from:
    http://public.kitware.com/pipermail/vtkusers/2002-September/062934.html
    """

    exporter = vtk.vtkImageExport()
    exporter.SetInput(vol)
    dims = exporter.GetDataDimensions()

    # Define Numpy data type depending on the vtkImageData scalar type
    if (exporter.GetDataScalarType() == 3):
        type = np.uint8
    if (exporter.GetDataScalarType() == 4):
        type = np.short
    if (exporter.GetDataScalarType() == 11):
        type = np.double

    # Create empty Numpy array of length equal to size of vtkImage data
    # then convert it into string and pass the pointer to the beginning of the
    # string into vtkExporter so the image data could be rewritten to the
    # string.
    a = np.zeros(reduce(np.multiply, dims), type)
    s = a.tostring()
    exporter.SetExportVoidPointer(s)
    exporter.Export()

    # Recreate nympy array from the string and return the result.
    a = np.reshape(np.fromstring(s, type), (dims[2], dims[1], dims[0]))
    return a
Esempio n. 3
0
def vtkImageDataToWxImage(data,
                          sliceNumber=-1,
                          startpos=None,
                          endpos=None,
                          ctf=None):
    """
	Converts vtk-ImageData to a WxImage
	"""
    if sliceNumber >= 0:
        data = getSlice(data, sliceNumber, startpos, endpos)
    if ctf != None:
        data = imageDataTo3Component(data, ctf)
    exporter = vtk.vtkImageExport()
    data.SetUpdateExtent(data.GetWholeExtent())
    data.Update()
    exporter.SetInputConnection(data.GetProducerPort())
    dataMemorySize = exporter.GetDataMemorySize()
    formatString = "%ds" % dataMemorySize
    structString = struct.pack(formatString, "")
    exporter.SetExportVoidPointer(structString)
    exporter.Export()
    width, height = data.GetDimensions()[0:2]
    image = wx.EmptyImage(width, height)
    image.SetData(structString)
    return image
Esempio n. 4
0
def VTKSPtoNumpy(vol):
    '''
    Utility function to convert a VTK structured points (SP) object to a numpy array
    the exporting is done via the vtkImageExport object which copies the data
    from the supplied SP object into an empty pointer or array

    C/C++ can interpret a python string as a pointer/array

    This function was shamelessly copied from
    http://public.kitware.com/pipermail/vtkusers/2002-September/013412.html
    args:
    	@a vol: vtk.vtkStructuredPoints object
    '''
    exporter = vtkImageExport()
    exporter.SetInputData(vol)
    dims = exporter.GetDataDimensions()
    if np.sum(dims) == 0:
        return np.zeros((1,64,64))
    if (exporter.GetDataScalarType() == 3):
    	dtype = UnsignedInt8
    if (exporter.GetDataScalarType() == 4):
    	dtype = np.short
    if (exporter.GetDataScalarType() == 5):
    	dtype = np.int16
    if (exporter.GetDataScalarType() == 10):
    	dtype = np.float32
    if (exporter.GetDataScalarType() == 11):
    	dtype = np.float64
    a = np.zeros(reduce(np.multiply,dims),dtype)
    s = a.tostring()
    exporter.SetExportVoidPointer(s)
    exporter.Export()
    a = np.reshape(np.fromstring(s,dtype),(dims[2],dims[0],dims[1]))
    return a
Esempio n. 5
0
def VTKSPtoNumpy(vol):
    '''
    Utility function to convert a VTK structured points (SP) object to a numpy array
    the exporting is done via the vtkImageExport object which copies the data
    from the supplied SP object into an empty pointer or array
    C/C++ can interpret a python string as a pointer/array
    This function was shamelessly copied from
    http://public.kitware.com/pipermail/vtkusers/2002-September/013412.html
    args:
    	@a vol: vtk.vtkStructuredPoints object
    '''
    exporter = vtkImageExport()
    exporter.SetInputData(vol)
    dims = exporter.GetDataDimensions()
    if np.sum(dims) == 0:
        raise RuntimeError(
            'Error converting vtk structured points file to numpy array')
        return np.zeros((1, 64, 64))
    if (exporter.GetDataScalarType() == 3):
        dtype = UnsignedInt8
    if (exporter.GetDataScalarType() == 4):
        dtype = np.short
    if (exporter.GetDataScalarType() == 5):
        dtype = np.int16
    if (exporter.GetDataScalarType() == 10):
        dtype = np.float32
    if (exporter.GetDataScalarType() == 11):
        dtype = np.float64
    a = np.zeros(reduce(np.multiply, dims), dtype)
    s = a.tostring()
    exporter.SetExportVoidPointer(s)
    exporter.Export()
    a = np.reshape(np.fromstring(s, dtype), (dims[2], dims[0], dims[1]))
    return a
Esempio n. 6
0
def VTKtoNumpy(vol):
    """
    Implemented from:
    http://public.kitware.com/pipermail/vtkusers/2002-September/062934.html
    """

    exporter = vtk.vtkImageExport()
    exporter.SetInput(vol)
    dims = exporter.GetDataDimensions()

    # Define Numpy data type depending on the vtkImageData scalar type
    if (exporter.GetDataScalarType() == 3):
       type = np.uint8
    if (exporter.GetDataScalarType() == 4):
       type = np.short
    if (exporter.GetDataScalarType() == 11):
       type = np.double

    # Create empty Numpy array of length equal to size of vtkImage data
    # then convert it into string and pass the pointer to the beginning of the
    # string into vtkExporter so the image data could be rewritten to the
    # string.
    a = np.zeros(reduce(np.multiply,dims), type)
    s = a.tostring()
    exporter.SetExportVoidPointer(s)
    exporter.Export()

    # Recreate nympy array from the string and return the result.
    a = np.reshape(np.fromstring(s,type),(dims[2],dims[1],dims[0]))
    return a
Esempio n. 7
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkImageExport(), 'Processing.',
         ('vtkImageData',), (),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Esempio n. 8
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(self,
                                       module_manager,
                                       vtk.vtkImageExport(),
                                       'Processing.', ('vtkImageData', ),
                                       (),
                                       replaceDoc=True,
                                       inputFunctions=None,
                                       outputFunctions=None)
Esempio n. 9
0
def VTKtoNumpy(vol):
    exporter = vtk.vtkImageExport()
    exporter.SetInput(vol)
    dims = exporter.GetDataDimensions()
    if (exporter.GetDataScalarType() == 3):
        type = UnsignedInt8
    if (exporter.GetDataScalarType() == 5):
        type = 'Int16'
    a = np.zeros(reduce(np.multiply,dims),type)
    s = a.tostring()
    exporter.SetExportVoidPointer(s)
    exporter.Export()
    a = np.reshape(np.fromstring(s,type),(dims[2],dims[0],dims[1]))
    return a
Esempio n. 10
0
def VTKtoNumpy(vol):
    exporter = vtk.vtkImageExport()
    exporter.SetInput(vol)
    dims = exporter.GetDataDimensions()
    if (exporter.GetDataScalarType() == 3):
        type = UnsignedInt8
    if (exporter.GetDataScalarType() == 5):
        type = 'Int16'
    a = np.zeros(reduce(np.multiply, dims), type)
    s = a.tostring()
    exporter.SetExportVoidPointer(s)
    exporter.Export()
    a = np.reshape(np.fromstring(s, type), (dims[2], dims[0], dims[1]))
    return a
Esempio n. 11
0
def loadVtk3d(filepath):
    reader = vtk.vtkXMLImageDataReader()
    reader.SetFileName(filepath)
    reader.Update()
    imgVtk = reader.GetOutput()
    dataExport = vtk.vtkImageExport()
    dataExport.SetInputData(imgVtk)
    nx, ny, nz = dataExport.GetDataDimensions()
    dataType = dataExport.GetDataScalarType()
    npDataType = vtkDTypeToNumpyDType(dataType)
    if npDataType is None:
        # meaning data type not supported
        return (None, None)
    img = np.zeros((nx, ny, nz), dtype=npDataType, order='F')
    dataExport.Export(img)
    return (img, dataExport.GetDataSpacing())
Esempio n. 12
0
def ExportVTKImageToArray( image ):
    export = vtk.vtkImageExport()
    if vtk.VTK_MAJOR_VERSION <= 5:
        export.SetInput( image )
    else:
        export.SetInputData( image )
    nCmps = image.GetNumberOfScalarComponents()
    dim = image.GetDimensions()
    # The underlying assumption is that the type is vtk.VTK_UNSIGNED_CHAR
    size = dim[0]*dim[1]*dim[2]*nCmps
    imString = np.zeros((size,), np.uint8).tostring()
    export.Export( imString )
    array = np.fromstring( imString, np.uint8 )
    del imString
    # reshape array appropriately.
    array = np.reshape(array, [dim[2], dim[1], dim[0]])
    return array
def vtkImageDataToWxImage(data, sliceNumber=-1, startpos=None, endpos=None, ctf=None):
    """
	Converts vtk-ImageData to a WxImage
	"""
    if sliceNumber >= 0:
        data = getSlice(data, sliceNumber, startpos, endpos)
    if ctf != None:
        data = imageDataTo3Component(data, ctf)
    exporter = vtk.vtkImageExport()
    data.SetUpdateExtent(data.GetWholeExtent())
    data.Update()
    exporter.SetInputConnection(data.GetProducerPort())
    dataMemorySize = exporter.GetDataMemorySize()
    formatString = "%ds" % dataMemorySize
    structString = struct.pack(formatString, "")
    exporter.SetExportVoidPointer(structString)
    exporter.Export()
    width, height = data.GetDimensions()[0:2]
    image = wx.EmptyImage(width, height)
    image.SetData(structString)
    return image
Esempio n. 14
0
def vtk_image_to_array(vtk_image) :
    """ Create an ``numpy.ndarray`` matching the contents and type of given image. 
        If the number of scalars components in the image is greater than 1, then
        the ndarray will be 4D, otherwise it will be 3D. 
    """
    
    exporter = vtkImageExport()
    exporter.SetInput(vtk_image)
    
    # Create the destination array
    extent = vtk_image.GetWholeExtent()
    shape = [extent[5]-extent[4]+1,
             extent[3]-extent[2]+1,
             extent[1]-extent[0]+1]
    if vtk_image.GetNumberOfScalarComponents() > 1:
        shape += [vtk_image.GetNumberOfScalarComponents()]
    dtype = vtk.util.numpy_support.get_numpy_array_type(vtk_image.GetScalarType())
    array = numpy.zeros(shape, dtype=dtype)
    
    exporter.Export(array)
    
    return array
Esempio n. 15
0
def vtk2array(vtk_array):
    """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.  The function
    is very efficient since it uses the VTK imaging pipeline to
    convert the data.  If a sufficiently new version of VTK (5.2) is
    installed then it actually uses the buffer interface to return a
    view of the VTK array in the returned numpy array.

    Parameters
    ----------

    - vtk_array : `vtkDataArray`

      The VTK data array to be converted.

    """
    typ = vtk_array.GetDataType()
    assert typ in get_vtk_to_numeric_typemap().keys(), \
           "Unsupported array type %s"%typ

    shape = vtk_array.GetNumberOfTuples(), \
            vtk_array.GetNumberOfComponents()
    if shape[0] == 0:
        dtype = get_numeric_array_type(typ)
        return numpy.array([], dtype)

    # First check if this array already has a numpy array cached,
    # if it does and the array size has not been changed, reshape
    # that and return it.
    if vtk_array in _array_cache:
        arr = _array_cache.get(vtk_array)
        if shape[1] == 1:
            shape = (shape[0], )
        if arr.size == numpy.prod(shape):
            arr = numpy.reshape(arr, shape)
            return arr

    # If VTK's new numpy support is available, use the buffer interface.
    if numpy_support is not None and typ != vtkConstants.VTK_BIT:
        dtype = get_numeric_array_type(typ)
        result = numpy.frombuffer(vtk_array, dtype=dtype)
        if shape[1] == 1:
            shape = (shape[0], )
        result.shape = shape
        return result

    # Setup an imaging pipeline to export the array.
    img_data = vtk.vtkImageData()
    img_data.SetDimensions(shape[0], 1, 1)
    if typ == vtkConstants.VTK_BIT:
        iarr = vtk.vtkCharArray()
        iarr.DeepCopy(vtk_array)
        img_data.GetPointData().SetScalars(iarr)
    elif typ == vtkConstants.VTK_ID_TYPE:
        # Needed since VTK_ID_TYPE does not work with VTK 4.5.
        iarr = vtk.vtkLongArray()
        iarr.SetNumberOfTuples(vtk_array.GetNumberOfTuples())
        nc = vtk_array.GetNumberOfComponents()
        iarr.SetNumberOfComponents(nc)
        for i in range(nc):
            iarr.CopyComponent(i, vtk_array, i)
        img_data.GetPointData().SetScalars(iarr)
    else:
        img_data.GetPointData().SetScalars(vtk_array)

    if is_old_pipeline():
        img_data.SetNumberOfScalarComponents(shape[1])
        if typ == vtkConstants.VTK_ID_TYPE:
            # Hack necessary because vtkImageData can't handle VTK_ID_TYPE.
            img_data.SetScalarType(vtkConstants.VTK_LONG)
            r_dtype = get_numeric_array_type(vtkConstants.VTK_LONG)
        elif typ == vtkConstants.VTK_BIT:
            img_data.SetScalarType(vtkConstants.VTK_CHAR)
            r_dtype = get_numeric_array_type(vtkConstants.VTK_CHAR)
        else:
            img_data.SetScalarType(typ)
            r_dtype = get_numeric_array_type(typ)
        img_data.Update()
    else:
        if typ == vtkConstants.VTK_ID_TYPE:
            r_dtype = get_numeric_array_type(vtkConstants.VTK_LONG)
        elif typ == vtkConstants.VTK_BIT:
            r_dtype = get_numeric_array_type(vtkConstants.VTK_CHAR)
        else:
            r_dtype = get_numeric_array_type(typ)
        img_data.Modified()

    exp = vtk.vtkImageExport()
    if is_old_pipeline():
        exp.SetInput(img_data)
    else:
        exp.SetInputData(img_data)

    # Create an array of the right size and export the image into it.
    im_arr = numpy.empty((shape[0]*shape[1],), r_dtype)
    exp.Export(im_arr)

    # Now reshape it.
    if shape[1] == 1:
        shape = (shape[0], )
    im_arr = numpy.reshape(im_arr, shape)
    return im_arr
# VTK will read the PNG image for us
reader = vtk.vtkPNGReader()
reader.SetFileName("../../Testing/Data/Input/cthead1.png")

# it has to be a single component, itk::VTKImageImport doesn't support more
lum = vtk.vtkImageLuminance()
lum.SetInput(reader.GetOutput())

# let's cast the output to float
imageCast = vtk.vtkImageCast()
imageCast.SetOutputScalarTypeToFloat()
imageCast.SetInput(lum.GetOutput())

# the end-point of this VTK pipeline segment is a vtkImageExport
vtkExporter = vtk.vtkImageExport()
vtkExporter.SetInput(imageCast.GetOutput())

# it connects to the itk::VTKImageImport at the beginning of
# the subsequent ITK pipeline; two-dimensional float type
itkImporter = itk.itkVTKImageImportF2_New()

# Call the magic function that connects the two.  This will only be
# available if you built ITK with ITK_CSWIG_CONNECTVTKITK set to ON.
CVIPy.ConnectVTKToITKF2(vtkExporter, itkImporter.GetPointer())

# perform a canny edge detection and rescale the output
canny  = itk.itkCannyEdgeDetectionImageFilterF2F2_New()
rescaler = itk.itkRescaleIntensityImageFilterF2US2_New()
canny.SetInput(itkImporter.GetOutput())
rescaler.SetInput(canny.GetOutput())
Esempio n. 17
0
def compute_topomesh_image(topomesh, img):

    image_start_time = time()
    print "<-- Computing topomesh image"

    polydata_img = np.ones_like(img)
        
    for c in list(topomesh.wisps(3)):
        if len(list(topomesh.borders(3,c))) > 0:
            polydata_start_time = time()
            sub_topomesh = cell_topomesh(topomesh,cells=[c]) 
            
            start_time = time()
            bounding_box = np.array([[0,polydata_img.shape[0]],[0,polydata_img.shape[1]],[0,polydata_img.shape[2]]])
            bounding_box[:,0] = np.floor(sub_topomesh.wisp_property('barycenter',0).values().min(axis=0)/np.array(img.resolution)).astype(int)-1
            bounding_box[:,0] = np.maximum(bounding_box[:,0],0)
            bounding_box[:,1] = np.ceil(sub_topomesh.wisp_property('barycenter',0).values().max(axis=0)/np.array(img.resolution)).astype(int)+1
            bounding_box[:,1] = np.minimum(bounding_box[:,1],np.array(img.shape)-1)
            
            sub_polydata_img = polydata_img[bounding_box[0,0]:bounding_box[0,1],bounding_box[1,0]:bounding_box[1,1],bounding_box[2,0]:bounding_box[2,1]]
            #world.add(sub_polydata_img,"topomesh_image",colormap='glasbey',alphamap='constant',bg_id=1,intensity_range=(0,1))

            reader = matrix_to_image_reader('sub_polydata_image',sub_polydata_img,sub_polydata_img.dtype)
            #reader = matrix_to_image_reader('polydata_image',polydata_img,polydata_img.dtype)

            end_time = time()
            print "  --> Extracting cell sub-image      [",end_time-start_time,"s]"

            start_time = time()
            topomesh_center = bounding_box[:,0]*np.array(img.resolution)
            positions = sub_topomesh.wisp_property('barycenter',0)
            
            polydata = vtk.vtkPolyData()
            vtk_points = vtk.vtkPoints()
            vtk_triangles = vtk.vtkCellArray()
            
            for t in sub_topomesh.wisps(2):
                triangle_points = []
                for v in sub_topomesh.borders(2,t,2):
                    p = vtk_points.InsertNextPoint(positions[v]-topomesh_center)
                    triangle_points.append(p)
                triangle_points = array_dict(triangle_points,list(sub_topomesh.borders(2,t,2)))
                poly = vtk_triangles.InsertNextCell(3)
                for v in sub_topomesh.borders(2,t,2):
                    vtk_triangles.InsertCellPoint(triangle_points[v])

            polydata.SetPoints(vtk_points)
            polydata.SetPolys(vtk_triangles)
            
            end_time = time()
            print "  --> Creating VTK PolyData      [",end_time-start_time,"s]"
            
            start_time = time()
            pol2stenc = vtk.vtkPolyDataToImageStencil()
            pol2stenc.SetTolerance(0)
            pol2stenc.SetOutputOrigin((0,0,0))
            #pol2stenc.SetOutputOrigin(tuple(-bounding_box[:,0]))
            pol2stenc.SetOutputSpacing(img.resolution)
            SetInput(pol2stenc,polydata)
            pol2stenc.Update()
            end_time = time()
            print "  --> Cell ",c," polydata stencil   [",end_time-start_time,"s]"
            
            start_time = time()
            imgstenc = vtk.vtkImageStencil()
            if vtk.VTK_MAJOR_VERSION <= 5:
                imgstenc.SetInput(reader.GetOutput())
                imgstenc.SetStencil(pol2stenc.GetOutput())
            else:
                imgstenc.SetInputData(reader.GetOutput())
                imgstenc.SetStencilConnection(pol2stenc.GetOutputPort())
            imgstenc.ReverseStencilOn()
            imgstenc.SetBackgroundValue(c)
            imgstenc.Update()
            end_time = time()
            print "  --> Cell ",c," image stencil   [",end_time-start_time,"s]"

            start_time = time()
            dim = tuple((bounding_box[:,1]-bounding_box[:,0])[::-1])
            array = np.ones(dim, img.dtype)
            export = vtk.vtkImageExport()
            export.SetInputConnection(imgstenc.GetOutputPort())
            export.Export(array)
            end_time = time()
            print "  --> Exporting image       [",end_time-start_time,"s]"
            
            start_time = time()
            array = np.transpose(array,(2,1,0))
            polydata_img[bounding_box[0,0]:bounding_box[0,1],bounding_box[1,0]:bounding_box[1,1],bounding_box[2,0]:bounding_box[2,1]] = array
            end_time = time()
            print "  --> Inserting cell sub-image       [",end_time-start_time,"s]"
            
            polydata_end_time = time()
            print "--> Inserting topomesh cell ",c,"   [",polydata_end_time-polydata_start_time,"s]"
        
    image_end_time = time()
    print "<-- Computing topomesh image   [",image_end_time-image_start_time,"s]"

    return polydata_img
# VTK will read the PNG image for us
reader = vtk.vtkPNGReader()
reader.SetFileName("../../Testing/Data/Input/cthead1.png")

# it has to be a single component, itk::VTKImageImport doesn't support more
lum = vtk.vtkImageLuminance()
lum.SetInput(reader.GetOutput())

# let's cast the output to float
imageCast = vtk.vtkImageCast()
imageCast.SetOutputScalarTypeToFloat()
imageCast.SetInput(lum.GetOutput())

# the end-point of this VTK pipeline segment is a vtkImageExport
vtkExporter = vtk.vtkImageExport()
vtkExporter.SetInput(imageCast.GetOutput())

# it connects to the itk::VTKImageImport at the beginning of
# the subsequent ITK pipeline; two-dimensional float type
itkImporter = itk.itkVTKImageImportF2_New()

# Call the magic function that connects the two.  This will only be
# available if you built ITK with ITK_CSWIG_CONNECTVTKITK set to ON.
CVIPy.ConnectVTKToITKF2(vtkExporter, itkImporter.GetPointer())

# perform a canny edge detection and rescale the output
canny  = itk.itkCannyEdgeDetectionImageFilterF2F2_New()
rescaler = itk.itkRescaleIntensityImageFilterF2US2_New()
canny.SetInput(itkImporter.GetOutput())
rescaler.SetInput(canny.GetOutput())
Esempio n. 19
-1
 def __init__(self):
     self.__export = vtkImageExport()
     self.__ConvertUnsignedShortToInt = False