将Simpleitk图像转换为位图。System.ArgumentException。

3
我希望使用simpleitk读取dicom图片,将其转换为位图,然后在pictureBox中显示结果。但是当我尝试这样做时,会抛出ArgumentException异常。我该如何解决?
以下是我的代码:
OpenFileDialog dialog = new OpenFileDialog();
dialog.Title = "Open";
dialog.Filter = "DICOM Files (*.dcm;*.dic)|*.dcm;*.dic|All Files (*.*)|*.*";
dialog.ShowDialog();
if (dialog.FileName != "")
{
    using (sitk.ImageFileReader reader = new sitk.ImageFileReader())
    {
        reader.SetFileName(dialog.FileName);                   
        reader.SetOutputPixelType(sitk.PixelIDValueEnum.sitkFloat32);
        sitk.Image image = reader.Execute();

        var castedImage = sitk.SimpleITK.Cast(image, 
            sitk.PixelIDValueEnum.sitkFloat32);
        var size = castedImage.GetSize();
        int length = size.Aggregate(1, (current, i) => current * (int)i);
        IntPtr buffer = castedImage.GetBufferAsFloat();

        // Declare an array to hold the bytes of the bitmap.                    
        byte[] rgbValues = new byte[length];

        // Copy the RGB values into the array.
        Marshal.Copy(buffer, rgbValues, 0, length);

        Stream stream = new MemoryStream(rgbValues);

        Bitmap newBitmap = new Bitmap(stream);

        //I have tried in this way, but it generated ArgumentException too
        //Bitmap newBitmap = new Bitmap((int)image.GetWidth(), (int)image.GetHeight(), (int)image.GetDepth(), PixelFormat.Format8bppIndexed, buffer);

        Obraz.pic.Image = newBitmap;
    }
}

你应该像这样检查你的 OpenFileDialog: if (dialog.ShowDialog() == DialogResult.OK){ } 另外,错误出现在哪一行?你使用了调试器吗?你是否搜索过关于任何位图转换函数的信息等? - MethodMan
谢谢你的回答。你说得对,我应该像你说的那样检查我的 OpenFileDialog。错误出现在这一行:New Bitmap bitmap = new Bitmap (stream); 我搜索了如何从流或缓冲区创建位图,以及如何将 SimpleITK.Image 转换为 Image 或 Bitmap。 - PAPP
你检查过以下异常条件了吗:流不包含图像数据或为空。
  • 或 - 流包含一个PNG图像文件,其中单个维度大于65,535像素?
- Jacob Seleznev
1
尝试这个例子 ImageGetBuffer.cs。请注意使用 float[] 而不是 byte[] - Jacob Seleznev
1个回答

1
感谢您的评论和帮助尝试。经过咨询和自己在互联网上的搜索,我解决了这个问题。第一个问题是像素图像的不充分表示。我必须将Float32更改为UInt8,以为像素提供八位。
var castedImage = sitk.SimpleITK.Cast(image2, sitk.PixelIDValueEnum.sitkUInt8);

那么我会使用在问题中被注释掉的构造函数创建一个位图,但是使用(int)image.GetWidth()代替(int)image.GetDepth()。

Bitmap newBitmap = new Bitmap((int)image.GetWidth(), (int)image.GetHeight(), (int)image.GetWidth(), PixelFormat.Format8bppIndexed, buffer);

很不幸,出现了一个新问题。原本应该是灰度的图像显示出奇怪的颜色。但我在这里找到了解决方案。
ColorPalette pal = newBitmap.Palette;
                for (int i = 0; i <= 255; i++)
                {
                    // create greyscale color table
                    pal.Entries[i] = Color.FromArgb(i, i, i);
                }
                newBitmap.Palette = pal; // you need to re-set this property to force the new ColorPalette

你是如何导入 Simpleitk 库的?当我尝试使用 regsvr32 导入 DLLs 时,出现了这样的错误:SimpleITKCSharpNative.dll 被加载,但未找到入口点 DllRegisterServer - talha06

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接