WPF C#, CalculateAverageColor for bitmap

Here is a simple method to calculate the average color in a bitmap (WPF C#). The result is not always the best, it can tend to be muddy or more like a grey-scale effect. An improved method is to find the dominant color, though more computationally expensive – I will post an example soon.

C#
<code>
 
public static Color CalculateAverageColor(BitmapSource source)
        {
            if (source.Format.BitsPerPixel != 32)
                throw new ApplicationException("expected 32bit image");
 
            Color cl;
            System.Windows.Size sz = new System.Windows.Size(source.PixelWidth, source.PixelHeight);
 
            //read bitmap 
            int pixelsSz = (int)sz.Width * (int)sz.Height * (source.Format.BitsPerPixel / 8);
            int stride = ((int)sz.Width * source.Format.BitsPerPixel + 7) / 8;
 
            byte[] pixels = new byte[pixelsSz];
            source.CopyPixels(pixels, stride, 0);
 
            //find the average color for the image
            const int alphaThershold = 10;
            UInt64 r, g, b, a; r = g = b = a = 0;
            UInt64 pixelCount = 0;
 
            for (int y = 0; y < sz.Height; y++)
            {
                for (int x = 0; x < sz.Width; x++)
                {
                    int index = (int)((y * sz.Width) + x) * 4;
                    if (pixels[index + 3] <= alphaThershold) //ignore transparent
                        continue;
 
                    pixelCount++;
                    a += pixels[index + 3];
                    r += pixels[index + 2];
                    g += pixels[index + 1];
                    b += pixels[index];
                }
            }
 
            //average color result
            cl = Color.FromArgb((int)(a / pixelCount),
                                (int)(r / pixelCount),
                                (int)(g / pixelCount),
                                (int)(b / pixelCount));
 
            return cl;           
        }
 
</code>

Comments (0)

› No comments yet.

Pingbacks (0)

› No pingbacks yet.