In [1]:
%matplotlib inline
In [2]:
# goal is to blur an image with clustering
In [8]:
from scipy import ndimage
import matplotlib.pyplot as plt
In [9]:
img = ndimage.imread("headshot.jpg")
In [10]:
plt.imshow(img)
Out[10]:
In [11]:
img.shape
Out[11]:
In [12]:
# to quantize an image we need to convert it to a 2 dimensional
# matrix with length being Height x Width of the image and the
# rows of the matrix being the RGB values
In [13]:
x,y,z = img.shape
In [14]:
long_img = img.reshape(x*y,z)
In [15]:
long_img.shape
Out[15]:
In [16]:
# we want 5 distinct colors so set n_clusters to 5
from sklearn import cluster
In [22]:
kmeans = cluster.KMeans(n_clusters=5)
kmeans.fit(long_img)
Out[22]:
In [23]:
centers = kmeans.cluster_centers_
In [24]:
centers
Out[24]:
In [25]:
labels = kmeans.labels_
labels[:5]
Out[25]:
In [26]:
plt.imshow(centers[labels].reshape(x,y,z))
Out[26]:
In [ ]: