Homework 3 Problem 5


In [1]:
import numpy as np
import matplotlib.pyplot as plt
import kmeans

KCENTROIDS = 16
MAX_ITERS = 200
EPSILON = 1e-7

Part 5.a.

Here we load the large mandrill image and display it.


In [2]:
Ilarge = plt.imread('mandrill-large.tiff')
Ilarge = np.uint8(np.round(Ilarge))

In [3]:
plt.imshow(Ilarge)
plt.show()


Part 5.b.

Here we load the small mandrill image and display it.


In [3]:
Ismall = plt.imread('mandrill-small.tiff')
Ismall = np.uint8(np.round(Ismall))

In [4]:
plt.imshow(Ismall)
plt.show()


Now apply the K-Means algorithm with k centroids to the small image.


In [5]:
clusters_small, centroids_small = kmeans.kmeans(Ismall, kcentroids=KCENTROIDS, epsilon=EPSILON, max_iterations=200)

The color palette obtained by running K-Means is the following.


In [6]:
plt.imshow(np.array([centroids_small]))
plt.show()



In [7]:
new_image_small = kmeans.make_image(clusters_small, centroids_small)

In [8]:
plt.imshow(new_image_small)
plt.show()


Part 5.c.

Do the same as above for the large mandrill image.


In [10]:
clusters_large, centroids_large = kmeans.kmeans(Ilarge, kcentroids=KCENTROIDS, epsilon=EPSILON, max_iterations=MAX_ITERS)

In [11]:
new_image_large = kmeans.make_image(clusters_large, centroids_large)

In [12]:
plt.imshow(new_image_large)
plt.show()


Part 5.d.

The original image requires 24 bits per pixel to represent the image. Compressing the representation to 16 colors using K-Means clustering requires log2(16) = 4 bits per pixel. The resulting compression factor is 24 / 4 = 6.


In [ ]: