C# 如何在C语言中使用Floyd Steinberg算法对图像进行抖动#

C# 如何在C语言中使用Floyd Steinberg算法对图像进行抖动#,c#,dithering,C#,Dithering,我是C#的新手,在我的第二个项目中,我试图编写一种使用Floyd Steinberg方法抖动位图的算法,我对视频进行了编码,但在RGB值超出范围的情况下,我遇到了一系列错误,例如,有时值是256,有时甚至是负数 下面是重要的代码块 static public Bitmap Imagedither(Bitmap original) { for (int y = 0; y < original.Height - 1; y++) { for (int x = 1;

我是C#的新手,在我的第二个项目中,我试图编写一种使用Floyd Steinberg方法抖动位图的算法,我对视频进行了编码,但在RGB值超出范围的情况下,我遇到了一系列错误,例如,有时值是256,有时甚至是负数

下面是重要的代码块

static public Bitmap Imagedither(Bitmap original)
{
    for (int y = 0; y < original.Height - 1; y++)
    {
        for (int x = 1; x < original.Width - 1; x++)
        {
            Color oldPixel = original.GetPixel(x, y);
            Color newPixel = roundColor(oldPixel, 1);
            original.SetPixel(x, y, newPixel);
            Error error = new Error(oldPixel.R - newPixel.R, oldPixel.G - newPixel.G, oldPixel.B - newPixel.B);

            original.SetPixel(x + 1, y    , AddError(original.GetPixel(x + 1, y), error, 7 / 16.0));
            original.SetPixel(x - 1, y + 1, AddError(original.GetPixel(x - 1, y + 1), error, 3 / 16.0));
            original.SetPixel(x    , y + 1, AddError(original.GetPixel(x, y + 1), error, 5 / 16.0));
            original.SetPixel(x + 1, y + 1, AddError(original.GetPixel(x + 1, y + 1), error, 1 / 16.0));
        }
    }
    return original;
}

static public Color roundColor(Color color, int factor)
{
    double R = (double)factor * color.R / 255.0;
    double newR = Math.Round(R) * (255 / factor);
    double G = (double)factor * color.G / 255.0;
    double newG = Math.Round(G) * (255 / factor);
    double B = (double)factor * color.B / 255.0;
    double newB = Math.Round(B) * (255 / factor);
    return Color.FromArgb((int)newR, (int)newG, (int)newB);
}

static public Color AddError(Color pixel, Error error, double amount)
{
    int R = (int)(pixel.R + (error.R * amount));
    int G = (int)(pixel.G + (error.G * amount));
    int B = (int)(pixel.B + (error.B * amount));
    return Color.FromArgb(R > 255 ? 255 : R, G > 255 ? 255 : G, B > 255 ? 255 : B);
}

public class Error
{
    public double R { get; set; }
    public double G { get; set; }
    public double B { get; set; }
    public Error() { }
    public Error(double r, double g, double b)
    {
        R = r;
        G = g;
        B = b;
    }
}
静态公共位图图像抖动器(位图原始)
{
对于(int y=0;y255?255:R,G>255?255:G,B>255?255:B);
}
公共类错误
{
公共双R{get;set;}
公共双G{get;set;}
公共双B{get;set;}
公共错误(){}
公共错误(双r、双g、双b)
{
R=R;
G=G;
B=B;
}
}

@TaW我不这么认为,因为我到处找,每个人都有255个,甚至是编码火车。你是对的。哪些行出现了错误?调试器没有帮助吗?-这一行可以创建负值:
Error Error=newerror(oldPixel.R-newPixel.R,oldPixel.G-newPixel.G,oldPixel.B
-newPixel.B);`-不要只限制太大的值,而需要在两侧钳制它们,可能像这样
intr=Math.Max(0,Math.Min(255,(int)(pixel.R+(error.R*amount))。@Taw您的解决方案有效,但我仍然不知道为什么需要钳制它。哦,错误出现在
return Color.FromArgb(R>255?255:R,G>255?255:G,B>255?255:B)行上我认为在计算RGB值时存在某种错误,类错误可能有负值。