# How to calculate the number of different colors in an image Hello guys, welcome to this post in which we will learn how to calculate number of different colors in an image, This is fairly a small program and quite intresting at the same time.

Here we will use OpenCV to load images and read a pixel level data.

So let’s start.

I am adding the full code here, if you want to understand the specific function or specific line then just navigate to the particular line in the explanation

```import cv2

print('Height if image: ',len(img))
print('Width of image: ',len(img))
pixel_data=[]
for i in range(len(img)):
for j in range(len(img)):
pixel_data.append(img[i][j])

print('Total number of pixels: ',len(pixel_data))

colors=set()

for color in pixel_data:

print('Total number of different colors: ',len(colors))

```

### Explanation

```import cv2

```

First of all we are importing the OpenCV. To install OpenCV use pip

```pip install opencv-python
```

Then we set the path to the image which we want to test.

```img=cv2.imread(filename)
print('Height if image: ',len(img))
print('Width of image: ',len(img))
```

Here we are reading the image and printing Height and width of an image.

```pixel_data=[]
for i in range(len(img)):
for j in range(len(img)):
pixel_data.append(img[i][j])

print('Total number of pixels: ',len(pixel_data))
```

Here we are initializing a list, pixel_data. In the next few lines, we are going to each and every pixel and copy the color code which is in the range of (0,0,0) to (255,255,255).

Once we have the code we store it in the list.

After completion of loop, we have a list of all the color codes that are available in an image.

```colors=set()

for color in pixel_data:

print('Total number of different colors: ',len(colors))colors: ',len(colors))

```

Since list contain the data of each and every pixel so if 2 pixel have same color then we have two positions which have same color.

To encounter this we use set() function. This set() will only return the unique values. but it will not work on list so trick is to convert the code into a string and then use set() function.

Here as you can see, we iterate each code from the list and add as the string.

Now string contain all the unique colors, and the length of this “colors” will give us the number of different colors present in an image.

For 4k image which contain 16 million colors, this program took more then 17 minutes. here is the output.

```total number of colors is  16777215
CPU times: user 16min 41s, sys: 34.2 s, total: 17min 15s
Wall time: 17min 47s
```