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

时间:2016-01-05 23:14:13

标签: c# bitmap system.drawing itk

我想使用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;
    }
}

1 个答案:

答案 0 :(得分:1)

感谢您的意见和尝试提供帮助。经过咨询和我自己在互联网上搜索,我解决了这个问题。第一个问题是像素图像的表示不充分。我不得不将Float32更改为UInt8以提供8位像素。

var castedImage = sitk.SimpleITK.Cast(image2, sitk.PixelIDValueEnum.sitkUInt8);

然后我已经使用被注释掉的构造函数创建了一个Bitmap,但使用(int)image.GetWidth()而不是(int)image.GetDepth()。

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

不幸的是,出现了一个新问题。应该是灰度级的图像以奇怪的颜色显示。但我找到了解决方案here

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