简体   繁体   English

如何在C#中使用两种颜色之间的rgb差异以找到最接近的匹配?

[英]How to use rgb difference between two colors in C# in order to find the closest match?

I have a code that gets the closest color based on RGB difference, but with dark colors like dark blue, it returns black instead of "dark blue". 我有一个代码,可以根据RGB差异获得最接近的颜色,但是如果使用深蓝色(如深蓝色),它将返回黑色而不是“深蓝色”。 Can u guys help me finding out what's happening? 你们可以帮助我了解发生了什么吗?

This is the code that calculates RGB difference between two colors: 这是计算两种颜色之间的RGB差异的代码:

int ColorDiff(Color c1, Color c2)
{
    return (int)Math.Sqrt((c1.R - c2.R) * (c1.R - c2.R)
                        + (c1.G - c2.G) * (c1.G - c2.G)
                        + (c1.B - c2.B) * (c1.B - c2.B));
}

This code gets the closest color on the list (the one that has less difference between RGB): 此代码获取列表中最接近的颜色(RGB之间的色差较小):

int encontrarCor(List<Color> colors, Color target)
{
    var colorDiffs = colors.Select(n => ColorDiff(n, target)).Min(n => n);
    return colors.FindIndex(n => ColorDiff(n, target) == colorDiffs);
}

What I think is happening is that, as you can see in the first code, it does: (c1.R - c2.R) * (c1.R - c2.R), so if one of these substrates is equal to 0, the whole product is gonna be 0, so returns black, cause RGB code of black is 0,0,0. 我认为正在发生的事情是,正如您在第一个代码中看到的那样,它确实是:(c1.R-c2.R)*(c1.R-c2.R),因此,如果这些底物之一等于0 ,整个乘积将为0,因此返回黑色,导致黑色的RGB代码为0,0,0。

I've tried to make myself as clear as possible, sorry if is a little bit confused. 我试图使自己尽可能清楚,对不起,如果有点困惑。

I don't get the point of the square root and multiplications, but the differences should be positive: 我不知道平方根和乘法的意义,但是差异应该是正的:

int RGBdiff(Color c1, Color c2)
{
    return Math.Abs(c1.R - c2.R) + Math.Abs(c1.G - c2.G) + Math.Abs(c1.B - c2.B);
}

Color ClosestColor(Color target, IEnumerable<Color> colors)
{
    return colors.Min(c => Tuple.Create(RGBdiff(c, targert), c)).Item2;
}

Note that more than one color can have the same difference. 请注意,不止一种颜色可以具有相同的差异。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM