我目前正在使用SimpleITK
库来操作3d图像。我已经能够阅读我的.mhd
元图像并执行阈值处理,运动,扩张等。输入图像是3D图像(或堆叠的2D图像),每个像素有一个分量。
现在我转向使用get buffer方法进行手动像素操作。我知道Simple ITK doxygen和例子https://itk.org/SimpleITKDoxygen/html/ImageGetBuffer_8cs-example.html
我做到了但却无法看到我操作的图像 - 输出图像与我的输入图像显示相同(我检查了我的像素循环及其工作情况,所以看起来我的缓冲区没有使用不安全的指针操作或我错误地导入缓冲区)。这是我的代码
非常感谢帮助和指导!!感谢
itk.simple.Image input = new itk.simple.Image();
string filepath = "C:\\Users\\pragun\\Desktop\\Selected Data\\stack.mhd";
ImageFileReader readerx = new ImageFileReader();
readerx.SetFileName(filepath);
input = readerx.Execute();
input = SimpleITK.Cast(input, PixelIDValueEnum.sitkUInt8);
// calculate the nubmer of pixels
VectorUInt32 size = input.GetSize();
VectorDouble spacing = input.GetSpacing();
Console.WriteLine(size[0]);
Console.WriteLine(size[1]);
Console.WriteLine(size[2]);
IntPtr buffer = new IntPtr(0);
buffer = input.GetBufferAsUInt8();
// There are two ways to access the buffer:
// (1) Access the underlying buffer as a pointer in an "unsafe" block
// (note that in C# "unsafe" simply means that the compiler can not
// perform full type checking), and requires the -unsafe compiler flag
unsafe
{
byte* bufferPtr = (byte*)buffer.ToPointer();
// Now the byte pointer can be accessed as per Brad's email
// (of course this example is only a 2d single channel image):
// This is a 1-D array but can be access as a 3-D. Given an
// image of size [xS,yS,zS], you can access the image at
// index [x,y,z] as you wish by image[x+y*xS+z*xS*yS],
// so x is the fastest axis and z is the slowest.
for (int k = 0; k < size[2]; k++)
{
for (int j = 0; j < size[1]; j++)
{
for (int i = 0; i < size[0]; i++)
{
byte pixel = bufferPtr[i + j * size[1] + k * size[2]*size[1] ] ;
pixel = 255; // example -> it should turn the images to all white
}
}
}
}
itk.simple.ImportImageFilter importer = new ImportImageFilter();
importer.SetSize(size);
importer.SetSpacing(spacing);
importer.SetBufferAsUInt8(buffer);
importer.SetOutputPixelType(PixelIDValueEnum.sitkUInt8);
itk.simple.Image output = importer.Execute();
SimpleITK.Show(output);
答案 0 :(得分:2)
尝试:
bufferPtr[i + j * size[1] + k * size[2]*size[1] ] = 255
在内部循环的第一行中,您已将数组的值分配给pixel
变量,而不是元素。在第二行中,您为变量分配了一个新值。