比较两个颜色列表

时间:2016-01-19 14:24:23

标签: c#

假设我有两个颜色列表,我需要比较它们。我有比较颜色的功能,但我对功能获得的类型有点困惑。如何施展它们?

public bool AreColorsSimilar(Color c1, Color c2, int tolerance)
{
    return Math.Abs(c1.R - c2.R) < tolerance &&
           Math.Abs(c1.G - c2.G) < tolerance &&
           Math.Abs(c1.B - c2.B) < tolerance;
}

这是我的第一个清单:

public static List<Color> PaletteOfSeasons()
{
    List<Color> springColors = new List<Color>();

    springColors.Add(ColorTranslator.FromHtml("#80a44c"));
    springColors.Add(ColorTranslator.FromHtml("#b4cc3a"));


    return springColors;
}

在另一个列表中,我从图像中提取像素:

public static IEnumerable<Color> GetPixels(Bitmap bitmap)
{
    for (int x = 0; x < bitmap.Width; x++)
    {
        for (int y = 0; y < bitmap.Height; y++)
        {
            Color pixel = bitmap.GetPixel(x, y);
            yield return pixel;
        }
    }
}

问题是,我该如何比较这些颜色?

2 个答案:

答案 0 :(得分:2)

如果我理解你的话:

var springColors = null;
springColors = PaletteOfSeasons(springColors);

var similarColors = GetPixels(bitmap).Intersect(springColors, new ColorComparer(tolerance));

你需要这堂课:

public class ColorComparer : IEqualityComparer<Color> 
{
    private _tolerance;

    public ColorComparer(int tolerance)
    {
        _tolerance = tolerance;
    }

    public bool Equals(Color x, Color y)
    {
        return AreColorsSimilar(x, y, _tolerance);
    }

    public int GetHashCode(Foo x)
    {
        return 0;
    }

    private bool AreColorsSimilar(Color c1, Color c2, int tolerance)
    {
        return Math.Abs(c1.R - c2.R) < tolerance &&
           Math.Abs(c1.G - c2.G) < tolerance &&
           Math.Abs(c1.B - c2.B) < tolerance;
    }
}

P.S。你的方法PaletteOfSeasons有点令人困惑。将名单愚蠢地传递给方法。

P.P.S。使用Bitmap.LockBits()来提高代码性能。

P.P.P.S。 GetHashCode的这种实现并不好。但在我们的情况下,这是可以的。

答案 1 :(得分:0)

只需将位图的所有像素与调色板中的所有颜色进行比较:

foreach(var pixel in GetPixels(myBitmap))
{
    foreach(var candidate in paletteOfSeasons)
    {
        if(AreColorsSimilar(pixel, candidate, 42)
        {
            // Hooray, found some similar colors.
        }
    }
}