How many different colors in my image

Invisionsoft

Well-known member
Joined
Apr 20, 2007
Messages
64
Location
United Kingdom
Programming Experience
1-3
Hello Folks,

I need to find out how many different colors are in an image.

Note I do not need to deal with alpha-transparent pixels, there will not be a transparent layer (24-bit PNGs/BMPs). Transparency is magic pink.

I found nothing using Bitmap.Pallete,which I thought would reveal all.

I came up with the following, it works.

VB.NET:
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim OFD As New OpenFileDialog
        OFD.FileName = String.Empty
        OFD.Filter = "PNGs|*.png|BMPs|*.bmp|JPEGs|*.jpeg"
        If OFD.ShowDialog = Windows.Forms.DialogResult.OK Then
            MsgBox(ImageCountColors(Image.FromFile(OFD.FileName)).ToString)
        End If
    End Sub

    Function ImageCountColors(ByVal TheImage As Bitmap) As Int16
        Dim AllColors As New Collection
        For X As Int16 = 0 To TheImage.Width - 1
            For Y As Int16 = 0 To TheImage.Height - 1
                Dim TheColor As Color = TheImage.GetPixel(X, Y)
                Dim TheColorString As String = TheColor.R.ToString + TheColor.G.ToString + TheColor.B.ToString
                Dim AlreadyThere As Boolean = False
                For Each P As String In AllColors
                    If P = TheColorString Then AlreadyThere = True : Exit For
                Next
                If Not AlreadyThere Then AllColors.Add(TheColorString)
            Next
        Next
        Return AllColors.Count
    End Function

It works a dream on small, 32x32 images. However, the images I will be using will often be 4096x4096 in size, which means the code takes a very very long time to run. It is because of the 'GetPixel' function that is really slow.

What do you suggest to make it work faster on large images?



Thanks.
James.
 
Palettes is only used in indexed image formats, where pixel data refers to palette index for color instead of the color data itself.

As you discovered GetPixel is slow for this, 'lockbits' method is what you need, start with this article: Using the LockBits method to access image data
 
Back
Top