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.
I found 4 online tools, of which 3 gave me the number 83,847 and 1 43,162
83,847:
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!