1.概述
本节阐述SetPixel( )
和GetPixel( )
方法的用法。这两个方法可以直接访问图像中包含的像素数据。考虑到这两种方法相对缓慢,在高性能的访问需求中不宜使用。图像迭代器是有效访问图像像素数据的合适机制。
图像中每个像素的位置是由一个唯一的index来识别。一个index 是一个整数数组,它定义了像素在图像中位置的坐标值。IndexType
可以由图像自动定义并可以被像itk::Index
这样的操作访问。数组的长度必须与对应图像的维数相匹配。
下面的代码是对一个index 变量的声明并对其数组元素赋值。请注意index 并不是用智能指针进行访问的,这是因为index 是一个轻量级对象,它并不用于在对象间共享。生成这些小对象的多个拷贝比使用智能指针机制分享它们更加有效。
下面的代码声明了一个IndexType
实例,并初始化以便与在图像中的像素位置相关联。
const ImageType::IndexType pixelIndex = {{27,29,37}};//{X,Y,Z}位置
用index定义了像素位置后,就可以访问图像中像素的内容。GetPixel( )
方法允许我们得到像素值。
ImageType::PixelType pixelValue = image->GetPixel( pixelIndex );
SetPixel( )
方法允许我们设定像素值。
image->SetPixel( pixelIndex, pixelValue+22 );
请注意GetPixel( )
使用拷贝而不是引用来返回像素值,所以该方法不能用来更改图像数据值。
记住SetPixel( )
和GetPixel( )
这两种方法都是低效率的,只能用来调试或支持交互,例如点击鼠标查询像素值。
2.代码展示
#include "itkImage.h"
//这个例子阐述了 SetPixel( )和 GetPixel( )方法的用法
//可以直接访问图像中包含的像素数据
int main(int, char *[])
{
typedef itk::Image< unsigned short, 3 > ImageType;
ImageType::Pointer image = ImageType::New();
const ImageType::SizeType size = {{ 200, 200, 200}}; //Size along {X,Y,Z}
const ImageType::IndexType start = {{ 0, 0, 0 }}; // First index on {X,Y,Z}
ImageType::RegionType region;
region.SetSize( size );
region.SetIndex( start );
// Pixel data is allocated
image->SetRegions( region );
image->Allocate(true); // 内存分配
//对 index 类型实例的声明并进行初始化
const ImageType::IndexType pixelIndex = {{26,29,31}}; // Position of {X,Y,Z}
//GetPixel(pixelIndex)方法将可得到pixelIndex处的像素值pixelValue
ImageType::PixelType pixelValue = image->GetPixel( pixelIndex );
std::cout << "pixelIndex处的像素值:"<<pixelValue << std::endl;//输出pixelIndex索引处的像素值pixelValue
//SetPixel( )方法可设定像素值,将pixelIndex索引处的像素值赋值为pixelValue+22
image->SetPixel( pixelIndex, pixelValue+22 );
ImageType::PixelType pixelValue1 = image->GetPixel(pixelIndex);//获取更改后的像素值
std::cout << "更改后pixelIndex处的像素值:" << pixelValue1 << std::endl;//输出pixelIndex索引处的像素值
return EXIT_SUCCESS;
}
3.结果展示
参考目录
https://blog.csdn.net/qq_32809093/article/details/116885698