0

I'm trying to count the number of (unique) colours in an image. This is what I've got:

from PIL import Image

myImage = "D:\\temp\\tiny_pal.png"

img = Image.open(myImage)
size = img.getcolors(img.size[0]*img.size[1])

if len(size) < 256:

  colours = img.convert('RGB').getcolors() # this converts the mode to RGB

  print str(len(colours)) + " colours"

else:
  print ("Image is too big!")

So far so good

tiny image 43 colours

>> 43 colours

...Only it's using PIL and moreover, is limited to a rather a small image size.

I'm aware of this question. However, it seems to have been confusingly marked as duplicate for wanting to find most dominant colour in an image.

Can you count colours, like my example above, in larger images with numpy or something similar?

Ghoul Fool
  • 6,249
  • 10
  • 67
  • 125

1 Answers1

1

How about using numpy. If you are looking for different RGB colours you can use np.unique() specifying the axis correctly to obtain all different colours. Then you could do len of the array obtained to know how many different colours are in the image.

IVR
  • 43
  • 1
  • 6