Home > Back-end >  Floyd-Steinberg dithering algorithm getting out of bounds
Floyd-Steinberg dithering algorithm getting out of bounds

Time:04-08

I have a problem with Floyd-Steinberg dithering algorithm in Python. It keeps getting out of bounds on its width. I've checked many sources and I can't figure out where is the mistake... Here is my code:

def floydSteinberg(src, colorPalette):
src = src.copy()
h,w = src.shape[:2]
for y in range(h):
    for x in range(w):
        oldpixel = src[x][y]
        newpixel = colorFit(oldpixel, colorPalette)
        src[x][y] = newpixel
        quant_error = oldpixel - newpixel
        if (x<w-1):
            src[x 1][y] = src[x 1][y]   quant_error * 7/16
        if (x>0) and (y<h-1):
            src[x-1][y 1] = src[x-1][y 1]   quant_error * 3/16
        if (y<h-1):
            src[x][y 1] = src[x][y 1]   quant_error * 5/16
        if (x<w-1) and (y<h-1):
            src[x 1][y 1] = src[x 1][y 1]   quant_error * 1/16     
return src

And the error:

line 33, in floydSteinberg
src[x][y 1] = src[x][y 1] quant_error * 5/16 IndexError: index 180 is out of bounds for axis 0 with size 180

Tested image is 180px wide. I also tried substracting 1 from w or h in for loop, but it does not help at all (just to see if that will do something)

CodePudding user response:

Your height and width seem to be swapped. Try changing:

h,w = src.shape[:2]

to:

w, h = src.shape[:2]

and it should work.

  • Related