Python Pillow Image.load() 方法有局限性?

Python Pillow Image.load() method has limitations?

我正尝试在 python 中进行一些图像处理。

我为此目的使用 Pillow 8.4.0,我需要处理单个像素(这里我只是试图将像素保存在文本文件中),因此我尝试使用 Image.load() 方法并对其进行循环,但它抛出 IndexError: image index out of range

Image.load() 函数是否有限制阻止我这样做?

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')

输出为:

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

Pillow 期望 (x,y) 而不是 (y,x)。请尝试以下操作:

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