I use Floyd-Steinberg dithering in order to diffuse the quantization error after processing an image with KMeans from scipy. The given data is RGB file - both for grayscale and color. The problem is the visualisation - I get no dithering.
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
im = Image.open('file.png').convert('RGB')
pic = np.array(im, dtype = np.float)/255
im.close()
I would like to omit the KMeans part and focus on Floyd-Steinberg:
"""pic - as above, original array; image - processed image"""
def dither(pic, image):
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] #Quantization error
Floyd[i][j + 1] = quan * (np.float(7 / 16)) + Floyd[i][j + 1]
Floyd[i + 1][j - 1] = quan * (np.float(3 / 16)) + Floyd[i + 1][j - 1]
Floyd[i + 1][j] = quan * (np.float(5 / 16)) + Floyd[i + 1][j]
Floyd[i + 1][j + 1] = quan * (np.float(1 / 16)) + Floyd[i + 1][j + 1]
return Floyd
Floyd = dither(pic, image)
plt.imshow(Floyd)
plt.show()
I receive a little dithering when I replace Floyd with pic, i.e. Floyd[i + 1][j] = quan * (np.float(5 / 16)) + pic[i + 1][j]
. However, this is improper code! Additionally, I have to deal with colours out of the clusters, thus I again assess the new pixels to clusters. How can I make it work? Where is THIS crucial mistake?