ITK  6.0.0
Insight Toolkit
SphinxExamples/src/Core/Mesh/AccessDataInCells/Code.py
1 #!/usr/bin/env python
2 
3 # ==========================================================================
4 #
5 # Copyright Insight Software Consortium
6 #
7 # Licensed under the Apache License, Version 2.0 (the "License")
8 # you may not use this file except in compliance with the License.
9 # You may obtain a copy of the License at
10 #
11 # https://www.apache.org/licenses/LICENSE-2.0.txt
12 #
13 # Unless required by applicable law or agreed to in writing, software
14 # distributed under the License is distributed on an "AS IS" BASIS,
15 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 # See the License for the specific language governing permissions and
17 # limitations under the License.
18 #
19 # ==========================================================================*/
20 
21 import sys
22 import itk
23 import numpy as np
24 
25 Dimension = 2
26 PixelType = itk.F # float or double
27 
28 MeshType = itk.Mesh[PixelType, Dimension]
29 PointType = itk.Point[itk.D, Dimension]
30 
31 mesh = MeshType.New()
32 
33 number_of_points = 10
34 for point_id in range(number_of_points):
35  point = [float(point_id), np.log(float(point_id) + np.finfo(float).eps)]
36  mesh.SetPoint(point_id, point)
37 
38 number_of_cells = number_of_points - 1
39 
40 # All cells are of type LINE so creating numpy of shape [number_of_cells x 2]
41 cells_array = np.zeros([number_of_cells, 2], dtype=np.uint64)
42 
43 for cell_id in range(number_of_cells):
44  cells_array[cell_id][0] = cell_id
45  cells_array[cell_id][1] = cell_id + 1
46 
47 cells_vector = itk.vector_container_from_array(cells_array.flatten())
48 
49 # When all cells are same use the second arguement to pass the cell type
50 mesh.SetCellsArray(cells_vector, itk.CommonEnums.CellGeometry_LINE_CELL)
51 
52 print("Points = ", mesh.GetNumberOfPoints())
53 print("Cells = ", mesh.GetNumberOfCells())
54 
55 # Assign data to cells
56 
57 # This can also be done by setting large array in one function call
58 # which would be more efficient than the following approach
59 for cell_id in range(number_of_cells):
60  mesh.SetCellData(cell_id, cell_id * cell_id)
61 
62 
63 # Retrieve data from cells
64 cell_data = mesh.GetCellData()
65 
66 # Obtain numpy array from the vector_container
67 cell_data_np = itk.array_from_vector_container(cell_data)
68 
69 for cell_id in range(number_of_cells):
70  # Demonstrating two ways of getting the element
71  # First using GetElement and second using the numpy array
72  if cell_id % 2 == 0:
73  print("Cell ", cell_id, " = ", cell_data.GetElement(cell_id))
74  else:
75  temp = cell_data_np[cell_id]
76  print("Cell ", cell_id, " = ", cell_data_np[cell_id])
itk::Mesh
Implements the N-dimensional mesh structure.
Definition: itkMesh.h:126
itk::Point
A templated class holding a geometric point in n-Dimensional space.
Definition: itkPoint.h:53