예제 #1
0
  def exportToTable(self, table, nonEmptyKeysOnly = True):
    """
    Export statistics to table node
    """
    tableWasModified = table.StartModify()
    table.RemoveAllColumns()

    keys = self.getNonEmptyKeys() if nonEmptyKeysOnly else self.keys
    columnHeaderNames, uniqueColumnHeaderNames = self.getHeaderNames(nonEmptyKeysOnly)

    # Define table columns
    statistics = self.getStatistics()
    for key in keys:
      # create table column appropriate for data type; currently supported: float, int, long, string
      measurements = [statistics[segmentID, key] for segmentID in statistics["SegmentIDs"] if
                      (segmentID, key) in statistics]
      if len(measurements)==0: # there were not measurements and therefore use the default "string" representation
        col = table.AddColumn()
      elif isinstance(measurements[0], int):
        col = table.AddColumn(vtk.vtkLongArray())
      elif isinstance(measurements[0], float):
        col = table.AddColumn(vtk.vtkDoubleArray())
      else: # default
        col = table.AddColumn()
      plugin = self.getPluginByKey(key)
      columnName = uniqueColumnHeaderNames[key]
      longColumnName = columnHeaderNames[key]
      col.SetName( columnName )
      if plugin:
        table.SetColumnProperty(columnName, "Plugin", plugin.name)
        longColumnName += '<br>Computed by '+plugin.name+' Statistics plugin'
      table.SetColumnLongName(columnName, longColumnName)
      measurementInfo = statistics["MeasurementInfo"][key] if key in statistics["MeasurementInfo"] else {}
      if measurementInfo:
        for mik, miv in measurementInfo.items():
          if mik=='description':
            table.SetColumnDescription(columnName, str(miv))
          elif mik=='units':
            table.SetColumnUnitLabel(columnName, str(miv))
          else:
            table.SetColumnProperty(columnName, str(mik), str(miv))

    # Fill columns
    for segmentID in statistics["SegmentIDs"]:
      rowIndex = table.AddEmptyRow()
      columnIndex = 0
      for key in keys:
        value = statistics[segmentID, key] if (segmentID, key) in statistics else None
        if value is None and key!='Segment':
          value = float('nan')
        table.GetTable().GetColumn(columnIndex).SetValue(rowIndex, value)
        columnIndex += 1

    table.Modified()
    table.EndModify(tableWasModified)
예제 #2
0
    def testNumpyReduce(self):
        "Test that reducing methods return scalars."
        vtk_array = vtk.vtkLongArray()
        for i in range(0, 10):
            vtk_array.InsertNextValue(i)

        numpy_vtk_array = dsa.vtkDataArrayToVTKArray(vtk_array)
        s = numpy_vtk_array.sum()
        self.assertEqual(s, 45)
        self.assertEqual(type(s), numpy.int64)

        m = numpy_vtk_array.mean()
        self.assertEqual(m, 4.5)
        self.assertEqual(type(m), numpy.float64)
def createLongArray(
        name,
        n_components=1,
        n_tuples=0,
        init_to_zero=0,
        verbose=0):

    larray = vtk.vtkLongArray()
    larray.SetName(name)
    larray.SetNumberOfComponents(n_components)
    larray.SetNumberOfTuples(n_tuples)

    if (init_to_zero):
        for k_tuple in xrange(n_tuples):
            iarray.SetTuple(k_tuple, [0]*n_components)

    return larray
예제 #4
0
    def extract_cell_field_data(self):
        """
        Extracts basic information about cell field
        :return:
        """

        cellType = vtk.vtkIntArray()
        cellType.SetName("celltype")
        cellTypeIntAddr = extract_address_int_from_vtk_object(self.field_extractor, cellType)

        # Also get the CellId
        cellId = vtk.vtkLongArray()
        cellId.SetName("cellid")
        cellIdIntAddr = extract_address_int_from_vtk_object(self.field_extractor, cellId)

        usedCellTypesList = self.field_extractor.fillCellFieldData3D(cellTypeIntAddr, cellIdIntAddr)

        ret_val = {
            'cell_type_array':cellType,
            'cell_id_array':cellId,
            'used_cell_types':usedCellTypesList
        }
        return ret_val
예제 #5
0
Created by Prabhu Ramachandran in Feb. 2008.
"""

import vtk
import vtkConstants
import numpy

# Useful constants for VTK arrays.
VTK_ID_TYPE_SIZE = vtk.vtkIdTypeArray().GetDataTypeSize()
if VTK_ID_TYPE_SIZE == 4:
    ID_TYPE_CODE = numpy.int32
elif VTK_ID_TYPE_SIZE == 8:
    ID_TYPE_CODE = numpy.int64

VTK_LONG_TYPE_SIZE = vtk.vtkLongArray().GetDataTypeSize()
if VTK_LONG_TYPE_SIZE == 4:
    LONG_TYPE_CODE = numpy.int32
    ULONG_TYPE_CODE = numpy.uint32
elif VTK_LONG_TYPE_SIZE == 8:
    LONG_TYPE_CODE = numpy.int64
    ULONG_TYPE_CODE = numpy.uint64


def get_vtk_array_type(numpy_array_type):
    """Returns a VTK typecode given a numpy array."""
    # This is a Mapping from numpy array types to VTK array types.
    _np_vtk = {numpy.character:vtkConstants.VTK_UNSIGNED_CHAR,
                numpy.uint8:vtkConstants.VTK_UNSIGNED_CHAR,
                numpy.uint16:vtkConstants.VTK_UNSIGNED_SHORT,
                numpy.uint32:vtkConstants.VTK_UNSIGNED_INT,
예제 #6
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
예제 #7
0
def topomesh_to_vtk_polydata(topomesh,degree=2,positions=None,topomesh_center=None,coef=1):
    import numpy as np
    import vtk
    from time import time
    from openalea.container import array_dict

    if positions is None:
        positions = topomesh.wisp_property('barycenter',0)
        
    if topomesh_center is None:
        topomesh_center = np.mean(positions.values(),axis=0)
#        topomesh_center = np.array([0,0,0])
        print topomesh_center

    vtk_mesh = vtk.vtkPolyData()
    vtk_points = vtk.vtkPoints()
    vtk_edges = vtk.vtkCellArray()
    vtk_triangles = vtk.vtkCellArray()
    vtk_cells = vtk.vtkLongArray()

    start_time = time()
    print "--> Creating VTK PolyData"
    
    if degree == 3:
        for c in topomesh.wisps(3):
            cell_points = []
            cell_center = np.mean([positions[v] for v in topomesh.borders(3,c,3)],axis=0)
            for v in topomesh.borders(3,c,3):
                position = cell_center + coef*(positions[v]-cell_center) - topomesh_center
                position[np.where(np.abs(position)<.001)] =0.
                p = vtk_points.InsertNextPoint(position)
                cell_points.append(p)
            cell_points = array_dict(cell_points,list(topomesh.borders(3,c,3)))

            for t in topomesh.borders(3,c):
                poly = vtk_triangles.InsertNextCell(3)
                for v in topomesh.borders(2,t,2):
                    vtk_triangles.InsertCellPoint(cell_points[v])
                vtk_cells.InsertValue(poly,c)

    elif degree == 2:
        for t in topomesh.wisps(2):
            triangle_points = []
            triangle_center = np.mean([positions[v] for v in topomesh.borders(2,t,2)],axis=0)
            for v in topomesh.borders(2,t,2):
                position = triangle_center + coef*(positions[v]-triangle_center) - topomesh_center
                position[np.where(np.abs(position)<.001)] =0.
                p = vtk_points.InsertNextPoint(position)
                triangle_points.append(p)
            triangle_points = array_dict(triangle_points,list(topomesh.borders(2,t,2)))
            poly = vtk_triangles.InsertNextCell(3)
            for v in topomesh.borders(2,t,2):
                vtk_triangles.InsertCellPoint(triangle_points[v])
            vtk_cells.InsertValue(poly,list(topomesh.regions(2,t))[0])

    elif degree == 1:
        points = []
        for v in topomesh.wisps(0):
            position = positions[v]
            position[np.where(np.abs(position)<.001)] =0.
            p = vtk_points.InsertNextPoint(position)
            points.append(p)
        points = array_dict(points,list(topomesh.wisps(0)))

        for e in topomesh.wisps(1):
            # if topomesh.wisp_property('epidermis',1)[e]:
            # if True:
            if len(list(topomesh.regions(1,e))) > 2:
                c = vtk_edges.InsertNextCell(2)
                for v in topomesh.borders(1,e):
                    vtk_edges.InsertCellPoint(points[v])

    print"  --> Linking Mesh"
    vtk_mesh.SetPoints(vtk_points)
    vtk_mesh.SetPolys(vtk_triangles)
    vtk_mesh.SetLines(vtk_edges)
    vtk_mesh.GetCellData().SetScalars(vtk_cells)

    end_time = time()
    print "<-- Creating VTK PolyData      [",end_time-start_time,"s]"

    return vtk_mesh
예제 #8
0
def image_to_vtk_cell_polydata(img,considered_cells=None,mesh_center=None,coef=1.0,mesh_fineness=1.0,smooth_factor=1.0):

    start_time = time()
    print "--> Generating vtk mesh from image"

    vtk_mesh = vtk.vtkPolyData()
    vtk_points = vtk.vtkPoints()
    vtk_triangles = vtk.vtkCellArray()
    vtk_cells = vtk.vtkLongArray()
    
    nx, ny, nz = img.shape
    data_string = img.tostring('F')

    reader = vtk.vtkImageImport()
    reader.CopyImportVoidPointer(data_string, len(data_string))
    if img.dtype == np.uint8:
        reader.SetDataScalarTypeToUnsignedChar()
    else:
        reader.SetDataScalarTypeToUnsignedShort()
    reader.SetNumberOfScalarComponents(1)
    reader.SetDataExtent(0, nx - 1, 0, ny - 1, 0, nz - 1)
    reader.SetWholeExtent(0, nx - 1, 0, ny - 1, 0, nz - 1)
    reader.SetDataSpacing(*img.resolution)
    reader.Update()

    if considered_cells is None:
        considered_cells = np.unique(img)[1:]

    if mesh_center is None:
        #mesh_center = np.array(img.resolution)*np.array(img.shape)/2.
        mesh_center = np.array([0,0,0])

    for label in considered_cells:

        cell_start_time = time()

        cell_volume = (img==label).sum()*np.array(img.resolution).prod()

        # mask_data = vtk.vtkImageThreshold()
        # mask_data.SetInputConnection(reader.GetOutputPort())
        # mask_data.ThresholdBetween(label, label)
        # mask_data.ReplaceInOn()
        # mask_data.SetInValue(label)
        # mask_data.SetOutValue(0)
        contour = vtk.vtkDiscreteMarchingCubes()
        # contour.SetInput(mask_data.GetOutput())
        SetInput(contour,reader.GetOutput())
        contour.ComputeNormalsOn()
        contour.ComputeGradientsOn()
        contour.SetValue(0,label)
        contour.Update()

        # print "    --> Marching Cubes : ",contour.GetOutput().GetPoints().GetNumberOfPoints()," Points,",contour.GetOutput().GetNumberOfCells()," Triangles,  1 Cell"

        # decimate = vtk.vtkDecimatePro()
        # decimate.SetInputConnection(contour.GetOutputPort())
        # # decimate.SetTargetReduction(0.75)
        # decimate.SetTargetReduction(0.66)
        # # decimate.SetTargetReduction(0.5)
        # # decimate.SetMaximumError(2*np.sqrt(3))
        # decimate.Update()

        smooth_iterations = int(np.ceil(smooth_factor*8.))

        smoother = vtk.vtkWindowedSincPolyDataFilter()
        SetInput(smoother,contour.GetOutput())
        smoother.BoundarySmoothingOn()
        # smoother.BoundarySmoothingOff()
        smoother.FeatureEdgeSmoothingOn()
        # smoother.FeatureEdgeSmoothingOff()
        smoother.SetFeatureAngle(120.0)
        # smoother.SetPassBand(1)
        smoother.SetPassBand(0.01)
        smoother.SetNumberOfIterations(smooth_iterations)
        smoother.NonManifoldSmoothingOn()
        smoother.NormalizeCoordinatesOn()
        smoother.Update()

        divisions = int(np.ceil(np.power(cell_volume,1/3.)*mesh_fineness))

        decimate = vtk.vtkQuadricClustering()
        # decimate = vtk.vtkQuadricDecimation()
        # decimate = vtk.vtkDecimatePro()
        # decimate.SetInput(contour.GetOutput())
        SetInput(decimate,smoother.GetOutput())
        # decimate.SetTargetReduction(0.95)
        # decimate.AutoAdjustNumberOfDivisionsOff()
        decimate.SetNumberOfDivisions(divisions,divisions,divisions)
        decimate.SetFeaturePointsAngle(120.0)
        # decimate.AttributeErrorMetricOn()
        # decimate.ScalarsAttributeOn()
        # decimate.PreserveTopologyOn()
        # decimate.CopyCellDataOn()
        # decimate.SetMaximumCost(1.0)
        # decimate.SetMaximumCollapsedEdges(10000.0)
        decimate.Update()

        # print "    --> Decimation     : ",decimate.GetOutput().GetPoints().GetNumberOfPoints()," Points,",decimate.GetOutput().GetNumberOfCells()," Triangles,  1 Cell"

        cell_polydata = decimate.GetOutput()
        # cell_polydata = smoother.GetOutput()

        polydata_points = np.array([cell_polydata.GetPoints().GetPoint(p) for p in xrange(cell_polydata.GetPoints().GetNumberOfPoints())])
        polydata_center = polydata_points.mean(axis=0)
        polydata_points = polydata_center + coef*(polydata_points-polydata_center) - mesh_center

        cell_points = []
        for p in xrange(cell_polydata.GetPoints().GetNumberOfPoints()):
            pid = vtk_points.InsertNextPoint(polydata_points[p])
            cell_points.append(pid)
        cell_points = array_dict(cell_points,np.arange(cell_polydata.GetPoints().GetNumberOfPoints()))

        for t in xrange(cell_polydata.GetNumberOfCells()):
            poly = vtk_triangles.InsertNextCell(3)
            for i in xrange(3):
                pid = cell_polydata.GetCell(t).GetPointIds().GetId(i)
                vtk_triangles.InsertCellPoint(cell_points[pid])
                vtk_cells.InsertValue(poly,label)

        cell_end_time = time()
        print "  --> Cell",label,":",decimate.GetOutput().GetNumberOfCells(),"triangles (",cell_volume," microm3 ) [",cell_end_time-cell_start_time,"s]"

    vtk_mesh.SetPoints(vtk_points)
    vtk_mesh.SetPolys(vtk_triangles)
    vtk_mesh.GetCellData().SetScalars(vtk_cells)

    print "  <-- Cell Mesh      : ",vtk_mesh.GetPoints().GetNumberOfPoints()," Points,",vtk_mesh.GetNumberOfCells()," Triangles, ",len(considered_cells)," Cells"

    end_time = time()
    print "<-- Generating vtk mesh from image      [",end_time-start_time,"s]"

    return vtk_mesh
예제 #9
0
def image_to_vtk_polydata(img,considered_cells=None,mesh_center=None,coef=1.0,mesh_fineness=1.0):
    start_time = time()
    print "--> Generating vtk mesh from image"

    vtk_mesh = vtk.vtkPolyData()
    vtk_points = vtk.vtkPoints()
    vtk_triangles = vtk.vtkCellArray()
    vtk_cells = vtk.vtkLongArray()
    
    nx, ny, nz = img.shape
    data_string = img.tostring('F')

    reader = vtk.vtkImageImport()
    reader.CopyImportVoidPointer(data_string, len(data_string))
    if img.dtype == np.uint8:
        reader.SetDataScalarTypeToUnsignedChar()
    else:
        reader.SetDataScalarTypeToUnsignedShort()
    reader.SetNumberOfScalarComponents(1)
    reader.SetDataExtent(0, nx - 1, 0, ny - 1, 0, nz - 1)
    reader.SetWholeExtent(0, nx - 1, 0, ny - 1, 0, nz - 1)
    reader.SetDataSpacing(*img.resolution)

    if considered_cells is None:
        considered_cells = np.unique(img)[1:]

    if mesh_center is None:
        mesh_center = np.array(img.resolution)*np.array(img.shape)/2.

    marching_cube_start_time = time()
    print "  --> Marching Cubes"
    contour = vtk.vtkDiscreteMarchingCubes()
    SetInput(contour,reader.GetOutput())
    contour.ComputeNormalsOn()
    contour.ComputeGradientsOn()
    contour.ComputeScalarsOn()
    for i,label in enumerate(considered_cells):
        contour.SetValue(i,label)
    contour.Update()
    marching_cube_end_time = time()
    print "  <-- Marching Cubes : ",contour.GetOutput().GetPoints().GetNumberOfPoints()," Points,",contour.GetOutput().GetNumberOfCells()," Triangles, ",len(np.unique(img)[1:])," Cells [",marching_cube_end_time - marching_cube_start_time,"s]"

    marching_cubes = contour.GetOutput()

    marching_cubes_cell_data = marching_cubes.GetCellData().GetArray(0)

    triangle_cell_start_time = time()
    print "    --> Listing triangles"
    print "      - ",marching_cubes.GetNumberOfCells()," triangles"
    marching_cubes_triangles = np.sort([[marching_cubes.GetCell(t).GetPointIds().GetId(i) for i in xrange(3)] for t in xrange(marching_cubes.GetNumberOfCells())])   
    triangle_cell_end_time = time()
    print "    <-- Listing triangles            [",triangle_cell_end_time - triangle_cell_start_time,"s]"

    triangle_cell_start_time = time()
    print "    --> Listing triangle cells"
    triangle_cell = np.array([marching_cubes_cell_data.GetTuple(t)[0] for t in xrange(marching_cubes.GetNumberOfCells())],np.uint16)
    triangle_cell_end_time = time()
    print "    <-- Listing triangle cells     [",triangle_cell_end_time - triangle_cell_start_time,"s]"

    triangle_cell_start_time = time()
    print "    --> Updating marching cubes mesh"
    vtk_mesh = vtk.vtkPolyData()
    vtk_points = vtk.vtkPoints()
    vtk_triangles = vtk.vtkCellArray()
    vtk_cells = vtk.vtkLongArray()

    for label in considered_cells:

        # cell_start_time = time()

        cell_marching_cubes_triangles = marching_cubes_triangles[np.where(triangle_cell == label)]

        marching_cubes_point_ids = np.unique(cell_marching_cubes_triangles)

        marching_cubes_points = np.array([marching_cubes.GetPoints().GetPoint(p) for p in marching_cubes_point_ids])
        marching_cubes_center = marching_cubes_points.mean(axis=0)
        marching_cubes_points = marching_cubes_center + coef*(marching_cubes_points-marching_cubes_center) - mesh_center

        cell_points = []
        for p in xrange(marching_cubes_points.shape[0]):
            pid = vtk_points.InsertNextPoint(marching_cubes_points[p])
            cell_points.append(pid)
        cell_points = array_dict(cell_points,marching_cubes_point_ids)

        for t in xrange(cell_marching_cubes_triangles.shape[0]):
            poly = vtk_triangles.InsertNextCell(3)
            for i in xrange(3):
                pid = cell_marching_cubes_triangles[t][i]
                vtk_triangles.InsertCellPoint(cell_points[pid])
            vtk_cells.InsertValue(poly,label)

        # cell_end_time = time()
        # print "  --> Cell",label,":",cell_marching_cubes_triangles.shape[0],"triangles [",cell_end_time-cell_start_time,"s]"

    vtk_mesh.SetPoints(vtk_points)
    vtk_mesh.SetPolys(vtk_triangles)
    vtk_mesh.GetCellData().SetScalars(vtk_cells)

    triangle_cell_end_time = time()
    print "    <-- Updating marching cubes mesh [",triangle_cell_end_time - triangle_cell_start_time,"s]"

    decimation_start_time = time()
    print "  --> Decimation"
    smoother = vtk.vtkWindowedSincPolyDataFilter()
    SetInput(smoother,vtk_mesh)
    smoother.SetFeatureAngle(30.0)
    smoother.SetPassBand(0.05)
    smoother.SetNumberOfIterations(25)
    smoother.NonManifoldSmoothingOn()
    smoother.NormalizeCoordinatesOn()
    smoother.Update()

    decimate = vtk.vtkQuadricClustering()
    SetInput(decimate,smoother.GetOutput())
    decimate.SetNumberOfDivisions(*tuple(mesh_fineness*np.array(np.array(img.shape)*np.array(img.resolution)/2.,np.uint16)))
    decimate.SetFeaturePointsAngle(30.0)
    decimate.CopyCellDataOn()
    decimate.Update()

    decimation_end_time = time()
    print "  <-- Decimation     : ",decimate.GetOutput().GetPoints().GetNumberOfPoints()," Points,",decimate.GetOutput().GetNumberOfCells()," Triangles, ",len(considered_cells)," Cells [",decimation_end_time - decimation_start_time,"s]"

    end_time = time()
    print "<-- Generating vtk mesh from image      [",end_time-start_time,"s]"

    return decimate.GetOutput()
예제 #10
0

Created by Prabhu Ramachandran in Feb. 2008.
"""

import vtk
import numpy

# Useful constants for VTK arrays.
VTK_ID_TYPE_SIZE = vtk.vtkIdTypeArray().GetDataTypeSize()
if VTK_ID_TYPE_SIZE == 4:
    ID_TYPE_CODE = numpy.int32
elif VTK_ID_TYPE_SIZE == 8:
    ID_TYPE_CODE = numpy.int64

VTK_LONG_TYPE_SIZE = vtk.vtkLongArray().GetDataTypeSize()
if VTK_LONG_TYPE_SIZE == 4:
    LONG_TYPE_CODE = numpy.int32
    ULONG_TYPE_CODE = numpy.uint32
elif VTK_LONG_TYPE_SIZE == 8:
    LONG_TYPE_CODE = numpy.int64
    ULONG_TYPE_CODE = numpy.uint64


def get_vtk_array_type(numpy_array_type):
    """Returns a VTK typecode given a numpy array."""
    # This is a Mapping from numpy array types to VTK array types.
    _np_vtk = {numpy.character:vtk.VTK_UNSIGNED_CHAR,
                numpy.uint8:vtk.VTK_UNSIGNED_CHAR,
                numpy.uint16:vtk.VTK_UNSIGNED_SHORT,
                numpy.uint32:vtk.VTK_UNSIGNED_INT,
예제 #11
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, reshape that and return it.
    if vtk_array in _array_cache:
        arr = _array_cache.get(vtk_array)
        if shape[1] == 1:
            shape = (shape[0], )
        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)

    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()

    exp = vtk.vtkImageExport()
    exp.SetInput(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
예제 #12
0
    def exportToTable(self, table, nonEmptyKeysOnly=True):
        """
    Export statistics to table node
    """
        tableWasModified = table.StartModify()
        table.RemoveAllColumns()

        keys = self.getNonEmptyKeys() if nonEmptyKeysOnly else self.keys
        columnHeaderNames, uniqueColumnHeaderNames = self.getHeaderNames(
            nonEmptyKeysOnly)

        # Define table columns
        statistics = self.getStatistics()
        for key in keys:
            # create table column appropriate for data type; currently supported: float, int, long, string
            measurements = [
                statistics[segmentID, key]
                for segmentID in statistics["SegmentIDs"]
                if statistics.has_key((segmentID, key))
            ]
            if len(
                    measurements
            ) == 0:  # there were not measurements and therefore use the default "string" representation
                col = table.AddColumn()
            elif type(measurements[0]) in [int, long]:
                col = table.AddColumn(vtk.vtkLongArray())
            elif type(measurements[0]) is float:
                col = table.AddColumn(vtk.vtkDoubleArray())
            else:  # default
                col = table.AddColumn()
            plugin = self.getPluginByKey(key)
            columnName = uniqueColumnHeaderNames[key]
            longColumnName = columnHeaderNames[key]
            col.SetName(columnName)
            if plugin:
                table.SetColumnProperty(columnName, "Plugin", plugin.name)
                longColumnName += '<br>Computed by ' + plugin.name + ' Statistics plugin'
            table.SetColumnLongName(columnName, longColumnName)
            measurementInfo = statistics["MeasurementInfo"][
                key] if key in statistics["MeasurementInfo"] else {}
            if measurementInfo:
                for mik, miv in measurementInfo.iteritems():
                    if mik == 'description':
                        table.SetColumnDescription(columnName, str(miv))
                    elif mik == 'units':
                        table.SetColumnUnitLabel(columnName, str(miv))
                    else:
                        table.SetColumnProperty(columnName, str(mik), str(miv))

        # Fill columns
        for segmentID in statistics["SegmentIDs"]:
            rowIndex = table.AddEmptyRow()
            columnIndex = 0
            for key in keys:
                value = statistics[segmentID, key] if statistics.has_key(
                    (segmentID, key)) else None
                if value is None and key != 'Segment':
                    value = float('nan')
                table.GetTable().GetColumn(columnIndex).SetValue(
                    rowIndex, value)
                columnIndex += 1

        table.Modified()
        table.EndModify(tableWasModified)
import pytest
import vtk

from pytestvtk.assert_vtk import assert_vtk


@pytest.fixture(params=[
    vtk.vtkDoubleArray(),
    vtk.vtkFloatArray(),
    vtk.vtkIntArray(),
    vtk.vtkIdTypeArray(),
    vtk.vtkLongArray(),
    vtk.vtkShortArray(),
    vtk.vtkUnsignedCharArray(),
    vtk.vtkUnsignedIntArray(),
    vtk.vtkUnsignedLongArray(),
    vtk.vtkUnsignedLongLongArray(),
    vtk.vtkUnsignedShortArray(),
    vtk.vtkCharArray(),
])
def vtk_array(request):
    array = request.param
    array.SetName('testing_array')
    array.SetNumberOfTuples(3)
    array.SetNumberOfComponents(3)
    array.InsertTuple3(0, 1, 2, 3)
    array.InsertTuple3(1, 4, 5, 6)
    array.InsertTuple3(2, 7, 8, 9)
    return array

예제 #14
0
#!/usr/bin/env python

import vtk
import os

graph = vtk.vtkMutableDirectedGraph()

name = vtk.vtkStringArray()
name.SetName("path")

size = vtk.vtkLongArray()
size.SetName("size")

graph.GetVertexData().AddArray(name)
graph.GetVertexData().AddArray(size)

folder = "/home/bryan/Documents"

parent = graph.AddVertex()
name.InsertNextValue(folder)
id_map = {folder: parent}

for dirpath, dirnames, filenames in os.walk(folder):
    parent = id_map[dirpath]
    this_size = 0
    for filename in filenames:
        child_path = os.path.join(dirpath, filename)
        try:
            child_size = os.path.getsize(child_path)
        except OSError:
            child_size = 0