Dominant Color Extraction
September 26, 2022
#!/usr/bin/env python
# coding: utf-8
# http://www.pillalamarri.in/python/dominant-color-extraction/
# In[1]:
import numpy as np
import matplotlib.pyplot as plt
import cv2
# In[2]:
img= cv2.imread("images/1-Saint-Basils-Cathedral.jpg")
# In[3]:
img.shape
# In[4]:
plt.imshow(img)
plt.show()
# In[5]:
img.shape
all_pixels=img.reshape((-1,3))
all_pixels.shape
all_pixels.shape
# # Visualizing The Image through K-Means sklearn
# In[6]:
from sklearn.cluster import KMeans
# In[7]:
k=9
km=KMeans(n_clusters=k)
# In[8]:
km.fit(all_pixels)
# In[9]:
km.cluster_centers_
# In[10]:
centers=np.array(km.cluster_centers_,dtype="uint")
#uint8 to represent number btw 0-255 8 bit integer is sufficient
# In[11]:
centers
# ### plot all these color ( data centres)
# In[12]:
for c in centers:
a=np.zeros((100,100,3))
a[:,:,:]=c
plt.imshow(a/255)
plt.axis("off")
plt.show()
# In[13]:
km.labels_
# In[14]:
new_img = np.zeros((all_pixels.shape[0], 3), dtype="uint")
# In[15]:
new_img.shape
# In[16]:
# giving appropriate colors to the pixel/data points of new image
for ix in range(all_pixels.shape[0]): #pic colors from centre and map it according to labels
new_img[ix] = centers[km.labels_[ix]]
# or we can do it like this by using plt.figure and creating list of all colors
# In[17]:
i= 1
plt.figure(0,figsize=(10,2)) #fig size
colors = []
for each_col in centers:
plt.subplot(1,len(centers),i) # 1 row 9 col
plt.axis("off")
i+=1 #everytime we go to next box we increment it!
colors.append(each_col)
#Color Swatch
a = np.zeros((100,100,3),dtype='uint')
a[:,:,:] = each_col
plt.imshow(a)
plt.show()
for ix in range(new_img.shape[0]):
new_img[ix] = colors[km.labels_[ix]]
new_img = new_img.reshape((img.shape))
plt.imshow(new_img)
plt.show()
# In[18]:
new_img = new_img.reshape((600,394,3))
# In[19]:
plt.imshow(new_img)
plt.show()
# In[20]:
def plot_colors(hist, centroids):
# initialize the bar chart representing the relative frequency
# of each of the colors
bar = np.zeros((50, 300, 3), dtype = "uint8")
startX = 0
# loop over the percentage of each cluster and the color of
# each cluster
for (percent, color) in zip(hist, centroids):
#The zip() function returns an
#iterator of tuples based on the iterable objects
# plot the relative percentage of each cluster
#zip() returns an iterator of
#tuples with each tuple having only one element.
endX = startX + (percent * 300)
cv2.rectangle(bar, (int(startX), 0), (int(endX), 50),
color.astype("uint8").tolist(), -1)
startX = endX
# return the bar chart
return bar
# In[21]:
numLabels = np.arange(0, len(np.unique(km.labels_)) + 1)
(hist, _) = np.histogram(km.labels_, bins = numLabels)
# normalize the histogram, such that it sums to one
hist = hist.astype("float")
hist /= hist.sum()
# In[22]:
bar = plot_colors(hist, km.cluster_centers_)
# show our color bart
plt.imshow(img)
plt.axis("off")
plt.imshow(bar)
plt.show()
# In[23]:
img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
plt.imshow(img)
plt.show()
# In[24]:
img.shape
# In[25]:
all_pixels=img.reshape((-1,3))
# In[26]:
from sklearn.cluster import KMeans
k=9
km=KMeans(n_clusters=k)
#so it will take color from cluster and find color
km.fit(all_pixels)
km.cluster_centers_ #center we have in decimal
#so rgb(14.91798497, 17.94468754, 13.52473915)<== are some color as these ar some dominant points
# In[27]:
centers=np.array(km.cluster_centers_,dtype="uint") #so changing it in integers
#centers==>color
centers
# In[28]:
for c in centers:
a=np.zeros((100,100,3)) #image
a[:,:,:]=c #so image will broadcast into a of the cluster center from img
plt.imshow(a/255) #a should be in 0 and 1
plt.axis("off") #removing axis
plt.show()
# In[29]:
km.labels_#it will give cluster number associated with a cluster
km.labels_.shape #showing number of cluster
# In[30]:
new_img = np.zeros((all_pixels.shape[0], 3), dtype="uint")
new_img
# In[31]:
new_img.shape
#you have same shape of image eariler of Pixels
# In[32]:
# giving appropriate colors to the pixel/data points of new image
for ix in range(all_pixels.shape[0]):
new_img[ix] = centers[km.labels_[ix]]
#in this we are iterating over all the points of image alloting all the color we have to new image
#colors are in center
# In[37]:
new_img = new_img.reshape((600, 394,3))
plt.imshow(img)
plt.axis('off')
plt.show()
plt.axis('off')
plt.imshow(new_img)
plt.show()
# In[ ]:
# In[ ]:
http://www.pillalamarri.in/python/dominant-color-extraction/
Posted in Python