I am trying to implement floyd-steinberg dithering algorithm in python but I have problems with the final output and I cant find out what is wrong because it's based on the pseudo-code on wikipedia.
The function to find closest value:
def closest(val):
legit = np.array([0, 255])
vals = np.array([val for i in range(len(legit))])
diffs = np.abs(vals - legit)
return legit[np.argmin(diffs)]
And here is the floyd-steinberg implementation:
def floyd(img):
img = img.copy()
height, width = img.shape
for i in range(height):
for j in range(width):
oldpixel = img[i, j]
newpixel = closest(oldpixel)
img[i, j] = newpixel
quant_error = oldpixel - newpixel
neighbors_and_weights = [
(i, j+1, 7.0/16), # right
(i+1, j-1, 3.0/16), # bottom left
(i+1, j, 5.0/16), # bottom
(i+1, j+1, 1.0/16) # bottom right
]
for nw in neighbors_and_weights:
x, y, w = nw
if (0 <= x < height) and (0 <= y < width):
img[x][y] += quant_error * w
return img