1

I'm trying to do some image processing in python.

I'm using Pillow 8.4.0 for this purpose and I need to work on individual pixels (here I'm just trying to save pixels in a text file), therefore I'm trying to use Image.load() method and looping over it but it is throwing IndexError: image index out of range

Is there a limitation in Image.load() function that is preventing me to do this?

from PIL import Image

with Image.open('nature.jpg') as img:
    print("Image size is : " ,img.size)
    
    pixels = img.load()
    
    with open('file.txt', 'w') as file:
        
        for row in range(img.height):
            for col in range(img.width):
                
                file.write(str(pixels[row, col])+ ' ')
                
            file.write('\n')

Output is:

Image size is :  (1024, 768)
Traceback (most recent call last):
  File "main.py", line 13, in <module>
    file.write(str(pixels[row, col])+ ' ')
IndexError: image index out of range
1
  • 1
    Try pixels[col,row] Commented Oct 24, 2021 at 9:11

1 Answer 1

2

Pillow expects (x,y) rather than (y,x). Please try following:

from PIL import Image
img = Image.open('nature.jpg')
pixels = img.load()
print(pixels[img.width-1,img.height-1])  # does provide tuple describing pixel
print(pixels[img.height-1,img.width-1])  # IndexError for non-square image
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.