Python:使用PIL库读取图像时发生AttributeError

时间:2018-07-12 02:24:53

标签: python image-processing pillow

我正在尝试使用PIL库处理一组图像。我在导入图像方面没有任何问题,但是,当我尝试从列表中访问第一个图像的尺寸信息时,出现错误。功能:

def loadImages(path):

    image_path = listdir(path)
    image_list = []
    for img in image_path:
        image = Image.open(path + img)
        image_list.append(image)

    return image_list

path = 'path/to/images'

images = loadImages(path)
N = len(images)
print("Number of images:", N)

w,h= Image.open(images[0]).size

以及整个错误列表:

  File "<ipython-input-42-502dda9bf243>", line 1, in <module>
    runfile('C:/Users/user/Desktop/mosaicing/vignetting/alphatrim_vs_distance.py', wdir='C:/Users/user/Desktop/mosaicing/vignetting')

  File "C:\Users\user\anaconda\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile
    execfile(filename, namespace)

  File "C:\Users\user\anaconda\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/user/Desktop/mosaicing/vignetting/alphatrim_vs_distance.py", line 39, in <module>
    w,h= Image.open(images[0]).size

  File "C:\Users\user\anaconda\Anaconda3\lib\site-packages\PIL\Image.py", line 2557, in open
    prefix = fp.read(16)

AttributeError: 'MpoImageFile' object has no attribute 'read'

我正在努力: 枕头5.0.0 python 3.6.4

1 个答案:

答案 0 :(得分:0)

好像您正在尝试打开图像两次。进入loadImage后,您尝试在以后执行以下操作时打开Image.open返回的内容(已经是图像):

w,h = Image.open(images[0]).size

由于images[0] = Image.open(path + listdir(path)[0]),您实际上在上述行中执行了以下操作:

w,h = Image.open(Image.open(path + listdir(path)[0])).size

您应该能够:

w, h = images[0].size