Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# finding similar colors

Tags:

c#

colors

I want to call a method with argument color. But there are a lot of colors which differ only by a shade. How can I find the colors which differ from my color only by little, for example AntiqueWhite and Bisque. Here's the color palette.

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);
like image 937
petko_stankoski Avatar asked Oct 21 '11 07:10

petko_stankoski


2 Answers

I found this routine 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);

    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;
    }
}
like image 22
Marco Avatar answered Oct 02 '22 12:10

Marco


Could you use a method like this:

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

This method takes two colours and a tolerance and returns whether those two colours are close or not based on their RGB values. I think that should do the trick but you may need to extend to include brightness and saturation.

like image 140
Kevin Holditch Avatar answered Oct 02 '22 10:10

Kevin Holditch