Page 1 of 1

Counting colours

Posted: Fri Mar 26, 2004 3:20 pm
by Kris_a
Hi,

Anyone know a really fast way to count the colours in an image? The only way I know is to check each pixel, then look for a matching pixel in the palette, adding the colour to the palette if it isn't already there. This method is really slow, though, especially with pictures over 100x100 pixels.

Paint Shop Pro (7) can count the colours in just about any size of picture in under 0.3 sec. How on Earth does it do it?

Thanks,
Kris

Posted: Fri Mar 26, 2004 3:41 pm
by LarsG
It probably loads the picture into an array upon loading...
It would then be just a matter of sorting the numbers of this array to get the colors..

(atleast that's what I would guess... ;))

Posted: Thu Apr 01, 2004 2:12 am
by MLK
just read today about:

Code: Select all

GetDeviceCaps_(HDC, nIndex)
so, maybe

Code: Select all

GetDeviceCaps_(HDC,#NUMCOLORS)
could be interesting


just take a look at the api help

Posted: Thu Apr 01, 2004 4:24 pm
by Kris_a
Thanks, I have actually figured a way out :D

Glad to share it if anyone needs it. It's really fast (well, about the same speed as PSP's one)

PS. GetDeviceCaps only works with 8-bit images :?

Posted: Thu Apr 01, 2004 5:30 pm
by LarsG
well then... just post yer code.. or tell us how you did it?!? :)

Posted: Thu Apr 01, 2004 5:50 pm
by Kris_a
Think it'd be easier to just tell you, especially since it's in C++.

All you have to do is copy the image to a buffer then use a sorting algorithm (I suggest radix, it's the fastest one for me) on it.
Then do something like this:

Code: Select all

last_colour = buffer(0);
num_colours = 1

for i = 0 to width*height-1
  if buffer(i) <> last_colour
    num_colours = num_colours + 1
    last_colour = buffer(i)
  endif
next
I was talking with a friend about counting colours, and this just popped into my mind. I didn't expect it to be so fast! I'd been looking for a method like this for a while, so I'm really happy about that. :D