如何在.NET中将Bitmap转换为MWArray(Matlab数组)

时间:2016-06-29 02:46:24

标签: c# .net matlab

我在Matlab上写了一个算法。因此我想在.Net上使用它。我完美地将.m文件转换为.dll,以便在.Net上使用Matlab库编译器。首先,我尝试将Matlab函数转换为.dll而没有任何参数,并且在.Net上运行良好。但是,当我想在参数中使用该函数时,我会在下面收到一些错误。参数基本上是图像。我在Matlab上调用函数就像这样I = imread('xxx.jpg'); Detect(I);所以我的c#代码就像这样

    static void Main(string[] args)
    {
        DetectDots detectDots = null;
        Bitmap bitmap = new Bitmap("xxx.jpg");

        //Get image dimensions
        int width = bitmap.Width;
        int height = bitmap.Height;
        //Declare the double array of grayscale values to be read from "bitmap"
        double[,] bnew = new double[width, height];
        //Loop to read the data from the Bitmap image into the double array
        int i, j;
        for (i = 0; i < width; i++)
        {
            for (j = 0; j < height; j++)
            {
                Color pixelColor = bitmap.GetPixel(i, j);
                double b = pixelColor.GetBrightness(); //the Brightness component

                bnew.SetValue(b, i, j);
            }
        }

        MWNumericArray arr = bnew;
        try
        {
            detectDots = new DetectDots();

            detectDots.Detect(arr);
            Console.ReadLine();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

我使用了与xxx.jpg相同的图像,即5312 x 2988。 但我在下面收到这个错误。

... MWMCR::EvaluateFunction error ... 
Index exceeds matrix dimensions.
Error in => DetectDots.m at line 12.

... Matlab M-code Stack Trace ...
    at
file C:\Users\TAHAME~1\AppData\Local\Temp\tahameral\mcrCache9.0\MTM_220\MTM\DetectDots.m, name DetectDots, line 12.

重要的是,它说“索引超过矩阵维度”,是否真的将Bitmap转换为MWArray?有什么问题?

1 个答案:

答案 0 :(得分:0)

我意识到C#中的行对应于MWarray中的列。所以我改变了代码上的小东西。

而不是double[,] bnew = new double[width, height];我使用它double[,] bnew = new double[height, width];

而不是bnew.SetValue(b, i, j);我使用它bnew.SetValue(b, j, i);

有人可能会将关于Bitmap的整个代码用于下面的MWArray

        Bitmap bitmap = new Bitmap("001-2.bmp");

        //Get image dimensions
        int width = bitmap.Width;
        int height = bitmap.Height;
        //Declare the double array of grayscale values to be read from "bitmap"
        double[,] bnew = new double[height, width];

        //Loop to read the data from the Bitmap image into the double array
        int i, j;
        for (i = 0; i < width; i++)
        {
            for (j = 0; j < height; j++)
            {
                Color pixelColor = bitmap.GetPixel(i, j);
                double b = pixelColor.GetBrightness(); //the Brightness component

                //Note that rows in C# correspond to columns in MWarray
                bnew.SetValue(b, j, i);
            }
        }

        MWNumericArray arr = bnew;