-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcolor_quantization.py
59 lines (49 loc) · 1.74 KB
/
color_quantization.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import sys
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.utils import shuffle
from time import time
from skimage import io
n_colors = int(sys.argv[1])
filename = ['image2.jpg','image3.jpg','image5.jpg']
# Load the image
for i in range(0,3):
image = io.imread("input/"+ filename[i])
image = np.array(image, dtype=np.float64) / 255
# Load Image and transform to a 2D numpy array.
w, h, d = original_shape = tuple(image.shape)
assert d == 3
image_array = np.reshape(image, (w * h, d))
t0 = time()
image_array_sample = shuffle(image_array, random_state=0)[:1000]
kmeans = KMeans(n_clusters=n_colors, random_state=0).fit(image_array_sample)
print("done in %0.3fs." % (time() - t0))
# Get labels for all points
t0 = time()
labels = kmeans.predict(image_array)
print("done in %0.3fs." % (time() - t0))
def recreate_image(codebook, labels, w, h):
"""Recreate the (compressed) image from the code book & labels"""
d = codebook.shape[1]
image = np.zeros((w, h, d))
label_idx = 0
for i in range(w):
for j in range(h):
image[i][j] = codebook[labels[label_idx]]
label_idx += 1
return image
# Display all results, alongside original image
plt.figure(1)
plt.clf()
plt.axis('off')
plt.title('Original image')
plt.imshow(image)
plt.figure(2)
plt.clf()
plt.axis('off')
plt.title('Compressed image')
recreated_image = recreate_image(kmeans.cluster_centers_, labels, w, h)
plt.imshow(recreated_image)
io.imsave('quantizedImages/'+ filename[i],recreated_image)
plt.show()