Building an Image Color Analyzer using Python | by Behic Guven | Towards Data Science

In this post, I will show you how to create a program that can detect colors and then calculate the weights of the colors in an image. This will be a fun and straightforward machine learning based computer vision project, where we will use Scikit-learn and OpenCV as our main modules. Especially, graphic designers and web designers will find this program very helpful. Not only detecting the colors but also seeing their volume levels in an image is a super neat feature.
As a technology and art enthusiast, I enjoy working on projects that are very much related to both fields. And that’s what I love about programming. Your limit is your imagination!
If you are into art/ programming, you can find many hands-on projects like this on my blog. Without losing any time, let’s get to work!
Getting Started
Libraries
Reading an Image
Functions
Image Color Analyzer in Action
Conclusion
We will be using two main modules in this color analysis project. And they are Scikit-learn and OpenCV. Scikit-learn is a well-known artificial intelligence and machine learning module. And OpenCV is a must-have computer vision module. Here is a short definition of OpenCV.
OpenCV (Open Source Computer Vision Library) is an open-source computer vision and machine learning software library. OpenCV was built to provide a common infrastructure for computer vision applications and accelerate machine perception in commercial products.
Reference: https://opencv.org
First things first, let me introduce you to the libraries. We will need five libraries for this project. And these libraries can be listed as following: OpenCV, Scikit-learn, NumPy, Matplotlib and Collections.
Now, let’s install them using pip, which is a python library manager. By the way, we don’t need to install collections; it comes by default with Python.
pip install opencv-python scikit-learn numpy matplotlib 
After the installation is completed, we can go ahead and import them. By the way, I will use Jupyter Notebook for this project. Great way to keep a timeline of the process.
from collections import Counterfrom sklearn.cluster import KMeansfrom matplotlib import colorsimport matplotlib.pyplot as pltimport numpy as npimport cv2
Here are the official links for each library. Feel free to check them out to learn more about them.
OpenCV
Scikit-learn
Matplotlib
Numpy
Collections
We need to choose an image to get started. Here is the image that I will be using for this project.
image = cv2.imread('test_image.jpg')image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)plt.imshow(image)
We are using imread method by OpenCV to read the image. And then, we are converting the color format from BGR to RGB using cvtColor. The everyday images that we see on our devices are in RGB format.
In this step, as you can understand from the title, we will be writing functions. I will define three functions that will be helpful for us. Functions are also an excellent method to simplify your programs.
Here are the functions with their definitions.
def rgb_to_hex(rgb_color):    hex_color = "#"    for i in rgb_color:        i = int(i)        hex_color += ("{:02x}".format(i))    return hex_color
In this function, we are converting an RGB color into Hex color format. This function will help at the end when visualizing the results of our analysis. Instead of having three different values (red, green, blue), we will have one output: hex value.
def prep_image(raw_img):    modified_img = cv2.resize(raw_img, (900, 600), interpolation = cv2.INTER_AREA)    modified_img = modified_img.reshape(modified_img.shape[0]*modified_img.shape[1], 3)    return modified_img
This function basically does the preprocessing of the image. If you want to make any changes to the picture before analyzing the colors, this is the function that you can use. We will resize and reshape the image in this step. Resizing is optional, but reshaping is needed for the color analysis model to work correctly. We will see it in the following function.
This is the function where the magic happens. I will cover in bullet points what is happening in the function.
def color_analysis(img):    clf = KMeans(n_clusters = 5)    color_labels = clf.fit_predict(img)    center_colors = clf.cluster_centers_    counts = Counter(color_labels)    ordered_colors = [center_colors[i] for i in counts.keys()]    hex_colors = [rgb_to_hex(ordered_colors[i]) for i in counts.keys()]    plt.figure(figsize = (12, 8))    plt.pie(counts.values(), color_labels = hex_colors, colors = hex_colors)    plt.savefig("color_analysis_report.png")    print(hex_colors)
First, we are using k-Means to cluster the top colors. Inside the function we are passing the value of how many clusters do we want to divide. Here is the documentation for K-Means clustering. After clustering we predict the colors that weigh the most — meaning getting the most area on the image.
Secondly, we are calling the Counter function. Counter creates a container to the elements as dictionary keys, and their volume is store as dictionary values. If you are not familiar with dictionaries, they store data in key: value pairs. They are like function, and when you pass in the “key,” you can “value” as a return. Then we are ordering the colors according to the keys.
Thirdly, we are passing those colors in the rgb_to_hex function so that we can get the hex values of the colors.
And lastly, the visualization of the result. I decided to go with a pie chart, which will be helpful to understand the weight of each color in the whole picture. After plotting the figure, I am also saving it into the computer using the savefig method. This way, we have a record of the result.
Before we move to the final step, I would like to share a compelling article related to our computer vision project: Object Detection via Color-based Image Segmentation using Python by Salma Ghoneim.
Almost done! We got the behind-the-scenes ready. Now we can get to the action part. We have the image defined earlier and assigned to the “image” variable. We will call the prep_image function to preprocess the image.
modified_image = prep_image(image)color_analysis(modified_image)
Congratulations! We have created a program that analyzes an image and returns the color report as a plot. One exciting feature is that we can define how many clusters we want to divide the colors into. I used five clusters, but feel free to try the model with different values. And the rest is done with Scikit-learn K-means model prediction and OpenCV.
Here comes the final result:
Hoping that you enjoyed reading this article and learned something new today. Working on hands-on programming projects is the best way to sharpen your coding skills. Feel free to reach me if you have any questions while implementing the code.
Let’s connect. Check my blog and youtube to stay inspired. Thank you,