def makeVTKarray(nArr, aName, sc=1.): if sc == 1.: vArr = numpy_support.numpy_to_vtk(nArr.ravel(), deep=1) else: # deep copy needed in both cases. Seems the multiplication does not create space vArr = numpy_support.numpy_to_vtk(nArr.ravel() * sc, deep=1) vArr.SetName(aName) return vArr
def reredner_points(self, list_of_points): """ Updates label with which files has been loaded :param list_of_points: List of points xyz, xn3 :type list_of_points: ndarray """ temp_RGB = np.array([[0, 0, 0]]).reshape((1, 3)) temp_points = np.array([[0, 0, 0]]).reshape((1, 3)) # Creating temp array for colors rgb3 = vtk.vtkUnsignedCharArray() # Setting number of scalars, number of colo channels rgb3.SetNumberOfComponents(3) rgb3.SetName("Colors") # Creating array of RGB and points for points in list_of_points: # Setting color R = np.ones((points[0].shape[0], 1)) * points[1][0] G = np.ones((points[0].shape[0], 1)) * points[1][1] B = np.ones((points[0].shape[0], 1)) * points[1][2] temp_RGB = np.append(temp_RGB, np.concatenate((R, G, B), axis=1), axis=0) temp_points = np.append(temp_points, points[0], axis=0) # Removing null row temp_RGB = np.delete(temp_RGB, 0, 0) temp_points = np.delete(temp_points, 0, 0) # Converting to VTKArray and updating points+colors self.vtk_points_data.SetData(npsup.numpy_to_vtk(temp_points[:, 0:3])) self.vtk_points_topology = vtk.vtkCellArray() self.vtk_points_topology.InsertNextCell( temp_points.shape[0], list(range(0, temp_points.shape[0]))) self.vtk_vertex.SetVerts(self.vtk_points_topology) vtk_test = npsup.numpy_to_vtk(temp_RGB, deep=1) vtk_test.SetName("Colors") # Copying data to proper array type rgb3.ShallowCopy(vtk_test) # Adding colors to points self.vtk_vertex.GetPointData().SetScalars(rgb3) # Update interface # self.actor.RotateX(np.pi) # self.actor.RotateY(0) # self.actor.RotateZ(0) self.renderer.ResetCamera() self.render_window.Render()
def add_vtk_molecules(molecules: np.ndarray, module_name: str, vtk_grid: vtkStructuredPoints) -> vtkStructuredPoints: point_data = vtk_grid.GetPointData() # the x-ferrin molecules have a record type which has several names, others do not if molecules.dtype.names: for name in molecules.dtype.names: data = numpy_to_vtk(molecules[name].ravel()) data.SetName(name) # TODO: should we put the module name as part? point_data.AddArray(data) else: data = numpy_to_vtk(molecules.ravel()) data.SetName(module_name) point_data.AddArray(data) return vtk_grid
def cellContainsPoint(inputs, locations): array = vtkDoubleArray() array.SetNumberOfComponents(3) array.SetNumberOfTuples(len(locations)) for i in range(len(locations)): array.SetTuple(i, locations[i]) node = vtkSelectionNode() node.SetFieldType(vtkSelectionNode.CELL) node.SetContentType(vtkSelectionNode.LOCATIONS) node.SetSelectionList(array) selection = vtkSelection() selection.AddNode(node) from vtkmodules.vtkFiltersExtraction import vtkExtractSelectedLocations cellsNear = vtkExtractSelectedLocations() cellsNear.SetInputData(0, inputs[0].VTKObject) cellsNear.SetInputData(1, selection) cellsNear.Update() extractedCells = cellsNear.GetOutput() numCells = inputs[0].GetNumberOfCells() result = np.zeros((numCells,), dtype = np.int8) extracted = dsa.WrapDataObject(extractedCells) cellIds = extracted.CellData.GetArray('vtkOriginalCellIds') if isinstance(cellIds, dsa.VTKCompositeDataArray): for a in cellIds.GetArrays(): result[a] = 1 else: result[cellIds] = 1 import vtkmodules.util.numpy_support as np_s vtkarray = np_s.numpy_to_vtk(result, deep=True) return dsa.vtkDataArrayToVTKArray(vtkarray)
def Label2Contour2D(array, dim, origin, spacing): ''' Input: array: numpy array, label to convert dim: dimention of input label origin: origin of input label spacing: spacing of input label Output: Contour Description: convert 2D label to Contour ''' array = array.astype(np.int) vtk_data = numpy_to_vtk(array.ravel('F'), array_type=vtk.VTK_INT) image = vtk.vtkImageData() image.SetDimensions([dim[0], dim[1], 1]) image.SetSpacing([spacing[0], spacing[1], 0]) image.SetOrigin([origin[0], origin[1], 0]) image.GetPointData().SetScalars(vtk_data) filer = vtk.vtkMarchingSquares() filer.SetInputData(image) filer.SetValue(0, 255) filer.Update() poly = filer.GetOutput() contour = Contour() b = contour.Init_From_Vtk(poly) return contour
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 = 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 = vtkImageData() # image_copy.DeepCopy(image) return image
def writepolydata(filename, points, normals, cells): polydata = vtkPolyData() vtkpoints = vtkPoints() vtkpoints.SetData(numpy_to_vtk(points)) polydata.SetPoints(vtkpoints) polydata.GetPointData().SetNormals(numpy_to_vtk(normals)) triangles = vtkCellArray() for i, j, k in cells: triangles.InsertNextCell(3) triangles.InsertCellPoint(i) triangles.InsertCellPoint(j) triangles.InsertCellPoint(k) polydata.SetPolys(triangles) wr = vtkPolyDataWriter() wr.SetFileName(filename) wr.SetInputData(polydata) wr.Write()
def _set_colormap_range(self, actor, ctable, scalar_bar, rng=None, background_color=None): if rng is not None: mapper = actor.GetMapper() mapper.SetScalarRange(*rng) lut = mapper.GetLookupTable() lut.SetTable(numpy_to_vtk(ctable)) if scalar_bar is not None: lut = scalar_bar.GetLookupTable() if background_color is not None: background_color = np.array(background_color) * 255 ctable = _alpha_blend_background(ctable, background_color) lut.SetTable(numpy_to_vtk(ctable, array_type=VTK_UNSIGNED_CHAR)) lut.SetRange(*rng)
def create_vtk_molecules(grid: RectangularGrid, molecules: MoleculesState) -> vtkStructuredPoints: vtk_grid = create_vtk_volume(grid) point_data = vtk_grid.GetPointData() for name in molecules.grid.concentrations.dtype.names: data = numpy_to_vtk(molecules.grid.concentrations[name].ravel()) data.SetName(name) point_data.AddArray(data) return vtk_grid
def create_vtk_geometry(grid: RectangularGrid, geometry: GeometryState) -> vtkStructuredPoints: vtk_grid = create_vtk_volume(grid) point_data = vtk_grid.GetPointData() # transform color values to get around categorical interpolation issue in visualization tissue = geometry.lung_tissue.copy() # copy required as postprocessing can be live tissue[tissue == 0] = 4 point_data.SetScalars(numpy_to_vtk(tissue.ravel())) return vtk_grid
def update_field(self, field: Field, patch: Patch, data: Array2D): target = self.grid.GetCellData( ) if field.cells else self.grid.GetPointData() data = ensure_ncomps(self.nan_filter(data), 3, allow_scalar=field.is_scalar) data = transpose(data, self.grid, cells=field.cells) array = numpy_to_vtk(data) array.SetName(field.name) target.AddArray(array)
def read_fields(node, topology, data): ''' Read fields form Ascent 'node' into VTK 'data' a vtkDataSet already created. ''' global _keep_around for fieldIt in node["fields"].children(): ghostField = False fieldName = fieldIt.name() if (fieldName == "ascent_ghosts"): ghostField = True field = fieldIt.node() if (field["topology"] != topology): continue values = field["values"] va = None if type(values) is np.ndarray: if (ghostField): # The values stored in ascent_ghosts match what VTK expects: # (0 real cell, 1 = vtkDataSetAttribute::DUPLICATEPOINT ghost # cell) values = values.astype(np.uint8) va = numpy_support.numpy_to_vtk(values) else: # structure of arrays components = [] for component in values: components.append(values[component.name()]) vn = np.stack(components, axis=1) _keep_around.append(vn) va = numpy_support.numpy_to_vtk(vn) if (ghostField): va.SetName("vtkGhostType") else: va.SetName(fieldName) if field["association"] == "element": data.GetCellData().AddArray(va) elif field["association"] == "vertex": data.GetPointData().AddArray(va) else: # null # skip higher order attributes for now continue
def numpy_to_vtp(position: np.array, array_dict: dict): vtk_position = numpy_support.numpy_to_vtk(position) points = vtk.vtkPoints() points.SetData(vtk_position) data_save = vtk.vtkPolyData() vertices = vtk.vtkPolyVertex() length = len(position) vertices.GetPointIds().SetNumberOfIds(length) for i in range(0, length): vertices.GetPointIds().SetId(i, i) vert_cell = vtk.vtkCellArray() vert_cell.InsertNextCell(vertices) data_save.SetVerts(vert_cell) data_save.SetPoints(points) pd = data_save.GetPointData() for k, v in array_dict.items(): vtk_array = numpy_support.numpy_to_vtk(v) vtk_array.SetName(k) pd.AddArray(vtk_array) return data_save
def convert_cells_to_vtk(cells: CellList) -> vtkPolyData: cell_data: CellData = cells.cell_data live_cells = cells.alive() cell_data = cell_data[live_cells] fields = dict(cell_data.dtype.fields) # type: ignore fields.pop('point') points = vtkPoints() poly = vtkPolyData() poly.SetPoints(points) if not len(cell_data): return poly # vtk uses coordinate ordering x, y, z while we use z, y, x. points.SetData(numpy_to_vtk(np.flip(cell_data['point'], axis=1))) point_data = poly.GetPointData() for field, (dtype, *_) in fields.items(): data = cell_data[field] # numpy_to_vtk doesn't handle bool for some reason if dtype == np.dtype('bool'): data = data.astype(np.dtype('uint8')) # noinspection PyBroadException try: scalar = numpy_to_vtk(data) except Exception: print(f'Unhandled data type in field {field}') continue scalar.SetName(field) point_data.AddArray(scalar) return poly
def _matrix_math_filter (narray, operation) : if operation not in ['Determinant', 'Inverse', 'Eigenvalue', 'Eigenvector'] : raise RuntimeError('Unknown quality measure ['+operation+']'+ ' Supported are [Determinant, Inverse, Eigenvalue, Eigenvector]') if narray.ndim != 3 : raise RuntimeError(operation+' only works for an array of matrices(3D array).'+ ' Input shape ' + str(narray.shape)) elif narray.shape[1] != narray.shape[2] : raise RuntimeError(operation+' requires an array of 2D square matrices.' + ' Input shape ' + str(narray.shape)) # numpy_to_vtk converts only contiguous arrays if not narray.flags.contiguous : narray = narray.copy() # Reshape is necessary because numpy_support.numpy_to_vtk only works with 2D or # less arrays. nrows = narray.shape[0] ncols = narray.shape[1] * narray.shape[2] narray = narray.reshape(nrows, ncols) ds = vtkImageData() ds.SetDimensions(nrows, 1, 1) varray = numpy_support.numpy_to_vtk(narray) varray.SetName('tensors') ds.GetPointData().SetTensors(varray) filter = vtkMatrixMathFilter() if operation == 'Determinant' : filter.SetOperationToDeterminant() elif operation == 'Inverse' : filter.SetOperationToInverse() elif operation == 'Eigenvalue' : filter.SetOperationToEigenvalue() elif operation == 'Eigenvector' : filter.SetOperationToEigenvector() filter.SetInputData(ds) filter.Update() varray = filter.GetOutput().GetPointData().GetArray(operation) ans = dsa.vtkDataArrayToVTKArray(varray) # The association information has been lost over the vtk filter # we must reconstruct it otherwise lower pipeline will be broken. ans.Association = narray.Association ans.DataSet = narray.DataSet return ans
def point_inside_cell(self, point, cell_idx, tolerance=1e-8): """Determines whether point is inside cell or not. Returns ------- inside : bool Notes ----- Result might be inconsistent due to the stochastic nature of the algorithm. Decreasing the tolerance might help. """ x = self.xyz[cell_idx[0], cell_idx[1], cell_idx[2]].copy() x[[2, 3]] = x[[3, 2]] x[[6, 7]] = x[[7, 6]] pts = [(0, 1, 2, 3), (4, 5, 6, 7), (0, 1, 5, 4), (1, 2, 6, 5), (2, 3, 7, 6), (3, 0, 4, 7)] cube = vtk.vtkPolyData() points = vtk.vtkPoints() points.SetDataTypeToDouble() polys = vtk.vtkCellArray() for i in range(8): points.InsertPoint(i, x[i]) for i in range(6): polys.InsertNextCell(mk_vtk_id_list(pts[i])) cube.SetPoints(points) cube.SetPolys(polys) points = np.array([point]) vtk_pts = vtk.vtkPoints() vtk_pts.SetDataTypeToDouble() vtk_pts.SetData(numpy_support.numpy_to_vtk(points, deep=1)) # Make the poly data poly_pts_vtp = vtk.vtkPolyData() poly_pts_vtp.SetPoints(vtk_pts) enclosed_points_filter = vtk.vtkSelectEnclosedPoints() enclosed_points_filter.SetTolerance(tolerance) enclosed_points_filter.SetSurfaceData(cube) enclosed_points_filter.SetInputData(poly_pts_vtp) enclosed_points_filter.Update() return enclosed_points_filter.IsInside(0)
def update_geometry(self, geometry: Field, patch: Patch, data: Array2D): super().update_geometry(geometry, patch, data) if not isinstance(patch.topology, StructuredTopology) and self.require_structured: raise TypeError( f"{self.writer_name} does not support unstructured grids") if isinstance(patch.topology, StructuredTopology) and self.allow_structured: if not isinstance(self.grid, vtkStructuredGrid): self.grid = vtkStructuredGrid() shape = patch.topology.shape while len(shape) < 3: shape = (*shape, 0) if not config.fix_orientation: shape = shape[::-1] self.grid.SetDimensions(*(s + 1 for s in shape)) elif not self.grid: self.grid = vtkUnstructuredGrid() data = ensure_ncomps(self.nan_filter(data), 3, allow_scalar=False) if config.fix_orientation: data = transpose(data, self.grid) points = vtkPoints() points.SetData(numpy_to_vtk(data)) self.grid.SetPoints(points) if isinstance(self.grid, vtkUnstructuredGrid): if patch.topology.celltype not in [Line(), Quad(), Hex()]: raise TypeError( f"Unexpected cell type found: needed line, quad or hex") cells = patch.topology.cells cells = np.hstack( [cells.shape[-1] * np.ones((len(cells), 1), dtype=int), cells]).ravel() cells = cells.astype('i8') cellarray = vtkCellArray() cellarray.SetCells(len(cells), numpy_to_vtkIdTypeArray(cells)) if patch.topology.celltype == Hex(): celltype = VTK_HEXAHEDRON elif patch.topology.celltype == Quad(): celltype = VTK_QUAD else: celltype = VTK_LINE self.grid.SetCells(celltype, cellarray)
def write_structured_points(cls, var: np.ndarray, filename: str, dx: float, dy: float, dz: float) -> None: vol = vtkStructuredPoints() # set dimensions X, Y, Z vol.SetDimensions(var.shape[2], var.shape[1], var.shape[0]) vol.SetOrigin(0, 0, 0) vol.SetSpacing(dx, dy, dz) scalars = numpy_to_vtk(num_array=var.ravel()) vol.GetPointData().SetScalars(scalars) writer = vtkStructuredPointsWriter() writer.SetFileName(filename) writer.SetInputData(vol) writer.Write()
def numpy_to_vts(data, nx, ny, nz, array_dict): assert data.shape[0] == nx * ny * nz vol = vtk.vtkStructuredPoints() vol.SetDimensions(nx, ny, nz) vol.SetOrigin(*list(data[:, :3].min(0))) sx, sy, sz = data[:, :3].max(0) - data[:, :3].min(0) sx /= nx - 1 sy /= ny - 1 sz /= nz - 1 vol.SetSpacing(sx, sy, sz) for k, v in array_dict.items(): vtk_array = numpy_support.numpy_to_vtk(v) vtk_array.SetName(k) vol.GetPointData().AddArray(vtk_array) return vol
def Get_vtkImageData(self): ''' Input: Output: image_data: vtkImageData Description: Convert to vtkImageData and return. ''' from vtkmodules.util.numpy_support import numpy_to_vtk vtk_data = numpy_to_vtk(self._data.ravel('F'), array_type=vtk.VTK_FLOAT) image_data = vtk.vtkImageData() image_data.SetDimensions(self._dim) image_data.SetSpacing(self._spacing) image_data.SetOrigin(self._origin) image_data.GetPointData().SetScalars(vtk_data) return image_data
def _set_volume_range(self, volume, ctable, alpha, scalar_bar, rng): color_tf = vtkColorTransferFunction() opacity_tf = vtkPiecewiseFunction() for loc, color in zip(np.linspace(*rng, num=len(ctable)), ctable): color_tf.AddRGBPoint(loc, *(color[:-1] / 255.)) opacity_tf.AddPoint(loc, color[-1] * alpha / 255.) color_tf.ClampingOn() opacity_tf.ClampingOn() prop = volume.GetProperty() prop.SetColor(color_tf) prop.SetScalarOpacity(opacity_tf) prop.ShadeOn() prop.SetInterpolationTypeToLinear() if scalar_bar is not None: lut = vtkLookupTable() lut.SetRange(*rng) lut.SetTable(numpy_to_vtk(ctable)) scalar_bar.SetLookupTable(lut)
def create_vtk_grid(self, use_only_active=True, scaling=True, **kwargs): """Creates pyvista unstructured grid object. Returns ------- grid : `pyvista.core.pointset.UnstructuredGrid` object """ _ = kwargs self._vtk_grid_params = {'use_only_active': use_only_active, 'cell_size': None, 'scaling': scaling} cells = self.xyz indexes = np.moveaxis(np.indices(self.dimens), 0, -1) if 'ACTNUM' in self and use_only_active: cells = cells[self.actnum] indexes = indexes[self.actnum] else: cells = cells.reshape((-1,) + cells.shape[3:]) indexes = indexes.reshape((-1,) + indexes.shape[3:]) self._cell_id_d = dict(enumerate(indexes)) cells[:, [2, 3]] = cells[:, [3, 2]] cells[:, [6, 7]] = cells[:, [7, 6]] n_cells = cells.shape[0] cells = cells.reshape(-1, cells.shape[-1], order='C') cells = numpy_support.numpy_to_vtk(cells, deep=True) points = vtk.vtkPoints() points.SetNumberOfPoints(8*n_cells) points.SetData(cells) cell_array = vtk.vtkCellArray() cell = vtk.vtkHexahedron() connectivity = np.insert(range(8 * n_cells), range(0, 8 * n_cells, 8), 8).astype(np.int64) cell_array.SetCells(n_cells, numpy_support.numpy_to_vtkIdTypeArray(connectivity, deep=True)) self._vtk_grid = vtk.vtkUnstructuredGrid() self._vtk_grid.SetPoints(points) self._vtk_grid.SetCells(cell.GetCellType(), cell_array)
def write_poly_data(cls, var, filename: str, attr_names: str) -> None: vol = vtkPolyData() verts = vtkPoints() # noinspection PyArgumentList lines = vtkCellArray() # Retained, but not used. 'Fungus' is current, not 'Afumigatus' # if isinstance(var, AfumigatusCellTreeList): # adjacency = var.adjacency # # for i, j in adjacency.keys(): # if i != j: # line = vtkLine() # line.GetPointIds().SetId(0, i) # line.GetPointIds().SetId(1, j) # lines.InsertNextCell(line) # # el if not isinstance(var, CellList): raise NotImplementedError( f'Only supported CellTree or CellList for POLY_DATA. \ Got {type(var)}' ) for index in var.alive(): cell = var[index] # noinspection PyArgumentList verts.InsertNextPoint(cell['point'][2], cell['point'][1], cell['point'][0]) alive_cells = np.take(var.cell_data, var.alive()) for attr_name in attr_names: cell_attr = alive_cells[attr_name] scalars = numpy_to_vtk(num_array=cell_attr) scalars.SetName(attr_name) vol.GetPointData().AddArray(scalars) vol.SetPoints(verts) vol.SetLines(lines) writer = vtkPolyDataWriter() writer.SetFileName(filename) writer.SetInputData(vol) writer.Write()
def convert_pixel_values_to_vtk_3d_array(self): """ Scale pixel_values based on W/L and convert it to a vtk 3D array """ three_dimension_np_array = np.array( self.patient_dict_container.additional_data["pixel_values"]) three_dimension_np_array = three_dimension_np_array.astype(np.int16) three_dimension_np_array = (three_dimension_np_array - (self.patient_dict_container.get("level"))) / \ self.patient_dict_container.get("window") * 255 three_dimension_np_array[three_dimension_np_array < 0] = 0 three_dimension_np_array[three_dimension_np_array > 255] = 255 three_dimension_np_array = three_dimension_np_array.astype(np.int8) self.depth_array = numpy_support.numpy_to_vtk( three_dimension_np_array.ravel(order="F"), deep=True, array_type=VTK_INT) self.shape = three_dimension_np_array.shape
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 = 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
def numpy_to_image(numpy_array): """Convert a numpy 2D or 3D array to a vtkImageData object. numpy_array 2D or 3D numpy array containing image data return vtkImageData with the numpy_array content """ try: import numpy except: paraview.print_error("Error: Cannot import numpy") shape = numpy_array.shape if len(shape) < 2: raise Exception('numpy array must have dimensionality of at least 2') h, w = shape[0], shape[1] c = 1 if len(shape) == 3: c = shape[2] # Reshape 2D image to 1D array suitable for conversion to a # vtkArray with numpy_support.numpy_to_vtk() linear_array = numpy.reshape(numpy_array, (w * h, c)) try: from vtkmodules.util import numpy_support except: paraview.print_error( "Error: Cannot import vtkmodules.util.numpy_support") vtk_array = numpy_support.numpy_to_vtk(linear_array) image = vtkImageData() image.SetDimensions(w, h, 1) image.AllocateScalars(vtk_array.GetDataType(), 4) image.GetPointData().GetScalars().DeepCopy(vtk_array) return image
def numpy_to_image(numpy_array): """Convert a numpy 2D or 3D array to a vtkImageData object. numpy_array 2D or 3D numpy array containing image data return vtkImageData with the numpy_array content """ try: import numpy except: paraview.print_error("Error: Cannot import numpy") shape = numpy_array.shape if len(shape) < 2: raise Exception('numpy array must have dimensionality of at least 2') h, w = shape[0], shape[1] c = 1 if len(shape) == 3: c = shape[2] # Reshape 2D image to 1D array suitable for conversion to a # vtkArray with numpy_support.numpy_to_vtk() linear_array = numpy.reshape(numpy_array, (w*h, c)) try: from vtkmodules.util import numpy_support except: paraview.print_error("Error: Cannot import vtkmodules.util.numpy_support") vtk_array = numpy_support.numpy_to_vtk(linear_array) image = vtkImageData() image.SetDimensions(w, h, 1) image.AllocateScalars(vtk_array.GetDataType(), 4) image.GetPointData().GetScalars().DeepCopy(vtk_array) return image
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 = vtkImageData() image.SetOrigin(0, 0, 0) image.SetSpacing(spacing) image.SetDimensions(dx, dy, dz) image.SetExtent(extent) # 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.Update() image.GetCellData().SetScalars(v_image) image.GetPointData().SetScalars(v_image) # image.Update() image_copy = vtkImageData() image_copy.DeepCopy(image) # image_copy.Update() return image_copy
def pointIsNear(locations, distance, inputs): array = vtkDoubleArray() array.SetNumberOfComponents(3) array.SetNumberOfTuples(len(locations)) for i in range(len(locations)): array.SetTuple(i, locations[i]) node = vtkSelectionNode() node.SetFieldType(vtkSelectionNode.POINT) node.SetContentType(vtkSelectionNode.LOCATIONS) node.GetProperties().Set(vtkSelectionNode.EPSILON(), distance) node.SetSelectionList(array) selection = vtkSelection() selection.AddNode(node) from vtkmodules.vtkFiltersExtraction import vtkExtractSelectedLocations pointsNear = vtkExtractSelectedLocations() pointsNear.SetInputData(0, inputs[0].VTKObject) pointsNear.SetInputData(1, selection) pointsNear.Update() extractedPoints = pointsNear.GetOutput() numPoints = inputs[0].GetNumberOfPoints() result = np.zeros((numPoints,), dtype = np.int8) extracted = dsa.WrapDataObject(extractedPoints) pointIds = extracted.PointData.GetArray('vtkOriginalPointIds') if isinstance(pointIds, dsa.VTKCompositeDataArray): for a in pointIds.GetArrays(): result[a] = 1 else: result[pointIds] = 1 import vtkmodules.util.numpy_support as np_s vtkarray = np_s.numpy_to_vtk(result, deep=True) return dsa.vtkDataArrayToVTKArray(vtkarray)
def _cell_derivatives (narray, dataset, attribute_type, filter): if not dataset : raise RuntimeError('Need a dataset to compute _cell_derivatives.') # Reshape n dimensional vector to n by 1 matrix if len(narray.shape) == 1 : narray = narray.reshape((narray.shape[0], 1)) ncomp = narray.shape[1] if attribute_type == 'scalars' and ncomp != 1 : raise RuntimeError('This function expects scalars. ' + 'Input shape ' + str(narray.shape)) if attribute_type == 'vectors' and ncomp != 3 : raise RuntimeError('This function expects vectors. ' + 'Input shape ' + str(narray.shape)) # numpy_to_vtk converts only contiguous arrays if not narray.flags.contiguous : narray = narray.copy() varray = numpy_support.numpy_to_vtk(narray) if attribute_type == 'scalars': varray.SetName('scalars') else : varray.SetName('vectors') # create a dataset with only our array but the same geometry/topology ds = dataset.NewInstance() ds.UnRegister(None) ds.CopyStructure(dataset.VTKObject) if dsa.ArrayAssociation.FIELD == narray.Association : raise RuntimeError('Unknown data association. Data should be associated with points or cells.') if dsa.ArrayAssociation.POINT == narray.Association : # Work on point data if narray.shape[0] != dataset.GetNumberOfPoints() : raise RuntimeError('The number of points does not match the number of tuples in the array') if attribute_type == 'scalars': ds.GetPointData().SetScalars(varray) else : ds.GetPointData().SetVectors(varray) elif dsa.ArrayAssociation.CELL == narray.Association : # Work on cell data if narray.shape[0] != dataset.GetNumberOfCells() : raise RuntimeError('The number of does not match the number of tuples in the array') # Since vtkCellDerivatives only works with point data, we need to convert # the cell data to point data first. ds2 = dataset.NewInstance() ds2.UnRegister(None) ds2.CopyStructure(dataset.VTKObject) if attribute_type == 'scalars' : ds2.GetCellData().SetScalars(varray) else : ds2.GetCellData().SetVectors(varray) c2p = vtkCellDataToPointData() c2p.SetInputData(ds2) c2p.Update() # Set the output to the ds dataset if attribute_type == 'scalars': ds.GetPointData().SetScalars(c2p.GetOutput().GetPointData().GetScalars()) else: ds.GetPointData().SetVectors(c2p.GetOutput().GetPointData().GetVectors()) filter.SetInputData(ds) if dsa.ArrayAssociation.POINT == narray.Association : # Since the data is associated with cell and the query is on points # we have to convert to point data before returning c2p = vtkCellDataToPointData() c2p.SetInputConnection(filter.GetOutputPort()) c2p.Update() return c2p.GetOutput().GetPointData() elif dsa.ArrayAssociation.CELL == narray.Association : filter.Update() return filter.GetOutput().GetCellData() else : # We shall never reach here raise RuntimeError('Unknown data association. Data should be associated with points or cells.')
pyplot.axis('off') pyplot.savefig('E:\\Dicom\\test\\images\\'+'CoronalSlice'+'.jpg',bbox_inches='tight',pad_inches=0.0) pyplot.show() pyplot.figure(dpi=300) pyplot.axes().set_aspect('equal') pyplot.set_cmap(pyplot.gray()) pyplot.pcolormesh(x, z, numpy.fliplr(numpy.rot90((ArrayDicom[:, image_2, :]),3))) pyplot.axis('off') pyplot.savefig('E:\\Dicom\\test\\images\\'+'SagitalSlice'+'.jpg',bbox_inches='tight',pad_inches=0.0) pyplot.show() ''' Array_vtk = numpy_support.numpy_to_vtk(ArrayDicom.ravel('F'), deep=True, array_type=vtk.VTK_FLOAT) imagedata = vtk.vtkImageData() imagedata.SetOrigin(ConstOrigin) imagedata.SetSpacing(ConstPixelSpacing) imagedata.SetDimensions(ConstPixelDims) imagedata.GetPointData().SetScalars(Array_vtk) origin = numpy.array(ConstOrigin) ConstPixelSpacing = numpy.array(ConstPixelSpacing) ConstPixelDims = numpy.array(ConstPixelDims) center = origin + (ConstPixelSpacing * ConstPixelDims / 2) DirectionCosines_x = (0, 0, 1, 0, 1, 0, -1, 0, 0) DirectionCosines_y = (1, 0, 0, 0, 0, -1, 0, 1, 0) DirectionCosines_z = (1, 0, 0, 0, 1, 0, 0, 0, 1)
def plot(points, triangles, rgb_add, surface_type): # Load Data # Load points # points = np.genfromtxt('vertices.csv', delimiter=',', skip_header=1) # (X,Y,Z,R,G,B) # triangles = np.genfromtxt('triangles.csv', delimiter=',', dtype=int) # (Point 1, Point 2, Point 3) # points = np.genfromtxt('data2.xyz') # triangles = np.genfromtxt('triangles_data2.xyz',dtype=int) # rgb_add = np.ones(points.shape,dtype=int)*200 points = np.hstack((points, rgb_add)) # Create Point object vtk_points_data = vtk.vtkPoints() # Create color scalars rgb = vtk.vtkUnsignedCharArray() # Setting number of scalars, number of colo channels rgb.SetNumberOfComponents(3) # Setting name of scalars set rgb.SetName("Colors") # Creating id objects for PolyData vtk_points_topology = vtk.vtkCellArray() vtk_triangles_topology = vtk.vtkCellArray() # Setting up PolyData - Vertices points_list_ids = [] for point_from_list in points: # points_list_ids.append(vtk_points_data.InsertNextPoint(point_from_list[0],point_from_list[1],point_from_list[2])) rgb.InsertNextTuple3(point_from_list[3], point_from_list[4], point_from_list[5]) # rgb.InsertNextTuple3(point_from_list[3],point_from_list[4],point_from_list[5]) vtk_points_data.SetData(npsup.numpy_to_vtk(points[:, 0:3])) vtk_points_topology.InsertNextCell(points.shape[0], list(range(0, len(points)))) # Initializing PolyData (vertices and triangles) vtk_vertex = vtk.vtkPolyData() vtk_triangle = vtk.vtkPolyData() # Set the vertices we created as the geometry and topology of the polydata vtk_vertex.SetPoints(vtk_points_data) vtk_vertex.SetVerts(vtk_points_topology) # Setting triangles vtk_triangle.SetPoints(vtk_points_data) # Adding color # print(rgb.GetArrayType()) vtk_triangle.GetPointData().SetScalars(rgb) vtk_vertex.GetPointData().SetScalars(rgb) # Setting up PolyData - Triangles for triangle_from_list in triangles: temp_triangle = vtk.vtkTriangle() temp_triangle.GetPointIds().SetId(0, triangle_from_list[0]) temp_triangle.GetPointIds().SetId(1, triangle_from_list[1]) temp_triangle.GetPointIds().SetId(2, triangle_from_list[2]) vtk_triangles_topology.InsertNextCell(temp_triangle) # Create Mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(vtk_vertex) vtk_triangle.SetPolys(vtk_triangles_topology) mapper.SetInputData(vtk_triangle) # Create and connect Actor actor = vtk.vtkActor() actor.SetMapper(mapper) # Passing the mapped source to actor actor.GetProperty().SetColor(1.0, 0.0, 0.0) # Setting color of the source if surface_type == 0: actor.GetProperty().SetRepresentationToSurface() elif surface_type == 1: actor.GetProperty().SetRepresentationToWireframe() else: actor.GetProperty().SetRepresentationToPoints() # actor.GetProperty().LightingOff() # Create renderer and passing mapped and acted source to it renderer = vtk.vtkRenderer() renderer.SetBackground(0.0, 0.0, 0.0) renderer.AddActor(actor) renderer.ResetCamera() # Create renderer window and passing the render render_window = vtk.vtkRenderWindow() render_window.SetWindowName('Scene') render_window.SetSize(400, 400) render_window.AddRenderer(renderer) # Create interactor and pass the render window interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(render_window) # Initialize the interactor and start the rendering interactor.Initialize() render_window.Render() interactor.Start()
def execute(self): inputDO = self.GetInputDataObject(0, 0) inputSEL = self.GetInputDataObject(1, 0) outputDO = self.GetOutputDataObject(0) assert inputSEL.GetNumberOfNodes() >= 1 selectionNode = inputSEL.GetNode(0) field_type = selectionNode.GetFieldType() if field_type == selectionNode.CELL: attributeType = vtkDataObject.CELL elif field_type == selectionNode.POINT: attributeType = vtkDataObject.POINT elif field_type == selectionNode.ROW: attributeType = vtkDataObject.ROW else: raise RuntimeError ("Unsupported field attributeType %r" % field_type) # evaluate expression on the inputDO. # this is equivalent to executing the Python Calculator on the input dataset # to produce a mask array. inputs = [] inputs.append(dsa.WrapDataObject(inputDO)) query = selectionNode.GetQueryString() # get a dictionary for arrays in the dataset attributes. We pass that # as the variables in the eval namespace for calculator.compute(). elocals = calculator.get_arrays(inputs[0].GetAttributes(attributeType)) if ("id" not in elocals) and re.search(r'\bid\b', query): # add "id" array if the query string refers to id. # This is a temporary fix. We should look into # accelerating id-based selections in the future. elocals["id"] = _create_id_array(inputs[0], attributeType) try: maskArray = calculator.compute(inputs, query, ns=elocals) except: from sys import stderr print ("Error: Failed to evaluate Expression '%s'. "\ "The following exception stack should provide additional developer "\ "specific information. This typically implies a malformed "\ "expression. Verify that the expression is valid.\n" % query, file=stderr) raise if not maskarray_is_valid(maskArray): raise RuntimeError( "Expression '%s' did not produce a valid mask array. The value "\ "produced is of the type '%s'. This typically implies a malformed "\ "expression. Verify that the expression is valid." % \ (query, type(maskArray))) # if inverse selection is requested, just logical_not the mask array. if selectionNode.GetProperties().Has(selectionNode.INVERSE()) and \ selectionNode.GetProperties().Get(selectionNode.INVERSE()) == 1: maskArray = algos.logical_not(maskArray) output = dsa.WrapDataObject(outputDO) if self.GetPreserveTopology(): # when preserving topology, just add the mask array as # vtkSignedCharArray to the output. vtkPythonExtractSelection should # have already ensured that the input is shallow copied over properly # before this method gets called. # Note: we must force the data type to VTK_SIGNED_CHAR or the array will # be ignored by the freeze selection operation from vtkmodules.util.numpy_support import numpy_to_vtk if type(maskArray) is not dsa.VTKNoneArray: insidedness = numpy_to_vtk(maskArray, deep=1, array_type=vtkConstants.VTK_SIGNED_CHAR) insidedness.SetName("vtkInsidedness") output.GetAttributes(attributeType).VTKObject.AddArray(insidedness) else: # handle extraction. # flatnonzero() will give is array of indices where the arrays is # non-zero (or non-False in our case). We then pass that to # vtkPythonExtractSelection to extract the selected ids. nonzero_indices = algos.flatnonzero(maskArray) output.FieldData.append(nonzero_indices, "vtkSelectedIds"); #print (output.FieldData["vtkSelectedIds"]) self.ExtractElements(attributeType, inputDO, outputDO) del nonzero_indices del maskArray
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 = 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 = vtkImageData() image_copy.DeepCopy(image) return image_copy
def ascent_to_vtk(node, topology=None, extent=None): ''' Read from Ascent node ("topologies/" + topology) into VTK data. topology is one of the names returned by topology_names(node) or topology_names(node)[0] if the parameter is None ''' global _keep_around # we use the same Python interpreter between time steps _keep_around = [] if topology is None: topology = topology_names(node)[0] data = None coords = node["topologies/" + topology + "/coordset"] if (node["topologies/" + topology + "/type"] == "uniform"): # tested with noise data = vtkImageData() origin = np.array([ float(o) for o in [ node["coordsets/" + coords + "/origin/x"], node["coordsets/" + coords + "/origin/y"], node["coordsets/" + coords + "/origin/z"] ] ]) spacing = np.array([ float(s) for s in [ node["coordsets/" + coords + "/spacing/dx"], node["coordsets/" + coords + "/spacing/dy"], node["coordsets/" + coords + "/spacing/dz"] ] ]) if extent is None: data.SetDimensions(node["coordsets/" + coords + "/dims/i"], node["coordsets/" + coords + "/dims/j"], node["coordsets/" + coords + "/dims/k"]) data.SetOrigin(origin) else: data.SetExtent(extent) origin = origin - np.array([extent[0], extent[2], extent[4] ]) * spacing data.SetOrigin(origin) data.SetSpacing(spacing) elif (node["topologies/" + topology + "/type"] == "rectilinear"): # tested on cloverleaf3d and kripke data = vtkRectilinearGrid() xn = node["coordsets/" + coords + "/values/x"] xa = numpy_support.numpy_to_vtk(xn) data.SetXCoordinates(xa) yn = node["coordsets/" + coords + "/values/y"] ya = numpy_support.numpy_to_vtk(yn) data.SetYCoordinates(ya) zn = node["coordsets/" + coords + "/values/z"] za = numpy_support.numpy_to_vtk(zn) data.SetZCoordinates(za) if (extent is None): data.SetDimensions(xa.GetNumberOfTuples(), ya.GetNumberOfTuples(), za.GetNumberOfTuples()) else: data.SetExtent(extent) elif (node["coordsets/" + coords + "/type"] == "explicit"): xn = node["coordsets/" + coords + "/values/x"] yn = node["coordsets/" + coords + "/values/y"] zn = node["coordsets/" + coords + "/values/z"] xyzn = np.stack((xn, yn, zn), axis=1) _keep_around.append(xyzn) xyza = numpy_support.numpy_to_vtk(xyzn) points = vtkPoints() points.SetData(xyza) if (node["topologies/" + topology + "/type"] == "structured"): # tested on lulesh data = vtkStructuredGrid() data.SetPoints(points) # elements are one less than points nx = node["topologies/" + topology + "/elements/dims/i"] + 1 ny = node["topologies/" + topology + "/elements/dims/j"] + 1 nz = node["topologies/" + topology + "/elements/dims/k"] + 1 data.SetDimensions(nx, ny, nz) elif (node["topologies/" + topology + "/type"] == "unstructured"): # tested with laghos data = vtkUnstructuredGrid() data.SetPoints(points) shape = node["topologies/" + topology + "/elements/shape"] c = node["topologies/" + topology + "/elements/connectivity"] # vtkIdType is int64 c = c.astype(np.int64) if (shape == "hex"): npoints = 8 cellType = vtkConstants.VTK_HEXAHEDRON elif (shape == "quad"): npoints = 4 cellType = vtkConstants.VTK_QUAD else: print("Error: Shape not implemented") return None c = c.reshape(c.shape[0] / npoints, npoints) # insert the number of points before point references c = np.insert(c, 0, npoints, axis=1) ncells = c.shape[0] c = c.flatten() _keep_around.append(c) ita = numpy_support.numpy_to_vtkIdTypeArray(c) cells = vtkCellArray() cells.SetCells(ncells, ita) data.SetCells((cellType), cells) read_fields(node, topology, data) return data