How can I use NumPy to calculate the count of distinct colors in an image?

In my computer vision course at school, I was told exclusively to use NumPy functions only to yield the total count of unique colors present in an image. Can anyone provide me with a solution? I tried surfing on the internet for this, but I got more confused.

1 Like

I have provided a solution below that finds the number of unique colors in an array. Since I didn’t have an image array to work with, I’ve used a random array, but the code will work for both cases.

The solution works as follows:

  • First, a 16x16x3 array is generated using NumPy’s random.randint() function, which generates random values between 0 and 1 and is cast to an 8-bit unsigned integer.
  • The array is then reshaped to a 2D array of shape (w*h, 3) using NumPy’s reshape function, which stacks the rows of the 3D array.
  • The np.unique() function is then applied to the flattened array to find the unique rows, and the number of unique rows is calculated using the len() function.

If you want to use your own image from your directory, simply replace the first two lines with the following code:

from PIL import Image
# load image and convert to NumPy array
img ='path/to/image.png')
arr = np.array(img)