# import the necessary packages
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import numpy as np
import argparse
import cv2
# ----------------------------------------------------
## OpenCV and Python K-Means Color Clustering
# ----------------------------------------------------
# load the image and convert it from BGR to RGB so that we can dispaly it with matplotlib
image1 = cv2.imread('python.jpg')
image1 = cv2.cvtColor(image1, cv2.COLOR_BGR2RGB)
# show our image
plt.figure()
plt.axis("on")
plt.imshow(image1)
# Image 2
image2 = cv2.imread('python_one.jpg')
image2 = cv2.cvtColor(image2, cv2.COLOR_BGR2RGB)
# show our image
plt.figure()
plt.axis("on")
plt.imshow(image2)
<matplotlib.image.AxesImage at 0x7f5bc49e4fd0>
# reshape the image to be a list of pixels
image1 = image1.reshape((image1.shape[0] * image1.shape[1], 3))
image2 = image2.reshape((image2.shape[0] * image2.shape[1], 3))
# cluster the pixel intensities
clt1 = KMeans(n_clusters = 6)
clt1.fit(image1)
KMeans(n_clusters=6)
clt2 = KMeans(n_clusters = 5)
clt2.fit(image2)
KMeans(n_clusters=5)
def centroid_histogram(clt):
# grab the number of different clusters and create a histogram
# based on the number of pixels assigned to each cluster
numLabels = np.arange(0, len(np.unique(clt.labels_)) + 1)
(hist, _) = np.histogram(clt.labels_, bins = numLabels)
# normalize the histogram, such that it sums to one
hist = hist.astype("float")
hist /= hist.sum()
# return the histogram
return hist
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):
# plot the relative percentage of each cluster
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
# build a histogram of clusters and then create a figure
# representing the number of pixels labeled to each color
hist = centroid_histogram(clt1)
bar = plot_colors(hist, clt1.cluster_centers_)
# show our color bart
plt.figure()
plt.axis("off")
plt.imshow(bar)
plt.show()
# build a histogram of clusters and then create a figure
# representing the number of pixels labeled to each color
hist = centroid_histogram(clt2)
bar = plot_colors(hist, clt2.cluster_centers_)
# show our color bart
plt.figure()
plt.axis("off")
plt.imshow(bar)
plt.show()
In this coding recipe, we discussed Basic Color Clustering using Python K-Means.
Specifically, we have learned the followings: