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
| import os
import numpy as np
from matplotlib import pyplot as plt
import urllib.request
from PIL import Image
from collections import Counter
from sklearn.cluster import KMeans
# Utility function, rgb to hex
def rgb2hex(rgb):
print(rgb)
hex = "#{:02x}{:02x}{:02x}".format(int(rgb[0]), int(rgb[1]), int(rgb[2]))
return hex
PATH = 'ted.jpg'
WIDTH = 128
HEIGHT = 128
CLUSTERS = 5
image = Image.open(PATH)print(image.size)
# print("Loaded {f} image. Size: {s:.2f} KB. Dimensions: ({d})".format(
# f=image.format, s=os.path.getsize(PATH) / 1024, d=image.size))
def calculate_new_size(image):
if image.width >= image.height:
wpercent = (WIDTH / float(image.width))
hsize = int((float(image.height) * float(wpercent)))
new_width, new_height = WIDTH, hsize
else:
hpercent = (HEIGHT / float(image.height))
wsize = int((float(image.width) * float(hpercent)))
new_width, new_height = wsize, HEIGHT
return new_width, new_height
new_width, new_height = calculate_new_size(image)
print(new_width)
print(new_height)
image.resize((new_width, new_height), Image.ANTIALIAS)
image = image.resize((new_width, new_height), Image.ANTIALIAS)
img_array = np.array(image)
img_vector = img_array.reshape((img_array.shape[0] * img_array.shape[1], 3))
model = KMeans(n_clusters=CLUSTERS)
labels = model.fit_predict(img_vector)
label_counts = Counter(labels)
total_count = sum(label_counts.values())
plt.figure(figsize=(14, 8))
plt.subplot(221)
plt.imshow(image)
plt.axis('off')
hex_colors = [
rgb2hex(center) for center in model.cluster_centers_
]
print(hex_colors) |
Partager