SimpleITK - 操作缓冲区图像的像素

SimpleITK - Manipulating pixel of the buffer image

我目前正在使用 SimpleITK 库来处理 3d 图像。我已经能够读取我的 .mhd 元图像并执行阈值处理、腐蚀、膨胀等。输入图像是 3D 图像(或堆叠的 2D 图像),每个像素一个分量。

现在我转向使用获取缓冲区方法进行手动像素操作。我知道 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);

尝试:

bufferPtr[i + j * size[1] + k * size[2]*size[1] ] = 255

在内部循环的第一行中,您已将数组的 分配给 pixel 变量,而不是元素。在第二行中,您为变量分配了一个新值。