我正在努力做简单的图像裁剪。这是代码
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'
快速Google搜索引导我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以及使用它们的正确方法是什么?
答案 0 :(得分:2)
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对象。