折线只包含0维和1维的单元格,它们由itk::VertexCell和itk::LineCell表示。
#include "itkMesh.h"
#include "itkVertexCell.h"
#include "itkLineCell.h"
然后定义PixelType并实例化网格类型。注意这个空间的维数是2。
typedef float PixelType;
typedef itk::Mesh< PixelType, 2 > MeshType;
现在可以使用从网格中获取的特征实例化单元格类型。
typedef MeshType::CellType CellType;
typedef itk::VertexCell< CellType > VertexType;
typedef itk::LineCell< CellType > LineType;
在这个例子中,我们创建了一条折线,通过使用正方形的三个边连接正方形的四个顶点:
MeshType::Pointer mesh = MeshType::New();
MeshType::PointType point0;
MeshType::PointType point1;
MeshType::PointType point2;
MeshType::PointType point3;
point0[0] = -1; point0[1] = -1;
point1[0] = 1; point1[1] = -1;
point2[0] = 1; point2[1] = 1;
point3[0] = -1; point3[1] = 1;
mesh->SetPoint( 0, point0 );
mesh->SetPoint( 1, point1 );
mesh->SetPoint( 2, point2 );
mesh->SetPoint( 3, point3 );
现在我们继续创建单元格,将它们与点关联起来,并将它们插入网格中:
CellType::CellAutoPointer cellpointer;
cellpointer.TakeOwnership( new LineType );
cellpointer->SetPointId( 0, 0 );
cellpointer->SetPointId( 1, 1 );
mesh->SetCell( 0, cellpointer );
cellpointer.TakeOwnership( new LineType ); cellpointer->SetPointId( 0, 1 );
cellpointer->SetPointId( 1, 2 );
mesh->SetCell( 1, cellpointer );
cellpointer.TakeOwnership( new LineType );
cellpointer->SetPointId( 0, 2 );
cellpointer->SetPointId( 1, 0 );
mesh->SetCell( 2, cellpointer );
最后,用itk::VertexCell表示的零维单元格被创建并插入到网格中:
cellpointer.TakeOwnership( new VertexType );
cellpointer->SetPointId( 0, 0 );
mesh->SetCell( 3, cellpointer );
cellpointer.TakeOwnership( new VertexType );
cellpointer->SetPointId( 0, 1 );
mesh->SetCell( 4, cellpointer );
cellpointer.TakeOwnership( new VertexType );
cellpointer->SetPointId( 0, 2 );
mesh->SetCell( 5, cellpointer );
cellpointer.TakeOwnership( new VertexType );
cellpointer->SetPointId( 0, 3 );
mesh->SetCell( 6, cellpointer );
此时网格包含四个点和三个单元格。
- 可以使用PointContainer迭代器访问这些点:
typedef MeshType::PointsContainer::ConstIterator PointIterator;
PointIterator pointIterator = mesh->GetPoints()->Begin();
PointIterator pointEnd = mesh->GetPoints()->End();
while( pointIterator != pointEnd )
{
std::cout << pointIterator.Value() << std::endl;
++pointIterator;
}
- 可以使用CellsContainer迭代器访问单元格
typedef MeshType::CellsContainer::ConstIterator CellIterator;
CellIterator cellIterator = mesh->GetCells()->Begin();
CellIterator cellEnd = mesh->GetCells()->End();
while( cellIterator != cellEnd )
{
CellType * cell = cellIterator.Value();
std::cout << cell->GetNumberOfPoints() << std::endl;
++cellIterator;
}
请注意,单元格存储为指向泛型单元格类型的指针,泛型单元格类型是所有特定单元格类的基类。这意味着在这个级别上我们只能访问CellType中定义的虚拟方法。
可以使用CellType特征中定义的迭代器访问与单元格关联的点标识符。下面的代码演示了PointIdIterator的使用。PointIdsBegin()方法将迭代器返回到单元格中的第一个点标识符。PointIdsEnd()方法将迭代器返回到单元格中的过期结束点标识符。
typedef CellType::PointIdIterator PointIdIterator;
PointIdIterator pointIditer = cell->PointIdsBegin();
PointIdIterator pointIdend = cell->PointIdsEnd();
while( pointIditer != pointIdend )
{
std::cout << *pointIditer << std::endl; ++pointIditer;
}
注意,点标识符是使用更传统的*iterator符号从迭代器获得的,而不是单元迭代器使用的Value()符号。