Guide To Image Color Analyzer In Python

In the modern age, we store all image data in digital memory. This can be your computer or your mobile device, or your cloud space. Whenever a device stores an image, it keeps it by breaking it into a very small mosaic or pixel form or simply saying that the computer breaks it into tiny box parts before storing any image. These small box parts can be considered as the pixel of the images. Therefore, as the size of tiles increases, the resolution of the image decreases, and the fineness of the tiles increases the resolution of the images. 

The simplest way to explain the pixels is that they consist of Red, Green, and Blue. Pixels are the smallest unit of information about any image, which are arranged in the 2-dimensional grid.

If any of those three colours of any pixel is at full intensity, we can consider it is having a pixel value of 255. A pixel value can change between 0-255; if an image is fully red, then the RGB value is (255,0,0), where red is denoted by 255 and green and blue are 0. Below is the example where we can see the formation of a full-color image.

Here in the image, we see that the combination of blue, red and green is forming a full image. So if the intensity of RGB is (0,0,0) then it will be a dark or black image, and again if the intensity of RGB is (255,255,255), the image will be white. An equal amount of red, blue and green will represent a grey colour; we call it a grey image. 

For a better representation of these colors we use hex values of the colors; this is a six-digit hex code with three pairs of two codes each and pairs representing the intensity of RGB colors. For example, if the hex code is #000100, then the intensity of red is zero(00), the first possible darkest shade of green without being black (01) and blue is also zero(00). Hex codes use the hexadecimal system to minimize the length.

In this article, we will learn about major factors of the image data and make a color analyzer that will tell us the colors presented in any image. 

Code Implementation of Image Color Analyzer

Set up an environment in the colab.

Requirements: Python 3.6 or above,opencv/cv2  3.4.15

Importing libraries 

We are importing some basic libraries like NumPy, matplotlib.pyplot etc. Apart from that,  we are importing cv2 for image processing,  sub-packages of sklearn(kmean) and skimage(rgb2lab, deltaE_cie6), counter from collections.

 import imageio
 import matplotlib.pyplot as plt
 import numpy as np
 from sklearn.cluster import KMeans
 import cv2
 from skimage.color import rgb2lab, deltaE_cie76
 from collections import Counter
 import os 

Reading the images.

 pic=imageio.imread('/content/drive/MyDrive/Yugesh/Image Color Analyzer in Python/image.JPG')
 plt.figure(figsize=(10,10))
 plt.imshow(pic)
 image = cv2.imread('/content/drive/MyDrive/Yugesh/Image Color Analyzer in Python/photo.JPG')
 image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
 plt.imshow(image) 

Output:

Here we called the images using imagio.imread and  cv2.imread for the first and second images, respectively and then for the second image, we converted the color order BGR(blue, green, red) to RGB(red, green, blue) because in BGR order, the image colors look different to the original image.

Let’s gather some basic information about our first image.

Check for the basic properties of image:

Input:

 print('Type of the image : ',type(pic))
 print('Shape of the image : {}'.format(pic.shape))
 print('Hight of the image {}'.format(pic.shape[0]))
 print('Width of the image {}'.format(pic.shape[1]))
 print('Dimension of the Image {}'.format(pic.ndim)) 

Output:

In properties, we can see the shape of the image is three-layered and its width is 4000, and the height of the image is 30. The type of image is an np array three-layered matrix.

Check for the RGB values and size of the image.

Input :

 print('Image size {}'.format(pic.size))
 print('Maximum RGB value in this image {}'.format(pic.max()))
 print('Minimum RGB value in this image {}'.format(pic.min())) 

Output:

Next, we are going to extract the information about the pixel located in a particular place.  The location of the pixel is pic[150,100].

Input :

 print('Value of only R channel {}'.format(pic[ 150, 100, 0]))
 print('Value of only G channel {}'.format(pic[ 150, 100, 1]))
 print('Value of only B channel {}'.format(pic[ 150, 100, 2])) 

Output:

Let’s view each channel in the whole image.

Red channel

Input :

 plt.title('R channel')
 plt.imshow(pic[ : , : , 0])
 plt.show() 

Output:

Green channel:

Input:

 plt.title('G channel')
 plt.imshow(pic[ : , : , 1])
 plt.show() 

Output:

Blue channel.

Input:

 plt.title('B channel')
 plt.imshow(pic[ : , : , 2])
 plt.show() 

Output:

Here we have seen some of the basic properties of image data. In the next step, we are making a function to analyze the color values present in an image. For this, in the beginning, we have imported an image with a variable name “image”..

Let’s check the details of our image.

Input :

 print("The type of image is {}".format(type(image)))
 print("Shape of the image: {}".format(image.shape)) 

Output:

Color analysis of the image:

Defining a function to extract the hex value of colors present in the image.

 def RGB_HEX(color):
     return "#{:02x}{:02x}{:02x}".format(int(color[0]), int(color[1]), int(color[2])) 

In the next function, we are Using Kmeans clusters to arrange the colors in different clusters. The algorithm of Kmeans requires a flattened array as input, which is why we are required to flatten the NumPy array into an array of 1 row, three columns. And using the counter to sort colors RGB value.

 def get_colors(image, number_of_colors, show_chart):
     reshaped_image = cv2.resize(image, (600, 400))
     reshaped_image = reshaped_image.reshape(reshaped_image.shape[0]*reshaped_image.shape[1], 3)
     clf = KMeans(n_clusters = number_of_colors)
     labels = clf.fit_predict(reshaped_image)
     counts = Counter(labels)
     counts = dict(sorted(counts.items()))
     center_colors = clf.cluster_centers_
     ordered_colors = [center_colors[i] for i in counts.keys()]
     hex_colors = [RGB_HEX(ordered_colors[i]) for i in counts.keys()]
     rgb_colors = [ordered_colors[i] for i in counts.keys()]
     if (show_chart):
         plt.figure(figsize = (8, 6))
         plt.pie(counts.values(), labels = hex_colors, colors = hex_colors)
     return rgb_colors 

Finally, we apply our functions to our images to know about the hex value of the colours presented in the image.

Input :

get_colors(image, 8, True)

Output:

Here in the output, we can see the arranged array of RGB values of colors presented in the image provided to openCV and in the pie chart, we see the hex value of 15 most occurred colors in the image. Thus, by this chart, we can analyze the colours presented in the image. 

There are many shades of any color available, so it is very difficult to discrete color names in an image. So we prefer to use hex values to represent the shade of color. In this article, we have seen some basic information extraction of any image data, and we picked up 15 most occurring colors from the image with their hex identity.

References

All the information written in this article is gathered from:

Download our Mobile App

Yugesh Verma
Yugesh is a graduate in automobile engineering and worked as a data analyst intern. He completed several Data Science projects. He has a strong interest in Deep Learning and writing blogs on data science and machine learning.

Subscribe to our newsletter

Join our editors every weekday evening as they steer you through the most significant news of the day.
Your newsletter subscriptions are subject to AIM Privacy Policy and Terms and Conditions.

Our Recent Stories

Our Upcoming Events

3 Ways to Join our Community

Telegram group

Discover special offers, top stories, upcoming events, and more.

Discord Server

Stay Connected with a larger ecosystem of data science and ML Professionals

Subscribe to our Daily newsletter

Get our daily awesome stories & videos in your inbox
MOST POPULAR

6 IDEs Built for Rust

Rust IDEs aid efficient code development by offering features like code completion, syntax highlighting, linting, debugging tools, and code refactoring