Count Number of Unique Colors in Image using Python

Image.getpixel method from Pillow library

  1. Install Pillow library from the command line:
pip install Pillow
  1. Count number of unique colors in image:
from PIL import Image

imgPath = 'test.jpg'

img = Image.open(imgPath)
uniqueColors = set()

w, h = img.size
for x in range(w):
    for y in range(h):
        pixel = img.getpixel((x, y))
        uniqueColors.add(pixel)

totalUniqueColors = len(uniqueColors)

print(totalUniqueColors)

Leave a Comment

Cancel reply

Your email address will not be published.