Example #1
0
def get_polydata_from(points, tr_re):

    numberPoints = len(points)
    Points = vtkPoints()
    ntype = get_numpy_array_type(Points.GetDataType())
    points_vtk = numpy_to_vtk(np.asarray(points, order='C', dtype=ntype),
                              deep=1)
    Points.SetNumberOfPoints(numberPoints)
    Points.SetData(points_vtk)

    Triangles = vtkCellArray()
    for item in tr_re:
        Triangle = vtkTriangle()
        Triangle.GetPointIds().SetId(0, item[0])
        Triangle.GetPointIds().SetId(1, item[1])
        Triangle.GetPointIds().SetId(2, item[2])
        Triangles.InsertNextCell(Triangle)

    polydata = vtkPolyData()
    polydata.SetPoints(Points)
    polydata.SetPolys(Triangles)

    polydata.Modified()
    polydata.Update()

    return polydata
Example #2
0
def get_polydata_from(points, tr_re):

    numberPoints = len(points)
    Points = vtkPoints()
    ntype = get_numpy_array_type(Points.GetDataType())
    points_vtk = numpy_to_vtk(np.asarray(points, order='C',dtype=ntype), deep=1)
    Points.SetNumberOfPoints(numberPoints)
    Points.SetData(points_vtk)

    Triangles = vtkCellArray()
    for item in tr_re:
        Triangle = vtkTriangle()
        Triangle.GetPointIds().SetId(0,item[0])
        Triangle.GetPointIds().SetId(1,item[1])
        Triangle.GetPointIds().SetId(2,item[2])
        Triangles.InsertNextCell(Triangle)

    polydata = vtkPolyData()
    polydata.SetPoints(Points)
    polydata.SetPolys(Triangles)

    polydata.Modified()
    polydata.Update()

    return polydata
Example #3
0
def polydata_from_numpy(coords):
    """
    Converts Numpy Array to vtkPolyData

    Parameters
    ----------
    coords: array, shape= [number of points, point features]
        array containing the point cloud in which each point has three coordinares [x, y, z]
        and none, one or three values corresponding to colors.

    Returns:
    --------
    PolyData: vtkPolyData
        concrete dataset represents vertices, lines, polygons, and triangle strips

    """

    Npts, Ndim = np.shape(coords)

    Points = vtkPoints()
    ntype = get_numpy_array_type(Points.GetDataType())
    coords_vtk = numpy_to_vtk(np.asarray(coords[:, 0:3],
                                         order='C',
                                         dtype=ntype),
                              deep=1)
    Points.SetNumberOfPoints(Npts)
    Points.SetData(coords_vtk)

    Cells = vtkCellArray()
    ids = np.arange(0, Npts, dtype=np.int64).reshape(-1, 1)
    IDS = np.concatenate([np.ones(Npts, dtype=np.int64).reshape(-1, 1), ids],
                         axis=1)
    ids_vtk = numpy_to_vtkIdTypeArray(IDS, deep=True)

    Cells.SetNumberOfCells(Npts)
    Cells.SetCells(Npts, ids_vtk)

    if Ndim == 4:
        color = [128] * len(coords)
        color = np.c_[color, color, color]
    elif Ndim == 6:
        color = coords[:, 3:]
    else:
        color = [[128, 128, 128]] * len(coords)

    color_vtk = numpy_to_vtk(np.ascontiguousarray(
        color, dtype=get_vtk_to_numpy_typemap()[VTK_UNSIGNED_CHAR]),
                             deep=True)

    color_vtk.SetName("colors")

    PolyData = vtkPolyData()
    PolyData.SetPoints(Points)
    PolyData.SetVerts(Cells)
    PolyData.GetPointData().SetScalars(color_vtk)
    return PolyData
Example #4
0
def copy_polydata_add_normals(polydata, normals):

    Points = vtkPoints()
    ntype = get_numpy_array_type(Points.GetDataType())
    normals_vtk = numpy_to_vtk(np.asarray(normals[:,0:3], order='C',dtype=ntype), deep=1)
    normals_vtk.SetName("Normals")

    output = vtkPolyData()
    output.ShallowCopy(polydata)
    output.GetPointData().SetNormals(normals_vtk)
    return output
Example #5
0
def polydata_from_numpy(coords):
    """
    Converts Numpy Array to vtkPolyData

    Parameters
    ----------
    coords: array, shape= [number of points, point features]
        array containing the point cloud in which each point has three coordinares [x, y, z]
        and none, one or three values corresponding to colors.

    Returns:
    --------
    PolyData: vtkPolyData
        concrete dataset represents vertices, lines, polygons, and triangle strips

    """

    Npts, Ndim = np.shape(coords)

    Points = vtkPoints()
    ntype = get_numpy_array_type(Points.GetDataType())
    coords_vtk = numpy_to_vtk(np.asarray(coords[:,0:3], order='C',dtype=ntype), deep=1)
    Points.SetNumberOfPoints(Npts)
    Points.SetData(coords_vtk)

    Cells = vtkCellArray()
    ids = np.arange(0,Npts, dtype=np.int64).reshape(-1,1)
    IDS = np.concatenate([np.ones(Npts, dtype=np.int64).reshape(-1,1), ids],axis=1)
    ids_vtk = numpy_to_vtkIdTypeArray(IDS, deep=True)

    Cells.SetNumberOfCells(Npts)
    Cells.SetCells(Npts,ids_vtk)

    if Ndim == 4:
        color = [128]*len(coords)
        color = np.c_[color, color, color]
    elif Ndim == 6:
        color = coords[:,3:]
    else:
        color = [[128, 128, 128]]*len(coords)

    color_vtk = numpy_to_vtk(
            np.ascontiguousarray(color, dtype=get_vtk_to_numpy_typemap()[VTK_UNSIGNED_CHAR]),
            deep=True)

    color_vtk.SetName("colors")

    PolyData = vtkPolyData()
    PolyData.SetPoints(Points)
    PolyData.SetVerts(Cells)
    PolyData.GetPointData().SetScalars(color_vtk)
    return PolyData
Example #6
0
def copy_polydata_add_normals(polydata, normals):

    Points = vtkPoints()
    ntype = get_numpy_array_type(Points.GetDataType())
    normals_vtk = numpy_to_vtk(np.asarray(normals[:, 0:3],
                                          order='C',
                                          dtype=ntype),
                               deep=1)
    normals_vtk.SetName("Normals")

    output = vtkPolyData()
    output.ShallowCopy(polydata)
    output.GetPointData().SetNormals(normals_vtk)
    return output
def dcm2mmap(input_dir, output_mmap):
    tmp_dcm_files = glob.glob(os.path.join(input_dir, '*'))

    sorter = gdcm.IPPSorter()
    sorter.Sort(tmp_dcm_files)
    dcm_files = sorter.GetFilenames()

    if not dcm_files:
        dcm_files = sorted(tmp_dcm_files)

    r = vtkgdcm.vtkGDCMImageReader()
    r.SetFileName(dcm_files[0])
    r.Update()

    x, y, z = r.GetOutput().GetDimensions()

    print x, y, z

    a_size = len(dcm_files), y, x
    t = numpy_support.get_numpy_array_type(r.GetDataScalarType())
    print t

    print t, a_size
    m_dcm = numpy.memmap(output_mmap, mode='w+', dtype='int16', shape=a_size)

    lp = 0
    zspacing = 0

    for i, dcm_file in enumerate(dcm_files):
        r = vtkgdcm.vtkGDCMImageReader()
        r.SetFileName(dcm_file)
        r.Update()

        if lp:
            zspacing += abs(r.GetImagePositionPatient()[2] - lp)
        lp = r.GetImagePositionPatient()[2]

        o = r.GetOutput()
        d = numpy_support.vtk_to_numpy(o.GetPointData().GetScalars())

        m_dcm[i] = d.reshape(y, x)

    m_dcm.flush()

    xs, ys, zs = o.GetSpacing()
    spacing = [xs, ys, zspacing / (len(dcm_files) - 1.0)]

    if spacing[2] < zs:
        spacing[2] = zs
    return m_dcm, spacing
Example #8
0
def polydata_from_numpy(coords, color):
    """
    :param coords:
    :param color:
    :return:
    """

    Npts, Ndim = np.shape(coords)

    Points = vtkPoints()
    ntype = get_numpy_array_type(Points.GetDataType())
    coords_vtk = numpy_to_vtk(np.asarray(coords, order='C',dtype=ntype), deep=1)
    Points.SetNumberOfPoints(Npts)
    Points.SetData(coords_vtk)

    Cells = vtkCellArray()
    ids = np.arange(0,Npts, dtype=np.int64).reshape(-1,1)
    IDS = np.concatenate([np.ones(Npts, dtype=np.int64).reshape(-1,1), ids],axis=1)
    ids_vtk = numpy_to_vtkIdTypeArray(IDS, deep=True)

    Cells.SetNumberOfCells(Npts)
    Cells.SetCells(Npts,ids_vtk)

    if color is None:
        [[128, 128, 128]]*len(coords)

    size = np.shape(color)
    if len(size)==1:
        color = [128]*len(coords)
        color = np.c_[color, color, color]

    color_vtk = numpy_to_vtk(
            np.ascontiguousarray(color, dtype=get_vtk_to_numpy_typemap()[VTK_UNSIGNED_CHAR]),
            deep=True
        )

    color_vtk.SetName("colors")

    PolyData = vtkPolyData()
    PolyData.SetPoints(Points)
    PolyData.SetVerts(Cells)
    PolyData.GetPointData().SetScalars(color_vtk)

    return PolyData
Example #9
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