Click here to Skip to main content
15,868,141 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This is my code:
Python
for y in range(0, dim, 3):
    for x in range(0, dim, 4):
        img.putpixel((x, y), color2)
        if not (x+1 > dim):
            img.putpixel((x+1, y), color2)
        if not (x+2 > dim):
            img.putpixel((x+2, y), color2)
        if not ((x+2 > dim) and (y+1 > dim)):
            img.putpixel((x+2, y+1), color2)

I am trying to make a sharkskin pattern by drawing pixels, but keep getting "IndexError: image index out range." I literally have the whole if not () check there so it doesn't. Why does it not respect that statement, oh and btw dim is the dimension of the image (same on both axis)

What I have tried:

I have tried adding a function checking so it doesn't happen, but it still does.
Posted
Updated 31-Dec-21 8:53am
Comments
0x01AA 31-Dec-21 14:19pm    
I guess all your comparisons if not (x+1 > dim) should be if not (x+1 >= dim)

1 solution

Python indexes start from zero - so if you have 5 elements in a collection, the only valid indexes are 0, 1, 2, 3, and 4 - any negative number or value greater than four will cause an index out of range error.

Pixels are organised the same way: so unless your image is exactly square and has dim values in both x and y directions, your code will fail because you access the pixel using the index plus one. I'd suggest using the debugger to check the image dimensions, and think about why your code is trying to access x + 1 and y + 1 at all!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900