从bmp获得平均颜色

时间:2011-03-05 16:57:43

标签: c# rgb

我正在开发第二个屏幕的任务栏(类似于displayfusion)。

但是,我很难从图标中获得正确的平均颜色。例如Google Chrome /当我将其悬停在主任务栏上时,它背景会变黄。我的代码变成橙色/红色。

这就是它现在的样子:

enter image description here

如何获得正确的显性/平均颜色?

我使用此代码计算平均颜色:

public static Color getDominantColor(Bitmap bmp)
{
     //Used for tally
     int r = 0;
     int g = 0;
     int b = 0;

     int total = 0;

     for (int x = 0; x < bmp.Width; x++)
     {
          for (int y = 0; y < bmp.Height; y++)
          {
               Color clr = bmp.GetPixel(x, y);    
               r += clr.R;
               g += clr.G;
               b += clr.B;    
               total++;
          }
     }

     //Calculate average
     r /= total;
     g /= total;
     b /= total;

     return Color.FromArgb(r, g, b);
}

1 个答案:

答案 0 :(得分:13)

平均颜色不一定是最常用的颜色。我建议计算饱和度超过某个阈值的像素的HUE,并使用数组创建图像的直方图。 (使用某种色调值的次数)。

然后平滑直方图(计算两个邻居的局部平均值),然后得到平滑直方图取最大值的位置。

您可以通过以下方式获取HSL值:

Color.GetHue
Color.GetSaturation
Color.GetBrightness