将代码从matlab转换为c#

时间:2016-05-03 16:20:01

标签: c# matlab

我正在尝试使用MRF实现图像降噪。我用了这个article。它还提供了this code in matlab。我尝试用c#重写它来处理带有蓝色通道的噪声图像like this

但在使用我的代码后,我只得到了更暗的图像。我究竟做错了什么?在matlab中我没有包含在我的代码中吗? 我的代码是:

public static Bitmap Process(Bitmap src, double covar, double max_diff, double weight_diff, int iterations)
{
    var buffer = new Bitmap[2];
    var b = new Bitmap(src.Width, src.Height, src.PixelFormat);
    for (var i = 0; i < src.Width; i++)
        for (var j = 0; j < src.Height; j++)
        {
            b.SetPixel(i, j, Color.FromArgb(src.GetPixel(i, j).A, 0, 0, 0));
        }

    buffer[0] = src;
    buffer[1] = b;
    var s = 1;
    var d = 0;
    var vMax = (src.Width * src.Height) * (Math.Pow(256, 2) / (2 * covar) + 4 * weight_diff * max_diff);

    for (var i = 0; i < iterations; i++)
    {
        Console.WriteLine("Iteration: " + i.ToString());
        if (s == 0) { s = 1; d = 0; }
        else { s = 0; d = 1; }
        for (var r = 0; r < src.Height - 1; r++)
            for (var c = 0; c < src.Width - 1; c++)
            {
                //val = red
                var vLocal = vMax;
                var minVal = -1;
                for (var val = 0; val < 255; val+=1)
                {
                    var V_Data = Math.Pow((val - src.GetPixel(r, c).B), 2) / (2 * covar); //r
                    var V_diff = 0;

                    if (r > 1)
                    {
                        V_diff = V_diff + (int)Math.Min((val - Math.Pow(buffer[s].GetPixel(r - 1, c).B, 2)), max_diff);
                    }

                    if (r < src.Height)
                    {
                        V_diff = V_diff + (int)Math.Min((val - Math.Pow(buffer[s].GetPixel(r + 1, c).B, 2)), max_diff);
                    }

                    if (c > 1)
                    {
                        V_diff = V_diff + (int)Math.Min((val - Math.Pow(buffer[s].GetPixel(r, c - 1).B, 2)), max_diff);
                    }

                    if (c < src.Height)
                    {
                        V_diff = V_diff + (int)Math.Min((val - Math.Pow(buffer[s].GetPixel(r, c + 1).B, 2)), max_diff);
                    }

                    var V_current = V_Data + weight_diff * V_diff;

                    if (V_current < vLocal)
                    {
                        minVal = val;
                        vLocal = V_current;
                    }
                }
                Color color = buffer[d].GetPixel(r, c); 
                var e = Color.FromArgb(color.A, color.R, color.G, minVal);
                buffer[d].SetPixel(r, c, e);
            }
    }
    return buffer[d];
}

0 个答案:

没有答案