c # найти похожие цвета - PullRequest
6 голосов
/ 21 октября 2011

Я хочу вызвать метод с аргументом color. Но есть много цветов, которые отличаются только оттенком. Как я могу найти цвета, которые мало отличаются от моего цвета, например AntiqueWhite и Bisque. Вот цветовая палитра.

Bitmap LogoImg = new Bitmap("file1.jpeg");//the extension can be some other
System.Drawing.Color x = LogoImg.GetPixel(LogoImg.Width-1, LogoImg.Height-1);
LogoImg.MakeTransparent(x);
image1.Source = GetBitmapSource(LogoImg);

Ответы [ 6 ]

11 голосов
/ 21 октября 2011

Не могли бы вы использовать такой метод:

 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;
 }

Этот метод принимает два цвета и допуск и возвращает, близки ли эти два цвета на основе их значений RGB. Я думаю, что это должно сработать, но вам может потребоваться расширить, чтобы включить яркость и насыщенность.

6 голосов
/ 21 октября 2011

Я нашел эту процедуру здесь :

Color nearest_color = Color.Empty;
foreach (object o in WebColors)
{
    // compute the Euclidean distance between the two colors
    // note, that the alpha-component is not used in this example
    dbl_test_red = Math.Pow(Convert.ToDouble(((Color)o).R) - dbl_input_red, 2.0);
    dbl_test_green = Math.Pow(Convert.ToDouble
        (((Color)o).G) - dbl_input_green, 2.0);
    dbl_test_blue = Math.Pow(Convert.ToDouble
        (((Color)o).B) - dbl_input_blue, 2.0);

    temp = Math.Sqrt(dbl_test_blue + dbl_test_green + dbl_test_red);
    // explore the result and store the nearest color
    if(temp == 0.0)
    {
        nearest_color = (Color)o;
        break;
    }
    else if (temp < distance)
    {
        distance = temp;
        nearest_color = (Color)o;
    }
}
3 голосов
/ 21 октября 2011

Ближайший цвет можно получить из перечисления KnownColors.

// A color very close to Rosy Brown
var color = Color.FromArgb(188, 143, 142);

var colors = Enum.GetValues(typeof (KnownColor))
                .Cast<KnownColor>()
                .Select(Color.FromKnownColor);

var closest = colors.Aggregate(Color.Black, 
                (accu, curr) =>
                ColorDiff(color, curr) < ColorDiff(color, accu) ? curr : accu);

И способ поддержки

private int ColorDiff(Color color, Color curr)
{
    return Math.Abs(color.R - curr.R) + Math.Abs(color.G - curr.G) + Math.Abs(color.B - curr.B);
}
2 голосов
/ 21 октября 2011

Анализируйте этот пример Find the Nearest Color with C#. Надежда дает вам представление.

enter image description here

Color nearest_color = Color.Empty;
foreach (object o in WebColors)
{
    // compute the Euclidean distance between the two colors
    // note, that the alpha-component is not used in this example
    dbl_test_red = Math.Pow(Convert.ToDouble(((Color)o).R) - dbl_input_red, 2.0);
    dbl_test_green = Math.Pow(Convert.ToDouble
        (((Color)o).G) - dbl_input_green, 2.0);
    dbl_test_blue = Math.Pow(Convert.ToDouble
        (((Color)o).B) - dbl_input_blue, 2.0);
    // it is not necessary to compute the square root
    // it should be sufficient to use:
    // temp = dbl_test_blue + dbl_test_green + dbl_test_red;
    // if you plan to do so, the distance should be initialized by 250000.0
    temp = Math.Sqrt(dbl_test_blue + dbl_test_green + dbl_test_red);
    // explore the result and store the nearest color
    if(temp == 0.0)
    {
        // the lowest possible distance is - of course - zero
        // so I can break the loop (thanks to Willie Deutschmann)
        // here I could return the input_color itself
        // but in this example I am using a list with named colors
        // and I want to return the Name-property too
        nearest_color = (Color)o;
        break;
    }
    else if (temp < distance)
    {
        distance = temp;
        nearest_color = (Color)o;
    }
}
1 голос
/ 01 августа 2013

Я использовал ответ Кевена Холдича ниже. Но я изменил это для своих собственных целей. В этой версии используется исключение или так, что только одно значение может быть отключено допуском и все еще возвращать true. (Допуск также <= вместо <.) </p>

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;
}
0 голосов
/ 21 октября 2011

Я думаю, чтобы найти похожие цвета, вам следует взглянуть на HSL или HSB вместо RGB, потому что с этим намного проще найти похожие цвета.

В .Net вы можете вызвать метод GetHue(), GetSaturation() и GetBrightness(), чтобы получить эти значения из данного цвета и сравнить ихзначения, чтобы найти похожие.

Если вам нужен путь от значения HSB к цвету, вы также можете использовать этот метод .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...