为什么'_io.BufferedRandom'对象没有属性'resize'

why'_io.BufferedRandom' object has no attribute 'resize'

我正在使用 PIL,但收到此错误消息:

AttributeError: '_io.BufferedRandom' object has no attribute 'resize'

我的代码:

def phash(img):
    img = img.resize((8, 8), Image.ANTIALIAS).convert('L')
    avg = reduce(lambda x, y: x + y, img.getdata()) / 64.
    return reduce(
        lambda x, y, z: x | (z << y),
        enumerate(map(lambda i: 0 if i < avg else 1, img.getdata())),
        0
    )

您分享的代码只包含函数的定义,我认为问题出在您的主要代码上。
您收到的错误消息显示您尝试调整大小的对象没有此功能,因此 我认为您不小心使用命令 open('path/to/image.png') 加载了图像,当您需要使用命令 Image.open('path/to/image.png').

将其加载为 'Image' 对象时

试试这样写:

from PIL import Image
from functools import reduce


def phash(img):
    pass # your function here

path = 'path/to/image.png'
image = Image.open(path)
phash = phash(image)