gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:49:25 25 4
gpt4 key购买 nike

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

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'

快速谷歌搜索让我找到了this link我将导入更改为

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

open(fp, mode='r')

Opens and identifies the given image file.

This is a lazy operation; this function identifies the file, but the file remains open and the actual image data is not read from the file until you try to process the data (or call the PIL.Image.Image.load method). See PIL.Image.new.

fp: A filename (string), pathlib.Path object, or a file object. The file object must implement file.read, file.seek, and file.tell methods, and be opened in binary mode.

returns: a PIL.Image.Image object.

关于python - PIL.Image 和 PIL.Image.Image 之间的混淆以及它们的正确使用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50880443/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com