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



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

现在我正在转向使用 get 缓冲区方法手动像素操作。我知道简单的ITK氧气和例子 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变量,而不是元素。在第二行中,您已为变量分配了一个新值。

最新更新