I'm currently trying to code Floyd-Steinberg dithering in python When trying to add colour in Floyd-Steinberg dithering, you have to calculate the "quantization error" of 2 tuples. How would I go about doing this? Converting them to grayscale doesn't produce good results, and I'm not sure how I would get it to work. I don't want help with any other part of my code, just the quantization error. Here is my code :
from PIL import Image
import sys,math
imag = Image.open(sys.argv[1])
palette = [(0,0,0,255),(255,255,255,255),(255,0,0,255),(0,255,0,255),(0,0,255,255)]
def distance(co1, co2):
return pow(abs(co1[0] - co2[0]), 2) + pow(abs(co1[1] - co2[2]), 2)
def palcol(col,pal):
return min(pal, key=lambda x: distance(x, col))
for y in range(imag.height-1):
for x in range(imag.width-1):
oldpixel = imag.getpixel((x,y))[0] * 299/1000 + imag.getpixel((x,y))[1] * 587/1000 + imag.getpixel((x,y))[2] * 114/1000
newpixel = palcol(imag.getpixel((x,y)),palette)[0] * 299/1000 + palcol(imag.getpixel((x,y)),palette)[1] * 587/1000 + palcol(imag.getpixel((x,y)),palette)[2] * 114/1000
querror = oldpixel - newpixel
newpixel = palcol(imag.getpixel((x,y)),palette)
imag.putpixel((x,y),newpixel)
imag.putpixel((x + 1,y ),tuple([round(imag.getpixel((x + 1,y ))[0] + (querror*7/16)),round(imag.getpixel((x + 1,y ))[1] + (querror*7/16)),round(imag.getpixel((x + 1,y ))[2] + (querror*7/16)),255]))
imag.putpixel((x - 1,y + 1),tuple([round(imag.getpixel((x - 1,y + 1))[0] + (querror*3/16)),round(imag.getpixel((x - 1,y + 1))[1] + (querror*3/16)),round(imag.getpixel((x - 1,y + 1))[2] + (querror*3/16)),255]))
imag.putpixel((x ,y + 1),tuple([round(imag.getpixel((x ,y + 1))[0] + (querror*5/16)),round(imag.getpixel((x ,y + 1))[1] + (querror*5/16)),round(imag.getpixel((x ,y + 1))[2] + (querror*5/16)),255]))
imag.putpixel((x + 1,y + 1),tuple([round(imag.getpixel((x + 1,y + 1))[0] + (querror*1/16)),round(imag.getpixel((x + 1,y + 1))[1] + (querror*1/16)),round(imag.getpixel((x + 1,y + 1))[2] + (querror*1/16)),255]))
imag.show()