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

本文关键字:位图 System ArgumentException 转换 Simpleitk 图像 | 更新日期: 2023-09-27 18:29:09

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

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

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

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

然后,我已经使用有问题的构造函数创建了一个位图,但使用(int)image.GetWidth()而不是(int)images.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