c# - 将 Simpleitk 图像转换为位图。系统参数异常

标签 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;
    }
}

最佳答案

感谢您的评论和尝试提供帮助。经过咨询和我自己在互联网上的搜索,我解决了这个问题。第一个问题是像素图像的表示不充分。我不得不将 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);

不幸的是,新的问题出现了。本应为灰度的图像显示为奇怪的颜色。但我找到了解决方案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

关于c# - 将 Simpleitk 图像转换为位图。系统参数异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34622970/

相关文章:

c# - 在 C# 中使用 native HBitmap,同时保留 alpha channel /透明度

c# - 使用 EPPlus 在 GDI+ Drawings.AddPicture 中发生一般性错误

c# - 如何在 C# 中使用 system.drawing 将居中文本绘制到 jpg 上

c# - 使用 C#,如何像 TinEye.com 在 Web 上那样在 Windows 文件系统中搜索图像?

C# listView 闪烁/替代颜色

c# - ASP.NET Core 表单 POST 导致 HTTP 415 Unsupported Media Type 响应

javascript - 从客户端的 java 脚本保存 base64 字符串(位图数据)

c# - 从字符串创建开放构造类型

c# - Linq - 在列表中按周分组

c - 位图文件没有以正确的顺序保存在内存中