0

I want to count unique colors in an image with Python. For reference I used multiple online tools. The thing is, I get 2 different values, depending on the tool I use.

Testimage: https://images.unsplash.com/photo-1500964757637-c85e8a162699?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxzZWFyY2h8NHx8YmVhdXRpZnVsJTIwbGFuZHNjYXBlfGVufDB8fDB8fHww&w=1000&q=80

I found 4 online tools, of which 3 gave me the number 83,847 and 1 43,162

83,847:

https://pixspy.com/

https://planetcalc.com/10185/#google_vignette

https://townsean.github.io/canvas-pixel-color-counter/

43,162:

https://www.imgonline.com.ua/eng/unique-colors-number.php

I'm confused, why that is. When I try to calculate it with python, I also get 43,162

I have 2 methodes!

Method 1:

img = Image.open(os.path.join(IMAGE_FOLDER_PATH, image))
x = np.array(img)

# unique colors
_, counts = np.unique(x.reshape(-1, x.shape[-1]), axis=0, return_counts=True)
counts_size = counts.size
print(f"Unique Color: {counts_size}")

Method 2

img = Image.open(os.path.join(IMAGE_FOLDER_PATH, image))
unique_colors = set()
image_width, image_height = img.size

for i in range(image_width):
    for j in range(image_height):
        pixel = img.getpixel((i, j))
        unique_colors.add(pixel)

unique_colors_count = len(unique_colors)

Both Methods give the same the same (43.162) value. The file is a jpeg.

Why do I get different values? I use the excact same image. Which one is probably the right one or are both right? And if 83,847 is correct, how do I calculate it in python?

Thanks for your help!

Ecko
  • 5
  • 2
  • 1
    Why don't you try this with an image for which you know for sure how many colors it has? – mkrieger1 Jul 19 '23 at 18:51
  • Pixspy and planet calc both give me 43,166 colors, not 83,847. – Nick ODell Jul 19 '23 at 19:02
  • 2
    The JPG decoding may work differently in different tools. Try a lossless compression format like PNG (or uncompressed like BMP). – Michael Butscher Jul 19 '23 at 19:39
  • With Python like this https://stackoverflow.com/a/59671950/2836621 Remember JPEG is ***lossy*** that means it can give you back different values from what you saved. – Mark Setchell Jul 19 '23 at 20:14
  • @NickODell Thats weird. I tried both again and still get 83,690 (don't know if wrote the wrong number or if it has changed). With planetcalc I can even drag and drop it from the browser window, so I'm not saving it on my pc. – Ecko Jul 19 '23 at 22:07
  • @MichaelButscher The image is just a test image. The images I want to use it on are in a dataset, which only offser jpgs. – Ecko Jul 19 '23 at 22:09
  • Perhaps unsplash is dynamically compressing the image, and offering different images to each user based on browser? – Nick ODell Jul 19 '23 at 22:29

0 Answers0