I am trying to implement Floyd-Steinberg dithering in Python after using KMeans. I realised, that after dithering I receive colours which are not included in the reduced palette, so I modify the image again with KMeans. However, when trying with this picture, I see no dithering at all. I got stucked, I got tired - please, help me. My ideas become almost extinct.
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
k = 16
im = Image.open('Image.png').convert('RGB') #Image converted to RGB
pic = np.array(im, dtype = np.float)/255 #Enables imshow()
im.close()
def kmeans(pic): #Prepares algorithmic data
v, c, s = pic.shape
repic = np.resize(pic, (c*v, 3))
kme = KMeans(n_clusters = k).fit(repic)
cl = kme.cluster_centers_
return kme, cl, repic, v, c
kme, cl, repic, v, c = kmeans(pic)
pred = kme.predict(repic)
def picture(v, c, cl, pred): #Creates a picture with reduced colors
image = np.ones((v, c, 3))
ind = 0
for i in range(v):
for j in range(c):
image[i][j] = cl[pred[ind]]
ind+=1
return image
image = picture(v, c, cl, pred)
def dither(pic, image): #Floyd-Steinberg dithering
v, c, s = pic.shape
Floyd = np.copy(image)
for i in range(1, v-1):
for j in range(1, c-1):
quan = pic[i][j] - image[i][j]
Floyd[i][j + 1] = quan * (np.float(7 / 16)) + pic[i][j + 1]
Floyd[i + 1][j - 1] = quan * (np.float(5 / 16)) + pic[i + 1][j - 1]
Floyd[i + 1][j] = quan * (np.float(3 / 16)) + pic[i + 1][j]
Floyd[i + 1][j + 1] = quan * (np.float(1 / 16)) + pic[i + 1][j + 1]
return Floyd
fld = dither(pic, image)
a1, a2, reim, a3, a4 = kmeans(fld)
lab = kme.predict(reim)
Floyd = picture(v, c, cl, lab)
plt.imshow(Floyd)
plt.show()