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

用户名

我正在尝试对图像进行简单裁剪。这是代码

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)

我收到以下错误。

image = Image.open(file)
AttributeError: type object 'Image' has no attribute 'open'

快速谷歌搜索使我转到此链接,并将导入更改为

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'

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

巴克

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

from PIL import Image

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

打开(fp,mode ='r')

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

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

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章