Python PIL.Image和PIL.Image.Image之间的混淆以及正确的使用方法?

Python PIL.Image和PIL.Image.Image之间的混淆以及正确的使用方法?,python,image,python-imaging-library,Python,Image,Python Imaging Library,我试着做一些简单的图像处理。这是密码 from PIL.Image import Image def get_image_half(image, half="upper"): if half not in ["upper", "lower", "right", "left"]: raise Exception('Not a valid image half') img = Image.open(image) width, height = img.

我试着做一些简单的图像处理。这是密码

from PIL.Image import Image


def get_image_half(image, half="upper"):

    if half not in ["upper", "lower", "right", "left"]:
        raise Exception('Not a valid image half')

    img = Image.open(image)
    width, height = img.size

    if half == "upper":
        return img.crop(0, 0, width, height//2)
    elif half == "lower":
        return img.crop(0, height//2, width, height)
    elif half == "left":
        return img.crop(0, 0, width//2, height)
    else:
        return img.crop(width//2, 0, width, height)


def get_image_quadrant(image, quadrant=1):

    if not (1 <= quadrant <= 4):
        raise Exception("Not a valid quadrant")

    img = Image.open(image)
    width, height = img.size

    if quadrant == 2:
        return img.crop(0, 0, width//2, height//2)
    elif quadrant == 1:
        return img.crop(width//2, 0, width, height//2)
    elif quadrant == 3:
        return img.crop(0, height//2, width//2, height)
    else:
        return img.crop(width//2, height//2, width, height)

# test code for the functions


if __name__ == "__main__":

    import os

    dir_path = os.path.dirname(os.path.realpath(__file__))
    file = os.path.join(dir_path,"nsuman.jpeg")
    image = Image.open(file)

    for i in ["upper", "lower", "left", "right"]:
        get_image_half(image, i).show()

    for i in range(1,5):
        get_image_quadrant(image, quadrant=i)
快速的谷歌搜索让我找到了,我将导入改为

import PIL.Image
并将代码更改为

PIL.Image.open(image)
这又是一个错误

Traceback (most recent call last):
  File "quadrant.py", line 53, in <module>
    get_image_half(image, i).show()
  File "quadrant.py", line 10, in get_image_half
    img = Image.open(image)
  File "/usr/lib/python3/dist-packages/PIL/Image.py", line 2557, in open
    prefix = fp.read(16)
AttributeError: 'JpegImageFile' object has no attribute 'read'
回溯(最近一次呼叫最后一次):
文件“quadrant.py”,第53行,在
获取图像(图像,i).show()
文件“quadrant.py”,第10行,在get_image_half中
img=Image.open(图像)
文件“/usr/lib/python3/dist packages/PIL/Image.py”,第2557行,打开
前缀=fp.read(16)
AttributeError:'JpegImageFile'对象没有属性'read'

这里的问题是如何解决这些错误,更重要的是什么是PIL.Image和PIL.Image.Image,以及如何正确使用它们?

PIL.Image
应该打开一个文件类型对象。打开后,将有一个PIL.Image.Image对象:

from PIL import Image

image = Image.open('/foo/myfile.png')
打开(fp,模式='r')

打开并标识给定的图像文件

这是一个懒惰的操作;此函数用于标识文件,但文件保持打开状态,在您尝试处理数据(或调用PIL.image.image.load方法)之前,不会从文件中读取实际图像数据。见PIL.Image.new

fp:文件名(字符串)、pathlib.Path对象或文件对象。file对象必须实现file.read、file.seek和file.tell方法,并以二进制模式打开

返回:一个PIL.Image.Image对象


是 啊我现在明白了,它修复了错误。谢谢
from PIL import Image

image = Image.open('/foo/myfile.png')