C#将2D双数组转换为灰度图像 [英] C# convert a 2D double array to and greyscale image

查看:149
本文介绍了C#将2D双数组转换为灰度图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一次在这里使用C#。我正在阅读一些图像文件,做一些计算,输出和数组的double。我需要能够将这个双数组(或者这些,因为我将有多个数组)保存到灰度图像。我一直在互联网上四处寻找,我找不到多少。我已经在Python和Mathlab上完成了它,但C#似乎对我不友好。这是我到目前为止所做的(对于双图像创建)。

first time working with C# here. I am reading a few images files, do some calculations, and output and array of double. I need to be able to save this double array (or these, since I will have multiples arrays) to a greyscale image. I have been looking around on the internet, I couldn't find much. i have done it on Python and Mathlab, but C# doesn't seems to be as friendly to me. here is what I have done so far (for the double image creation).

        static Image MakeImage(double[,] data)
    {
        Image img = new Bitmap(data.GetUpperBound(1), data.GetUpperBound(0));
        //Bitmap bitmap = new Bitmap(data.GetUpperBound(1), data.GetUpperBound(0));
        for (int i = 0; i < data.GetUpperBound(1); i++)
        {
            for (int k = 0; k < data.GetUpperBound(0); k++)
            {
                //bitmap.SetPixel(k, i, Color.FromArgb((int)data[i, k],(int) data[i, k],(int) data[i, k]));
            }
        }

        return img;
    }
}

}

这段代码实际上并没有做太多。它创建我的空白图像模板。颜色不需要双倍输入。我不知道如何从数据创建图像......我被卡住=)

This code actually doesnt do much. It create my blank image template. color doesnt take double as input. I have no Idea how to create an image from data... I am stuck =)

提前谢谢。

推荐答案

如果您可以接受使用不安全的阻止,这非常快:

If you can accept using an unsafe block this is pretty fast:

    private Image CreateImage(double[,] data)
    {
        double min = data.Min();
        double max = data.Max();
        double range = max - min;
        byte v;

        Bitmap bm = new Bitmap(data.GetLength(0), data.GetLength(1));
        BitmapData bd = bm.LockBits(new Rectangle(0, 0, bm.Width, bm.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);

        // This is much faster than calling Bitmap.SetPixel() for each pixel.
        unsafe
        {
            byte* ptr = (byte*)bd.Scan0;
            for (int j = 0; j < bd.Height; j++)
            {
                for (int i = 0; i < bd.Width; i++)
                {
                    v = (byte)(255 * (data[i, bd.Height - 1 - j] - min) / range);
                    ptr[0] = v;
                    ptr[1] = v;
                    ptr[2] = v;
                    ptr[3] = (byte)255;
                    ptr += 4;
                }
                ptr += (bd.Stride - (bd.Width * 4));
            }
        }

        bm.UnlockBits(bd);
        return bm;

    }

这篇关于C#将2D双数组转换为灰度图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆