vb.netvb.net-2010

Averaging color of an Image


I'm using this code to calculate the average color of an image but this is not working as desired. The result is inaccurate. How to find the average color of the image ?

Private Sub btnAvg_Click() Handles btnAvg.Click
    Dim x, y As Integer
    bmp = New Bitmap(picBox.Tag.ToString)

    For y = picBox.Top To picBox.Bottom
        For x = picBox.Left To picBox.Right
            With bmp.GetPixel(x, y)
                totalR = totalR + .R : totalG = totalG + .G : totalB = totalB + .B
            End With
        Next x
    Next y

    avgR = totalR / ((picBox.Bottom - picBox.Top) * (picBox.Right - picBox.Left))
    avgG = totalG / ((picBox.Bottom - picBox.Top) * (picBox.Right - picBox.Left))
    avgB = totalB / ((picBox.Bottom - picBox.Top) * (picBox.Right - picBox.Left))
End Sub

I'm looking for a hi-speed, more than 80% accurate result. This is not a duplicate question as other questions deals with C# only


Solution

  • Averaging colors doesn't make much sense in general. What's the average of hot pink and navy yellow? The way you are calculating it now produces a completely different color.

    You'll need to work in a different color space. HSB is an easy one to work with and directly supported by the Color type. Albeit that it doesn't deal with the strongly non-linear color perception of the human eye. Color.GetHue() returns the hue, a value that's directly proportional to the color. You also ought to create a histogram so that the background of the photo doesn't disturb the results too much. Or at least work from the center of photo outwards. Whether that's good enough to detect skin color is fairly doubtful.