Counting colours

Advanced game related topics
Kris_a
User
User
Posts: 92
Joined: Sun Feb 15, 2004 8:04 pm
Location: Manchester, UK

Counting colours

Post 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
LarsG
Enthusiast
Enthusiast
Posts: 713
Joined: Mon Jun 02, 2003 1:06 pm
Location: Norway
Contact:

Post 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... ;))

AMD Athlon XP2400, 512 MB RAM, Hercules 3D Prophet 9600 256MB RAM, WinXP
PIII 800MHz, 320 MB RAM, Nvidia Riva Tnt 2 Mach 64 (32MB), WinXP + Linux
17" iMac, 1.8 GHz G5, 512 MB DDR-RAM, 80 GB HD, 64 MB Geforce FX 5200, SuperDrive, OSX
MLK
User
User
Posts: 57
Joined: Sat Jan 24, 2004 8:46 pm
Location: Germany

Post 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
Kris_a
User
User
Posts: 92
Joined: Sun Feb 15, 2004 8:04 pm
Location: Manchester, UK

Post 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 :?
LarsG
Enthusiast
Enthusiast
Posts: 713
Joined: Mon Jun 02, 2003 1:06 pm
Location: Norway
Contact:

Post by LarsG »

well then... just post yer code.. or tell us how you did it?!? :)

AMD Athlon XP2400, 512 MB RAM, Hercules 3D Prophet 9600 256MB RAM, WinXP
PIII 800MHz, 320 MB RAM, Nvidia Riva Tnt 2 Mach 64 (32MB), WinXP + Linux
17" iMac, 1.8 GHz G5, 512 MB DDR-RAM, 80 GB HD, 64 MB Geforce FX 5200, SuperDrive, OSX
Kris_a
User
User
Posts: 92
Joined: Sun Feb 15, 2004 8:04 pm
Location: Manchester, UK

Post 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
Post Reply