I'm currently running this function 60 times per second in order to get the dominant color on my screen in RGB values. It is using approximately 15% of my CPU on 30FPS and 25% of my CPU on 60FPS. Is there any way I can improve the efficiency of this loop or is there a better way to get the color altogether?
public Color getDominantColor(System.Drawing.Bitmap bmp) {
BitmapData srcData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
int stride = srcData.Stride;
IntPtr Scan0 = srcData.Scan0;
int[] totals = new int[] { 0, 0, 0 };
int width = bmp.Width;
int height = bmp.Height;
unsafe
{
byte* p = (byte*)(void*)Scan0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
for (int color = 0; color < 3; color++) {
int idx = (y * stride) + x * 4 + color;
totals[color] += p[idx];
}
}
}
}
int avgB = totals[0] / (width * height);
int avgG = totals[1] / (width * height);
int avgR = totals[2] / (width * height);
bmp.UnlockBits(srcData);
return Color.FromArgb(avgR, avgG, avgB);
}